diff --git a/.github/actions/setup-android-replay-host/action.yml b/.github/actions/setup-android-replay-host/action.yml index 3db790a624f..041c716249b 100644 --- a/.github/actions/setup-android-replay-host/action.yml +++ b/.github/actions/setup-android-replay-host/action.yml @@ -36,7 +36,7 @@ runs: run: | VERSION="$(node -p 'require("./package.json").version')" echo "version=$VERSION" >> "$GITHUB_OUTPUT" - echo "value=${{ hashFiles('android/snapshot-helper/AndroidManifest.xml', 'android/snapshot-helper/debug.keystore', 'android/snapshot-helper/src/**', 'android/ime-helper/AndroidManifest.xml', 'android/ime-helper/res/**', 'android/ime-helper/src/**', 'scripts/build-android-helper.sh', 'scripts/package-android-helper.sh', '.github/actions/setup-android-replay-host/action.yml', '.github/actions/setup-android-sdk/action.yml') }}" >> "$GITHUB_OUTPUT" + echo "value=${{ hashFiles('android/snapshot-helper/AndroidManifest.xml', 'android/snapshot-helper/src/**', 'android/ime-helper/AndroidManifest.xml', 'android/ime-helper/res/**', 'android/ime-helper/src/**', 'scripts/build-android-helper.sh', 'scripts/package-android-helper.sh', '.github/actions/setup-android-replay-host/action.yml', '.github/actions/setup-android-sdk/action.yml') }}" >> "$GITHUB_OUTPUT" shell: bash # The helper build refuses to guess its build-tools version on CI, and that version decides @@ -45,6 +45,8 @@ runs: - name: Setup Android SDK if: inputs.package-helpers == 'true' uses: ./.github/actions/setup-android-sdk + with: + ephemeral-helper-signing: 'true' - name: Restore packaged Android helpers if: inputs.package-helpers == 'true' diff --git a/.github/actions/setup-android-sdk/action.yml b/.github/actions/setup-android-sdk/action.yml index c08e263fcdd..17536668471 100644 --- a/.github/actions/setup-android-sdk/action.yml +++ b/.github/actions/setup-android-sdk/action.yml @@ -13,6 +13,10 @@ inputs: description: 'Install the API 36 x86_64 Play Store emulator image' required: false default: 'false' + ephemeral-helper-signing: + description: 'Generate a run-scoped helper signing key for non-release CI builds' + required: false + default: 'false' outputs: build-tools-dir: @@ -76,3 +80,24 @@ runs: echo "AGENT_DEVICE_ANDROID_BUILD_TOOLS=$BUILD_TOOLS_VERSION" >> "$GITHUB_ENV" echo "build-tools-dir=$BUILD_TOOLS_DIR" >> "$GITHUB_OUTPUT" echo "system-image-dir=$SYSTEM_IMAGE_DIR" >> "$GITHUB_OUTPUT" + + - name: Generate ephemeral Android helper signing key + if: inputs.ephemeral-helper-signing == 'true' + shell: bash + run: | + set -euo pipefail + KEYSTORE="$RUNNER_TEMP/agent-device-ci-helper-${GITHUB_RUN_ID}-${GITHUB_JOB}.jks" + keytool -genkeypair \ + -keystore "$KEYSTORE" \ + -storepass agent-device-ci-only \ + -keypass agent-device-ci-only \ + -alias agent-device-ci-helper \ + -keyalg RSA \ + -keysize 2048 \ + -validity 1 \ + -dname 'CN=Agent Device CI Helper, O=Callstack, C=PL' + chmod 600 "$KEYSTORE" + echo "AGENT_DEVICE_ANDROID_KEYSTORE=$KEYSTORE" >> "$GITHUB_ENV" + echo "AGENT_DEVICE_ANDROID_KEY_ALIAS=agent-device-ci-helper" >> "$GITHUB_ENV" + echo "AGENT_DEVICE_ANDROID_KEYSTORE_PASSWORD=agent-device-ci-only" >> "$GITHUB_ENV" + echo "AGENT_DEVICE_ANDROID_KEY_PASSWORD=agent-device-ci-only" >> "$GITHUB_ENV" diff --git a/.github/workflows/release-android-snapshot-helper.yml b/.github/workflows/release-android-snapshot-helper.yml index b87afd6f2f7..4e3d63c1500 100644 --- a/.github/workflows/release-android-snapshot-helper.yml +++ b/.github/workflows/release-android-snapshot-helper.yml @@ -1,7 +1,6 @@ name: Release Android Snapshot Helper on: - # release.yml calls this after publishing a stable release; dispatch reruns it for one tag. workflow_call: inputs: release_tag: @@ -14,89 +13,16 @@ on: description: GitHub Release tag to upload assets to, for example v0.13.3. required: true type: string - checkout_ref: - description: Optional branch, tag, or commit SHA to build. Defaults to the selected workflow ref. - required: false - type: string -permissions: - contents: write +permissions: {} jobs: publish-android-snapshot-helper: - name: Publish Android Snapshot Helper - runs-on: blacksmith-4vcpu-ubuntu-2404 - timeout-minutes: 30 + name: Block Android Snapshot Helper release until signing is isolated + runs-on: ubuntu-24.04 + timeout-minutes: 5 steps: - - name: Checkout - uses: useblacksmith/checkout@2b9fe87d796feea153b455ec2f3125b471a7b0e7 # v1.8.2 - with: - ref: ${{ inputs.checkout_ref || github.ref }} - - - name: Checkout release validator - uses: useblacksmith/checkout@2b9fe87d796feea153b455ec2f3125b471a7b0e7 # v1.8.2 - with: - repository: ${{ job.workflow_repository }} - ref: ${{ job.workflow_sha }} - path: .release-validator - sparse-checkout: scripts/release-version.mjs - sparse-checkout-cone-mode: false - persist-credentials: false - - - name: Setup Node.js - uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0 - with: - node-version: '24.13' - - - name: Resolve release metadata - id: meta - env: - TAG_NAME: ${{ inputs.release_tag }} - run: | - set -euo pipefail - node .release-validator/scripts/release-version.mjs asset-tag "$TAG_NAME" - VERSION="${TAG_NAME#v}" - echo "tag=$TAG_NAME" >> "$GITHUB_OUTPUT" - echo "version=$VERSION" >> "$GITHUB_OUTPUT" - shell: bash - - # Exports AGENT_DEVICE_ANDROID_BUILD_TOOLS, which the helper build requires on CI. - - name: Setup Android SDK - uses: ./.github/actions/setup-android-sdk - - - name: Check Java toolchain - run: | - javac --version - java --version - - - name: Package Android snapshot helper - id: package - env: - RELEASE_ASSET_DIR: ${{ github.workspace }}/.tmp/release-assets - RELEASE_VERSION: ${{ steps.meta.outputs.version }} - RELEASE_TAG: ${{ steps.meta.outputs.tag }} - AGENT_DEVICE_ANDROID_HELPER: snapshot - run: | - set -euo pipefail - mkdir -p "${RELEASE_ASSET_DIR}" - sh ./scripts/package-android-helper.sh \ - "$RELEASE_VERSION" \ - "$RELEASE_TAG" \ - "${RELEASE_ASSET_DIR}" - shell: bash - - - name: Upload helper assets to GitHub Release - env: - APK_PATH: ${{ steps.package.outputs.apk_path }} - CHECKSUM_PATH: ${{ steps.package.outputs.checksum_path }} - MANIFEST_PATH: ${{ steps.package.outputs.manifest_path }} - GH_TOKEN: ${{ github.token }} - RELEASE_TAG: ${{ steps.meta.outputs.tag }} + - name: Refuse source checkout with the production signing key run: | - set -euo pipefail - gh release upload "$RELEASE_TAG" \ - "$APK_PATH" \ - "$CHECKSUM_PATH" \ - "$MANIFEST_PATH" \ - --clobber - shell: bash + echo 'Published Android helpers require an isolated signer and a stable external key. This workflow cannot sign source checkout scripts.' >&2 + exit 1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d894944efd3..7d87fdef7b9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,6 +6,8 @@ name: Release # dry-run (PR), nightly (main-owned schedule or dispatch), or stable (a vX.Y.Z tag on # main). The tag ruleset, which only admins can bypass, is the stable release's # approval: a tag publishes without another review. +# Nightly and stable publishing are paused until the Android helper has an isolated signer and +# stable external key. The build preflight fails before checkout, npm publish, or asset upload. on: pull_request: paths: @@ -88,6 +90,12 @@ jobs: env: VERSION: ${{ needs.plan.outputs.version }} steps: + - name: Pause nightly and stable release until helper signing is isolated + if: needs.plan.outputs.mode != 'dry-run' + run: | + echo 'Published Android helpers require an isolated signer and a stable external key. Release is blocked until that path is configured.' >&2 + exit 1 + - name: Checkout uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: @@ -112,6 +120,8 @@ jobs: # Exports AGENT_DEVICE_ANDROID_BUILD_TOOLS, which the helper build requires on CI. - name: Setup Android SDK uses: ./.github/actions/setup-android-sdk + with: + ephemeral-helper-signing: 'true' - name: Stamp release version run: node .release-tools/scripts/release-version.mjs stamp "$VERSION" @@ -243,7 +253,6 @@ jobs: uses: ./.github/workflows/release-ios-runner.yml with: release_tag: v${{ needs.plan.outputs.version }} - android-snapshot-helper: name: Android helper assets needs: [plan, github-release] diff --git a/.github/workflows/size.yml b/.github/workflows/size.yml index 5448ff184f4..cc94d6025be 100644 --- a/.github/workflows/size.yml +++ b/.github/workflows/size.yml @@ -51,6 +51,8 @@ jobs: # Exports AGENT_DEVICE_ANDROID_BUILD_TOOLS, which the helper build requires on CI. - name: Setup Android SDK uses: ./.github/actions/setup-android-sdk + with: + ephemeral-helper-signing: 'true' # dist is fully determined by the base commit, so reuse it across PR runs # against the same base. Startup medians are still measured fresh on this diff --git a/.gitignore b/.gitignore index c13417f7a61..df9d5d6485e 100644 --- a/.gitignore +++ b/.gitignore @@ -40,6 +40,8 @@ xcuserdata/ *.xcresult *.ipa *.apk +*.jks +*.keystore *.dSYM *.dSYM.zip *.app diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ec854ade70d..dd906f73b52 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -101,6 +101,11 @@ described below. A local `npm publish` from the repository root refuses to run. The core and every public workspace package release together at one version. Private packages stay unpublished. The workflow supports these release modes: +Nightly and stable publishing are currently paused until Android helper signing uses an isolated +signer with a stable external key. The Release build stops before npm publish or asset upload. +Pull-request dry runs still build with a disposable key. A tag or GitHub Release created by an +admin may already exist, but this paused workflow does not publish packages or attach helper assets. + - **Nightly** (`npm install -g agent-device@nightly`): once a day, at 01:23 UTC, the workflow checks `main`. It publishes `X.Y.Z-nightly..` under the `nightly` dist-tag when `main`'s HEAD has changed since the last nightly and its CI passed, waiting up to 20 minutes for diff --git a/android/ime-helper/AndroidManifest.xml b/android/ime-helper/AndroidManifest.xml index c270833e8c8..7f957d2b513 100644 --- a/android/ime-helper/AndroidManifest.xml +++ b/android/ime-helper/AndroidManifest.xml @@ -1,6 +1,6 @@ + package="com.callstack.agentdevice.imehelper.v2"> + package="com.callstack.agentdevice.snapshothelper.v2"> @@ -10,8 +10,8 @@ android:theme="@android:style/Theme.NoDisplay" /> diff --git a/android/snapshot-helper/README.md b/android/snapshot-helper/README.md index 33643d3eb4d..c8ae6390ca8 100644 --- a/android/snapshot-helper/README.md +++ b/android/snapshot-helper/README.md @@ -8,8 +8,41 @@ unavailable, it falls back to the active-window root. The helper is intentionally provider-neutral. Local `adb`, cloud ADB tunnels, and remote device providers can all install and run the same APK as long as they can execute ADB-style operations. -Released helper APKs use the committed `debug.keystore`; do not rotate it casually, because Android -requires a stable signing certificate for `adb install -r` upgrades. +The snapshot and IME helpers use rotated package identities. The release workflow is blocked until +an isolated signing stage can use a stable externally managed key. The repository does not contain a private key. +Android treats the rotated packages as new applications, so a compromised legacy package cannot +satisfy the current helper manifest or receive package-scoped host commands. + +## Signing rotation + +Generate and protect the release key outside this repository. Do not use the removed legacy key. +The release workflow must keep signing credentials away from the job that checks out and runs the +planned source commit. Before enabling releases, add a trusted signing stage that treats the build +artifact as untrusted data, validates its paths and expected APKs, signs both helpers, updates their +checksums and manifests, and uploads the final npm tarballs. Scope the key and passwords to that +stage, pin its code to the workflow commit, and verify the certificate fingerprint. The GitHub +snapshot asset must come from those same signed package bytes. Configure +`AGENT_DEVICE_ANDROID_KEYSTORE`, `AGENT_DEVICE_ANDROID_KEY_ALIAS`, +`AGENT_DEVICE_ANDROID_KEYSTORE_PASSWORD`, and `AGENT_DEVICE_ANDROID_KEY_PASSWORD` only for that stage. + +The first rotated release installs beside the legacy packages. The host addresses only +`com.callstack.agentdevice.snapshothelper.v2` and `com.callstack.agentdevice.imehelper.v2`. +After you verify both rotated helpers on a device, remove the legacy packages: + +```sh +adb uninstall com.callstack.agentdevice.snapshothelper +adb uninstall com.callstack.agentdevice.imehelper +``` + +If the legacy IME is active, select another input method before you remove it. Do not configure a +legacy helper as the restore target for a rotated helper session. Package removal is an explicit +deployment step because it changes device state and can affect an active input method. + +If close reports an invalid saved keyboard, list installed input methods with `adb shell ime list -s`. +Select a non-helper keyboard with `adb shell ime set `. Then delete the stale +`agent_device_ime_helper_previous_ime` and `agent_device_ime_helper_rebind_displaced` secure +settings with `adb shell settings delete secure `. Restart the daemon to clear its recovery +marker after it confirms that no helper is active. ## Accessibility services @@ -27,7 +60,11 @@ See [issue #4179](https://github.com/callstack/agent-device/issues/4179). ```sh VERSION="$(node -p 'require("./package.json").version')" -AGENT_DEVICE_ANDROID_HELPER=snapshot sh ./scripts/build-android-helper.sh "$VERSION" .tmp/android-snapshot-helper +# Export AGENT_DEVICE_ANDROID_KEYSTORE, AGENT_DEVICE_ANDROID_KEY_ALIAS, +# AGENT_DEVICE_ANDROID_KEYSTORE_PASSWORD, and AGENT_DEVICE_ANDROID_KEY_PASSWORD +# from your secret store before running this in a trusted signing shell. +AGENT_DEVICE_ANDROID_HELPER=snapshot sh ./scripts/build-android-helper.sh \ + "$VERSION" .tmp/android-snapshot-helper ``` The build uses Android SDK command-line tools directly. It expects `ANDROID_HOME` or @@ -35,8 +72,11 @@ The build uses Android SDK command-line tools directly. It expects `ANDROID_HOME build-tools version named by `AGENT_DEVICE_ANDROID_BUILD_TOOLS` (or the script's last positional). CI must name that version; a local build without it uses the newest version under `build-tools` and says so on stderr. -`pnpm prepack` builds the npm-bundled helper into `android/snapshot-helper/dist`; npm users get -that APK in the package and the first helper-backed `snapshot` installs it automatically when +The root `build:android-*` and `package:android-*` scripts need the same four signing values. +`pnpm prepack` reaches those scripts through release preparation and needs the values too; it +builds the npm-bundled helper into `android/snapshot-helper/dist`. +For a local test build, use a disposable caller-owned key; never use the release signing key. +Npm users get that APK in the package and the first helper-backed `snapshot` installs it when missing or outdated. ## Run @@ -50,7 +90,7 @@ adb shell am instrument -w \ -e timeoutMs 8000 \ -e maxDepth 128 \ -e maxNodes 5000 \ - com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation + com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation ``` `maxDepth` also caps recursive traversal depth inside the helper. @@ -80,11 +120,11 @@ Snapshot mode uses the idle wait configured above. ```sh # Read the interactive-window viewport without capturing a snapshot. adb shell am instrument -w -e mode viewport \ - com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation + com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation # Inject a planned touch gesture, described by a base64 JSON payload. adb shell am instrument -w -e mode gesture -e payloadBase64 "$PAYLOAD" \ - com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation + com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation ``` The `gesture` payload is a base64-encoded JSON object using protocol `android-touch-plan-v1`: diff --git a/android/snapshot-helper/debug.keystore b/android/snapshot-helper/debug.keystore deleted file mode 100644 index e61a744020d..00000000000 Binary files a/android/snapshot-helper/debug.keystore and /dev/null differ diff --git a/packages/daemon/src/core/composite-resource-admission-ime.test.ts b/packages/daemon/src/core/composite-resource-admission-ime.test.ts index 2df72c6d218..bb84b8f0369 100644 --- a/packages/daemon/src/core/composite-resource-admission-ime.test.ts +++ b/packages/daemon/src/core/composite-resource-admission-ime.test.ts @@ -16,7 +16,8 @@ import { resourceAdmissionWorld, assertRpcOk } from './composite-resource-admiss import { isDaemonIdle } from '../sessions/server/daemon-idle-reap.ts'; const originalIme = 'com.google.android.inputmethod.latin/.LatinIME'; -const helperIme = 'com.callstack.agentdevice.imehelper/.TestInputMethodService'; +const helperIme = + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService'; function gate() { let release!: () => void; @@ -283,7 +284,7 @@ function androidHelperWorld(failRestoreOnce = false) { version: '1.0.0', assetName: 'helper.apk', sha256: '0'.repeat(64), - packageName: 'com.callstack.agentdevice.imehelper', + packageName: 'com.callstack.agentdevice.imehelper.v2', versionCode: 1, serviceComponent: helperIme, broadcastProtocol: 'android-ime-helper-v2' as const, diff --git a/packages/platform-android/src/__tests__/doctor.test.ts b/packages/platform-android/src/__tests__/doctor.test.ts index 6796a43d7ef..99107dc878c 100644 --- a/packages/platform-android/src/__tests__/doctor.test.ts +++ b/packages/platform-android/src/__tests__/doctor.test.ts @@ -3,32 +3,11 @@ import { promises as fs } from 'node:fs'; import path from 'node:path'; import { afterEach, test, vi } from 'vitest'; -const HELPER_SERVICE = 'com.callstack.agentdevice.imehelper/.TestInputMethodService'; +const HELPER_SERVICE = + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService'; +const LEGACY_HELPER_SERVICE = 'com.callstack.agentdevice.imehelper/.TestInputMethodService'; const NORMAL_IME = 'com.google.android.inputmethod.latin/.LatinIME'; -// probeAndroidTestIme reads the helper's service component from the bundled artifact; inject a -// fixture so the orphan-detection checks pass on a fresh checkout that hasn't packaged -// android/ime-helper/dist (CI's Coverage job runs no packaging step). -vi.mock('../ime-helper.ts', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - resolveAndroidImeHelperArtifact: vi.fn(async () => ({ - apkPath: '/fixture/helper.apk', - manifest: { - name: 'android-ime-helper' as const, - version: '0.0.0', - assetName: 'helper.apk', - sha256: 'a'.repeat(64), - packageName: 'com.callstack.agentdevice.imehelper', - versionCode: 1, - serviceComponent: HELPER_SERVICE, - broadcastProtocol: 'android-ime-helper-v2' as const, - }, - })), - }; -}); - import { ANDROID_EMULATOR } from './test-utils/device-fixtures.ts'; import type { HostDiagnosticsContext } from '@agent-device/contracts/host-diagnostics'; import { androidDeviceChecks, androidToolchainCheck } from '../doctor.ts'; @@ -141,6 +120,18 @@ test('reports fail with a remediation command when the test IME is orphaned', as assert.equal(check?.evidence?.previousIme, NORMAL_IME); }); +test('reports the legacy IME as orphaned even without an owning session', async () => { + const check = await runImeCheck(fakeAdb(LEGACY_HELPER_SERVICE, NORMAL_IME)); + assert.equal(check?.status, 'fail'); + assert.equal(check?.command, `adb -s ${ANDROID_EMULATOR.id} shell ime set ${NORMAL_IME}`); +}); + +test('does not offer an IME helper component as the restore target', async () => { + const check = await runImeCheck(fakeAdb(HELPER_SERVICE, LEGACY_HELPER_SERVICE)); + assert.equal(check?.status, 'fail'); + assert.equal(check?.command, `adb -s ${ANDROID_EMULATOR.id} shell ime list -s`); +}); + test('falls back to ime list -s when no previous-IME record was persisted', async () => { const check = await runImeCheck(fakeAdb(HELPER_SERVICE)); assert.equal(check?.status, 'fail'); diff --git a/packages/platform-android/src/__tests__/ime-helper-ack.test.ts b/packages/platform-android/src/__tests__/ime-helper-ack.test.ts index 61acd2d4d2e..9102259cb59 100644 --- a/packages/platform-android/src/__tests__/ime-helper-ack.test.ts +++ b/packages/platform-android/src/__tests__/ime-helper-ack.test.ts @@ -10,7 +10,7 @@ import { } from '../ime-helper.ts'; import type { AndroidAdbExecutor } from '../adb-executor.ts'; -const PACKAGE = 'com.callstack.agentdevice.imehelper'; +const PACKAGE = 'com.callstack.agentdevice.imehelper.v2'; const CLEAR_ACTION = 'com.callstack.agentdevice.imehelper.ACTION_CLEAR_TEXT'; const INPUT_ACTION = 'com.callstack.agentdevice.imehelper.ACTION_INPUT_TEXT_B64'; diff --git a/packages/platform-android/src/__tests__/ime-helper.test.ts b/packages/platform-android/src/__tests__/ime-helper.test.ts index 1b93ec47d26..3470b8bed42 100644 --- a/packages/platform-android/src/__tests__/ime-helper.test.ts +++ b/packages/platform-android/src/__tests__/ime-helper.test.ts @@ -10,11 +10,12 @@ import { resetAndroidImeHelperInstallCache, sendAndroidImeHelperText, clearAndroidImeHelperText, + isAndroidImeHelperPackage, } from '../ime-helper.ts'; import type { AndroidAdbExecutor, AndroidAdbProvider } from '../adb-executor.ts'; import { mkdtempForTest } from './test-utils/tmp-dir.ts'; -const PACKAGE = 'com.callstack.agentdevice.imehelper'; +const PACKAGE = 'com.callstack.agentdevice.imehelper.v2'; const LATIN_IME = 'com.google.android.inputmethod.latin/com.android.inputmethod.latin.LatinIME'; const manifest = { @@ -24,7 +25,8 @@ const manifest = { sha256: 'a'.repeat(64), packageName: PACKAGE, versionCode: 19002, - serviceComponent: 'com.callstack.agentdevice.imehelper/.TestInputMethodService', + serviceComponent: + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService', broadcastProtocol: 'android-ime-helper-v2' as const, }; @@ -32,6 +34,12 @@ beforeEach(() => { resetAndroidImeHelperInstallCache(); }); +test('current and legacy helper packages both retain the broadcast text route', () => { + assert.equal(isAndroidImeHelperPackage(PACKAGE), true); + assert.equal(isAndroidImeHelperPackage('com.callstack.agentdevice.imehelper'), true); + assert.equal(isAndroidImeHelperPackage('com.example.keyboard'), false); +}); + test('sendAndroidImeHelperText package-scopes the broadcast and base64-encodes UTF-8', async () => { let capturedArgs: readonly string[] | undefined; await sendAndroidImeHelperText( diff --git a/packages/platform-android/src/__tests__/ime-lifecycle-race.test.ts b/packages/platform-android/src/__tests__/ime-lifecycle-race.test.ts index d90813ee04f..88f67795f14 100644 --- a/packages/platform-android/src/__tests__/ime-lifecycle-race.test.ts +++ b/packages/platform-android/src/__tests__/ime-lifecycle-race.test.ts @@ -14,7 +14,8 @@ import { runStartupRecoveryFence, } from '@agent-device/contracts/startup-recovery-fence'; -const HELPER_SERVICE = 'com.callstack.agentdevice.imehelper/.TestInputMethodService'; +const HELPER_SERVICE = + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService'; const LATIN_IME = 'com.google.android.inputmethod.latin/.LatinIME'; const PREVIOUS_IME_KEY = 'agent_device_ime_helper_previous_ime'; const REBIND_DISPLACED_KEY = 'agent_device_ime_helper_rebind_displaced'; @@ -51,7 +52,7 @@ vi.mock('../ime-helper.ts', async (importOriginal) => { version: '0.0.0', assetName: 'ime-helper.apk', sha256: 'fixture', - packageName: 'com.callstack.agentdevice.imehelper', + packageName: 'com.callstack.agentdevice.imehelper.v2', versionCode: 1, serviceComponent: HELPER_SERVICE, broadcastProtocol: 'android-ime-helper-v2' as const, diff --git a/packages/platform-android/src/__tests__/ime-lifecycle.test.ts b/packages/platform-android/src/__tests__/ime-lifecycle.test.ts index 6d37d8638c5..b1f2d2cd013 100644 --- a/packages/platform-android/src/__tests__/ime-lifecycle.test.ts +++ b/packages/platform-android/src/__tests__/ime-lifecycle.test.ts @@ -4,8 +4,10 @@ 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 HELPER_SERVICE = + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService'; const SETTINGS_KEY = 'agent_device_ime_helper_previous_ime'; const REBIND_DISPLACED_KEY = 'agent_device_ime_helper_rebind_displaced'; const PENDING_DIR = 'android-test-ime-pending'; @@ -23,7 +25,7 @@ vi.mock('../ime-helper.ts', async (importOriginal) => { version: '0.0.0', assetName: 'helper.apk', sha256: fixture.ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.sha256, - packageName: 'com.callstack.agentdevice.imehelper', + packageName: 'com.callstack.agentdevice.imehelper.v2', versionCode: 1, serviceComponent: HELPER_SERVICE, broadcastProtocol: 'android-ime-helper-v2' as const, @@ -105,7 +107,7 @@ function fakeDeviceState(initialIme: string) { function handleShowVersionCode(): FakeAdbResult { return installed - ? ok('package:com.callstack.agentdevice.imehelper versionCode:19002') + ? ok('package:com.callstack.agentdevice.imehelper.v2 versionCode:1') : { exitCode: 1, stdout: '', stderr: 'not found' }; } @@ -158,6 +160,14 @@ function fakeDeviceState(initialIme: string) { const adb: AndroidAdbExecutor = async (args) => { if (args.includes('--show-versioncode')) return handleShowVersionCode(); + const installedApk = '/data/app/com.callstack.agentdevice.imehelper.v2/base.apk'; + if (args.join(' ') === 'shell pm path com.callstack.agentdevice.imehelper.v2') { + return ok(`package:${installedApk}`); + } + if (args[0] === 'pull' && args[1] === installedApk && args[2]) { + await fsp.copyFile(ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.apkPath, args[2]); + return ok('1 file pulled'); + } 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__/index-dispatch-disclosure.test.ts b/packages/platform-android/src/__tests__/index-dispatch-disclosure.test.ts index a60460a1700..6fefeaa0e84 100644 --- a/packages/platform-android/src/__tests__/index-dispatch-disclosure.test.ts +++ b/packages/platform-android/src/__tests__/index-dispatch-disclosure.test.ts @@ -82,7 +82,8 @@ async function doubleTapWithSecondTapRefused(): Promise { assert.equal(taps, 2); } -const HELPER_IME_ACTIVE = 'mInputShown=true mCurMethodId=com.callstack.agentdevice.imehelper/.Ime'; +const HELPER_IME_ACTIVE = + 'mInputShown=true mCurMethodId=com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService'; /** `type` on a device whose active input method is the helper IME, with the broadcast scripted. */ async function typeThroughHelperIme(broadcast: Error | { exitCode: number; stderr: string }) { diff --git a/packages/platform-android/src/__tests__/settings-locale.test.ts b/packages/platform-android/src/__tests__/settings-locale.test.ts index fc4d360de38..cbae3979852 100644 --- a/packages/platform-android/src/__tests__/settings-locale.test.ts +++ b/packages/platform-android/src/__tests__/settings-locale.test.ts @@ -22,7 +22,7 @@ vi.mock('../automation-helper-artifact.ts', async (importOriginal) => { }; }); -const PACKAGE = 'com.callstack.agentdevice.snapshothelper'; +const PACKAGE = 'com.callstack.agentdevice.snapshothelper.v2'; const VERSION_CODE = 13003; const HELPER_BYTES = 'helper-apk'; const APK = `/data/app/~~a1==/${PACKAGE}-b2==/base.apk`; @@ -144,7 +144,7 @@ async function helperArtifact(): Promise { sha256: crypto.createHash('sha256').update(HELPER_BYTES).digest('hex'), packageName: PACKAGE, versionCode: VERSION_CODE, - instrumentationRunner: `${PACKAGE}/.SnapshotInstrumentation`, + instrumentationRunner: `${PACKAGE}/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation`, minSdk: 23, outputFormat: 'uiautomator-xml', statusProtocol: 'android-snapshot-helper-v1', 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..52f2cdb2e55 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 @@ -58,7 +58,7 @@ function helperVersionResponse(args: readonly string[]): AndroidAdbExecutorResul if (!args.includes('--show-versioncode')) return undefined; return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:999999', + stdout: `package:${helperArtifact.manifest.packageName} versionCode:999999`, stderr: '', }; } diff --git a/packages/platform-android/src/__tests__/snapshot-capture.test.ts b/packages/platform-android/src/__tests__/snapshot-capture.test.ts index 4f6cc026dd7..fb00aa12b63 100644 --- a/packages/platform-android/src/__tests__/snapshot-capture.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-capture.test.ts @@ -73,7 +73,7 @@ function helperAdbServing( if (args.includes('--show-versioncode')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stdout: `package:${helperArtifact.manifest.packageName} versionCode:13004`, 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..ed1a509d0dc 100644 --- a/packages/platform-android/src/__tests__/snapshot-clickability.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-clickability.test.ts @@ -129,7 +129,7 @@ test('snapshotAndroid captures the hierarchy once and publishes the clickability if (args.includes('--show-versioncode')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode=13004', + stdout: 'package:com.callstack.agentdevice.snapshothelper.v2 versionCode:13002', stderr: '', }; } diff --git a/packages/platform-android/src/__tests__/snapshot-helper-capture.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-capture.test.ts index 99d8db46b7d..7836cc5f928 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-capture.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-capture.test.ts @@ -5,6 +5,7 @@ import { AppError } from '@agent-device/kernel/errors'; import { captureAndroidSnapshotWithHelper, parseAndroidSnapshotHelperOutput, + resolveAndroidSnapshotHelperCaptureOptions, } from '../snapshot-helper-capture.ts'; import { resetAndroidSnapshotHelperRetirements } from '../snapshot-helper-retirement.ts'; import type { AndroidAdbExecutor } from '../snapshot-helper-types.ts'; @@ -17,6 +18,20 @@ beforeEach(() => { resetAndroidSnapshotHelperRetirements(); }); +test('custom helper package keeps its relative instrumentation runner fallback', () => { + const adb: AndroidAdbExecutor = async () => ({ exitCode: 0, stdout: '', stderr: '' }); + const custom = resolveAndroidSnapshotHelperCaptureOptions({ + adb, + packageName: 'com.example.snapshot', + }); + const bundled = resolveAndroidSnapshotHelperCaptureOptions({ adb }); + assert.equal(custom.runner, 'com.example.snapshot/.SnapshotInstrumentation'); + assert.equal( + bundled.runner, + 'com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation', + ); +}); + test('one-shot capture that resolves during cancellation retires before rejecting', async () => { const controller = new AbortController(); const cancellation = new Error('wait deadline exceeded'); @@ -27,6 +42,10 @@ test('one-shot capture that resolves during cancellation retires before rejectin }); const adb: AndroidAdbExecutor = async (args, options) => { if (args.join(' ').includes('am instrument')) { + assert.equal( + args.at(-1), + 'com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation', + ); return await new Promise((resolve) => { const onAbort = () => { events.push('instrumentation-resolved'); @@ -45,7 +64,7 @@ test('one-shot capture that resolves during cancellation retires before rejectin 'shell', 'am', 'force-stop', - 'com.callstack.agentdevice.snapshothelper', + 'com.callstack.agentdevice.snapshothelper.v2', ]); // The retirement stop must not inherit the aborted command signal; it bounds itself. assert.ok(!options?.signal?.aborted); 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..7d11d40a1b9 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 @@ -106,7 +106,7 @@ function helperFailingWith(run: FailedRun): AndroidAdbExecutor { if (args.includes('--show-versioncode')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stdout: `package:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName} versionCode:13004`, stderr: '', }; } 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..6878eadcaf0 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-install.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-install.test.ts @@ -19,9 +19,10 @@ const manifest: AndroidSnapshotHelperManifest = { version: '0.13.3', apkUrl: null, sha256: 'a'.repeat(64), - packageName: 'com.callstack.agentdevice.snapshothelper', + packageName: 'com.callstack.agentdevice.snapshothelper.v2', versionCode: 13003, - instrumentationRunner: 'com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation', + instrumentationRunner: + 'com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation', minSdk: 23, targetSdk: 36, outputFormat: 'uiautomator-xml', diff --git a/packages/platform-android/src/__tests__/snapshot-helper-retirement.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-retirement.test.ts index 824094c57f8..95278865548 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-retirement.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-retirement.test.ts @@ -18,7 +18,7 @@ import { isAndroidHelperRuntimeProbe, } from './snapshot-helper-session.fixtures.ts'; -const PACKAGE_NAME = 'com.callstack.agentdevice.snapshothelper'; +const PACKAGE_NAME = 'com.callstack.agentdevice.snapshothelper.v2'; const DEVICE_KEY = 'android:emulator-5554'; // The device is asked for the helper process and told to echo a marker when there is none, so a // release can only come from a shell that ran the command. diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts index 2015fc8fef2..91818837cf8 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts @@ -183,8 +183,9 @@ test('a session capture keeps a short connect wait and the full session share of commandTimeoutMs: 30_000, maxDepth: 128, maxNodes: 5_000, - packageName: 'com.callstack.agentdevice.snapshothelper', - runner: 'com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation', + packageName: 'com.callstack.agentdevice.snapshothelper.v2', + runner: + 'com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation', }); assert.equal(resolved.timeoutMs, 2_000); assert.equal(resolved.commandTimeoutMs, 15_000); @@ -629,5 +630,5 @@ function countForceStops(options: SessionProviderOptions): number { } function isHelperRuntimeForceStop(args: readonly string[]): boolean { - return args.join(' ') === 'shell am force-stop com.callstack.agentdevice.snapshothelper'; + return args.join(' ') === 'shell am force-stop com.callstack.agentdevice.snapshothelper.v2'; } diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session-peer.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session-peer.test.ts index b0d0922adec..a7609a61887 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session-peer.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session-peer.test.ts @@ -115,8 +115,9 @@ test('after a refused peer, touch commands run one-shot until the start backoff deviceKey: DEVICE_KEY, action: 'viewport', helper: { - packageName: 'com.callstack.agentdevice.snapshothelper', - runner: 'com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation', + packageName: 'com.callstack.agentdevice.snapshothelper.v2', + runner: + 'com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation', }, timeoutMs: 2_000, }); diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session-runtime-isolation.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session-runtime-isolation.test.ts index e59fb1d625d..9a4d18ad0ab 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session-runtime-isolation.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session-runtime-isolation.test.ts @@ -79,6 +79,6 @@ test("a runtime's pending retirement survives another runtime's close", async () function forceStops(calls: readonly (readonly string[])[]): number { return calls.filter( - (args) => args.join(' ') === 'shell am force-stop com.callstack.agentdevice.snapshothelper', + (args) => args.join(' ') === 'shell am force-stop com.callstack.agentdevice.snapshothelper.v2', ).length; } 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..4b3f8bb7ae7 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 { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } 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:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName} versionCode:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.versionCode + 1}`, 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..6865e2897ae 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 @@ -44,9 +44,8 @@ const device: DeviceInfo = { booted: true, }; -const HELPER_PACKAGE = ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName; // The component as `am` names it in its refusal: fully qualified, not the `/.Class` short form. -const HELPER_RUNNER = `${HELPER_PACKAGE}/${HELPER_PACKAGE}.SnapshotInstrumentation`; +const HELPER_RUNNER = ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.instrumentationRunner; // What `am instrument -w` printed, verbatim, when the system refused to start the uninstalled helper // on an Android 15 (API 35) emulator: ActivityManagerService reports the refusal as status -1, and diff --git a/packages/platform-android/src/__tests__/snapshot-helper.test.ts b/packages/platform-android/src/__tests__/snapshot-helper.test.ts index cc6e8ff8200..2da6ed83fda 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper.test.ts @@ -28,9 +28,10 @@ const manifest: AndroidSnapshotHelperManifest = { version: '0.13.3', apkUrl: null, sha256: 'a'.repeat(64), - packageName: 'com.callstack.agentdevice.snapshothelper', + packageName: 'com.callstack.agentdevice.snapshothelper.v2', versionCode: 13003, - instrumentationRunner: 'com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation', + instrumentationRunner: + 'com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation', minSdk: 23, targetSdk: 36, outputFormat: 'uiautomator-xml', @@ -202,7 +203,7 @@ test('ensureAndroidSnapshotHelper installs when missing and skips a newer versio const skipped = await ensureAndroidSnapshotHelper({ adb: async () => ({ exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stdout: 'package:com.callstack.agentdevice.snapshothelper.v2 versionCode:13004', stderr: '', }), artifact: { apkPath, manifest: localManifest }, @@ -568,7 +569,7 @@ test('ensureAndroidSnapshotHelper uninstalls and retries when signatures differ' if (args.includes('--show-versioncode')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:1', + stdout: 'package:com.callstack.agentdevice.snapshothelper.v2 versionCode:1', stderr: '', }; } @@ -593,7 +594,7 @@ test('ensureAndroidSnapshotHelper uninstalls and retries when signatures differ' assert.equal(result.installed, true); assert.equal(result.reason, 'outdated'); assert.deepEqual(calls[1], ['install', '-r', apkPath]); - assert.deepEqual(calls[2], ['uninstall', 'com.callstack.agentdevice.snapshothelper']); + assert.deepEqual(calls[2], ['uninstall', 'com.callstack.agentdevice.snapshothelper.v2']); assert.deepEqual(calls[3], ['install', '-r', apkPath]); }); @@ -641,7 +642,7 @@ test('ensureAndroidSnapshotHelper retry install also uses provider install capab if (args.includes('--show-versioncode')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:1', + stdout: 'package:com.callstack.agentdevice.snapshothelper.v2 versionCode:1', stderr: '', }; } @@ -671,7 +672,7 @@ test('ensureAndroidSnapshotHelper retry install also uses provider install capab assert.equal(result.installed, true); assert.deepEqual(installCalls, [apkPath, apkPath]); - assert.deepEqual(adbCalls[1], ['uninstall', 'com.callstack.agentdevice.snapshothelper']); + assert.deepEqual(adbCalls[1], ['uninstall', 'com.callstack.agentdevice.snapshothelper.v2']); }); test('captureAndroidSnapshotWithHelper gives adb command overhead beyond helper timeout', 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..8eb1532ec23 100644 --- a/packages/platform-android/src/__tests__/snapshot-quality-fixtures.ts +++ b/packages/platform-android/src/__tests__/snapshot-quality-fixtures.ts @@ -14,7 +14,7 @@ export const androidSnapshotQualityHelperArtifact = ANDROID_SNAPSHOT_HELPER_FIXT const installedHelperProbe = { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stdout: `package:${androidSnapshotQualityHelperArtifact.manifest.packageName} versionCode:13004`, 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..e836da544c8 100644 --- a/packages/platform-android/src/__tests__/snapshot-results.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-results.test.ts @@ -48,7 +48,7 @@ test('snapshotAndroid emits helper failure diagnostics', async () => { if (args.includes('--show-versioncode')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stdout: `package:${helperArtifact.manifest.packageName} versionCode:13004`, stderr: '', }; } @@ -214,7 +214,8 @@ test('snapshotAndroid fails closed after unparseable helper output', async () => ); assert.equal( calls.some( - (args) => args.join(' ') === 'shell am force-stop com.callstack.agentdevice.snapshothelper', + (args) => + args.join(' ') === 'shell am force-stop com.callstack.agentdevice.snapshothelper.v2', ), true, ); @@ -254,7 +255,7 @@ test('snapshotAndroid re-probes helper install after helper capture failure', as versionProbeCount += 1; return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stdout: `package:${helperArtifact.manifest.packageName} versionCode:13004`, stderr: '', }; } diff --git a/packages/platform-android/src/__tests__/snapshot.test.ts b/packages/platform-android/src/__tests__/snapshot.test.ts index e1e4f79ecf4..85f09b1c51b 100644 --- a/packages/platform-android/src/__tests__/snapshot.test.ts +++ b/packages/platform-android/src/__tests__/snapshot.test.ts @@ -208,7 +208,7 @@ test('snapshotAndroid uses the injected helper artifact', async () => { if (args.includes('--show-versioncode')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stdout: installedHelperProbe.stdout, stderr: '', }; } @@ -294,7 +294,7 @@ test('snapshotAndroid emits helper phase diagnostics', async () => { if (args.includes('--show-versioncode')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stdout: installedHelperProbe.stdout, stderr: '', }; } @@ -336,7 +336,7 @@ test('snapshotAndroid resolves helper adb through scoped provider', async () => if (args.includes('--show-versioncode')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stdout: installedHelperProbe.stdout, stderr: '', }; } @@ -598,7 +598,7 @@ test('snapshotAndroid fails closed when the helper fails', async () => { if (args.includes('--show-versioncode')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:13004', + stdout: installedHelperProbe.stdout, stderr: '', }; } @@ -640,7 +640,8 @@ test('snapshotAndroid fails closed when helper returns only system windows', asy ); assert.equal( adbCalls.some( - (args) => args.join(' ') === 'shell am force-stop com.callstack.agentdevice.snapshothelper', + (args) => + args.join(' ') === 'shell am force-stop com.callstack.agentdevice.snapshothelper.v2', ), true, ); 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..36cb36f02a8 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 @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url'; import type { AndroidAdbExecutor } from '../../adb-executor.ts'; import type { AndroidSnapshotHelperArtifact } from '../../snapshot-helper-types.ts'; -const SNAPSHOT_HELPER_PACKAGE = 'com.callstack.agentdevice.snapshothelper'; +const SNAPSHOT_HELPER_PACKAGE = 'com.callstack.agentdevice.snapshothelper.v2'; const SNAPSHOT_HELPER_FIXTURE_APK_PATH = fileURLToPath( new URL('./fixtures/android-helper-apk.fixture', import.meta.url), ); @@ -18,7 +18,7 @@ export const ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT: AndroidSnapshotHelperArti sha256: SNAPSHOT_HELPER_FIXTURE_APK_SHA256, packageName: SNAPSHOT_HELPER_PACKAGE, versionCode: 13003, - instrumentationRunner: `${SNAPSHOT_HELPER_PACKAGE}/.SnapshotInstrumentation`, + instrumentationRunner: `${SNAPSHOT_HELPER_PACKAGE}/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation`, minSdk: 23, targetSdk: 36, outputFormat: 'uiautomator-xml', diff --git a/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts b/packages/platform-android/src/__tests__/text-input-fill-helper-lifecycle.test.ts index 3423419ad25..5400f3c7024 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 @@ -89,7 +89,7 @@ function createFillWorld( } if ( args.includes('--show-versioncode') || - args.join(' ') === 'shell pm path com.callstack.agentdevice.snapshothelper' || + args.join(' ') === 'shell pm path com.callstack.agentdevice.snapshothelper.v2' || args[0] === 'pull' ) { return await persistent.exec(args, execOptions); diff --git a/packages/platform-android/src/__tests__/text-input-test-ime.fixtures.ts b/packages/platform-android/src/__tests__/text-input-test-ime.fixtures.ts index 6a91ee8f1e4..6e696022dca 100644 --- a/packages/platform-android/src/__tests__/text-input-test-ime.fixtures.ts +++ b/packages/platform-android/src/__tests__/text-input-test-ime.fixtures.ts @@ -3,7 +3,7 @@ // leaves behind. Both files that exercise the channel read the same fake, so an ack and the field it // wrote mean the same thing in all of them. -export const PACKAGE = 'com.callstack.agentdevice.imehelper'; +export const PACKAGE = 'com.callstack.agentdevice.imehelper.v2'; export const CLEAR_ACTION = 'com.callstack.agentdevice.imehelper.ACTION_CLEAR_TEXT'; export const INPUT_ACTION = 'com.callstack.agentdevice.imehelper.ACTION_INPUT_TEXT_B64'; @@ -23,7 +23,8 @@ export function androidImeHelperFixtureArtifact() { sha256: 'a'.repeat(64), packageName: PACKAGE, versionCode: 1, - serviceComponent: 'com.callstack.agentdevice.imehelper/.TestInputMethodService', + serviceComponent: + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService', broadcastProtocol: 'android-ime-helper-v2' as const, }, }; @@ -74,7 +75,7 @@ export function helperSelected(args: readonly string[]): { const stdout = args[4] === 'agent_device_ime_helper_rebind_displaced' ? '1\n' - : 'com.callstack.agentdevice.imehelper/.TestInputMethodService\n'; + : 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService\n'; return { exitCode: 0, stdout, stderr: '' }; } diff --git a/packages/platform-android/src/__tests__/text-input-test-ime.test.ts b/packages/platform-android/src/__tests__/text-input-test-ime.test.ts index 2f1e41b6fd0..6ac2b881191 100644 --- a/packages/platform-android/src/__tests__/text-input-test-ime.test.ts +++ b/packages/platform-android/src/__tests__/text-input-test-ime.test.ts @@ -454,7 +454,10 @@ test('fillAndroid stops on an unconfirmed rebind and leaves the helper for close await writeAndroidTestImeRecoveryMarker(stateDir, ANDROID_EMULATOR.id); const device: FakeImeDeviceState = { settings: new Map([ - ['default_input_method', 'com.callstack.agentdevice.imehelper/.TestInputMethodService'], + [ + 'default_input_method', + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService', + ], ['agent_device_ime_helper_previous_ime', 'com.samsung/.Keyboard'], ]), // `settings get` timing out under load: the rebind cannot read back which IME is selected. diff --git a/packages/platform-android/src/__tests__/touch-helper.fixtures.ts b/packages/platform-android/src/__tests__/touch-helper.fixtures.ts index f5cd36e57fd..fe51cb76626 100644 --- a/packages/platform-android/src/__tests__/touch-helper.fixtures.ts +++ b/packages/platform-android/src/__tests__/touch-helper.fixtures.ts @@ -12,9 +12,10 @@ export const ANDROID_TOUCH_HELPER_MANIFEST = { version: '0.17.0', assetName: 'helper.apk', sha256: 'a'.repeat(64), - packageName: 'com.callstack.agentdevice.snapshothelper', + packageName: 'com.callstack.agentdevice.snapshothelper.v2', versionCode: 17000, - instrumentationRunner: 'com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation', + instrumentationRunner: + 'com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation', statusProtocol: 'android-snapshot-helper-v1' as const, }; diff --git a/packages/platform-android/src/doctor.ts b/packages/platform-android/src/doctor.ts index ad8ff26b49f..bbebec75919 100644 --- a/packages/platform-android/src/doctor.ts +++ b/packages/platform-android/src/doctor.ts @@ -10,7 +10,7 @@ import { readAndroidDefaultInputMethod, ANDROID_TEST_IME_SETTINGS_KEYS, } from './ime-lifecycle.ts'; -import { resolveAndroidImeHelperArtifact } from './ime-helper.ts'; +import { isAndroidImeHelperServiceComponent } from './ime-helper.ts'; import { requireAndroidAdbHost, type AndroidAdbEnvironment, @@ -76,7 +76,7 @@ async function probeAndroidTestIme( try { const currentIme = await readAndroidDefaultInputMethod(adb); const helperActiveInThisProcess = isAndroidTestImeActive(device); - const isHelperCurrentIme = currentIme === (await resolveAndroidImeHelperServiceComponent()); + const isHelperCurrentIme = isAndroidImeHelperServiceComponent(currentIme); if (isHelperCurrentIme && !helperActiveInThisProcess) { return await buildOrphanedTestImeCheck(adb, device, currentIme); } @@ -86,14 +86,6 @@ async function probeAndroidTestIme( } } -async function resolveAndroidImeHelperServiceComponent(): Promise { - try { - return (await resolveAndroidImeHelperArtifact()).manifest.serviceComponent; - } catch { - return undefined; - } -} - // Test IME is active but no session in this process owns it: orphaned by a crashed daemon run. async function buildOrphanedTestImeCheck( adb: AndroidAdbExecutor, @@ -106,7 +98,10 @@ async function buildOrphanedTestImeCheck( { allowFailure: true, timeoutMs: ANDROID_PROBE_TIMEOUT_MS }, ); const previousIme = previousImeResult.stdout.trim(); - const restoreTarget = previousIme && previousIme !== 'null' ? previousIme : undefined; + const restoreTarget = + previousIme && previousIme !== 'null' && !isAndroidImeHelperServiceComponent(previousIme) + ? previousIme + : undefined; return { id: 'android-test-ime', status: 'fail', diff --git a/packages/platform-android/src/ime-activation.test.ts b/packages/platform-android/src/ime-activation.test.ts index 3e240bcd118..8d91af3db42 100644 --- a/packages/platform-android/src/ime-activation.test.ts +++ b/packages/platform-android/src/ime-activation.test.ts @@ -6,6 +6,7 @@ import type { AndroidAdbExecutor } from './adb-transport.ts'; import { bindAndroidAdbHostStub, type AndroidAdbHostStub } from './adb-host.fixtures.ts'; import { withAndroidAdbProvider } from './adb-provider-scope.ts'; import { activateAndroidTestIme } from './ime-activation.ts'; +import { restoreAndroidTestIme } from './ime-restore.ts'; import { fakeImeDeviceAdb, type FakeImeDeviceState } from './ime-device.fixtures.ts'; import { getAndroidTestImeOwnership, @@ -21,7 +22,9 @@ const DEVICE: DeviceInfo = { kind: 'emulator', booted: true, }; -const HELPER_SERVICE = 'com.callstack.agentdevice.imehelper/.TestInputMethodService'; +const HELPER_SERVICE = + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService'; +const LEGACY_HELPER_SERVICE = 'com.callstack.agentdevice.imehelper/.TestInputMethodService'; const STATE_DIR = '/state'; const ARTIFACT: AndroidImeHelperArtifact = { @@ -31,7 +34,7 @@ const ARTIFACT: AndroidImeHelperArtifact = { version: '0.0.0', assetName: 'helper.apk', sha256: 'f'.repeat(64), - packageName: 'com.callstack.agentdevice.imehelper', + packageName: 'com.callstack.agentdevice.imehelper.v2', versionCode: 1, serviceComponent: HELPER_SERVICE, broadcastProtocol: 'android-ime-helper-v2', @@ -77,6 +80,35 @@ test('activation records the restore target and marker, then switches and claims expect(isAndroidTestImeActive(DEVICE)).toBe(true); }); +test('activation retains the user keyboard when the retired helper is active', async () => { + activationHost(); + const state: FakeImeDeviceState = { + settings: new Map([ + ['default_input_method', LEGACY_HELPER_SERVICE], + ['agent_device_ime_helper_previous_ime', 'com.samsung/.Keyboard'], + ]), + }; + + const result = await activateWith(state); + + expect(result).toMatchObject({ activated: true, previousIme: 'com.samsung/.Keyboard' }); + expect(state.settings.get('agent_device_ime_helper_previous_ime')).toBe('com.samsung/.Keyboard'); + expect(state.settings.get('default_input_method')).toBe(HELPER_SERVICE); +}); + +test('activation leaves a retired helper active when no user keyboard is recorded', async () => { + activationHost(); + const state: FakeImeDeviceState = { + settings: new Map([['default_input_method', LEGACY_HELPER_SERVICE]]), + }; + + const result = await activateWith(state); + + expect(result).toMatchObject({ activated: false, persistFailed: true }); + expect(state.settings.has('agent_device_ime_helper_previous_ime')).toBe(false); + expect(state.settings.get('default_input_method')).toBe(LEGACY_HELPER_SERVICE); +}); + test('a switch that never takes effect rolls back records and claims nothing', async () => { const host = activationHost(); const state: FakeImeDeviceState = { @@ -211,6 +243,35 @@ test('a confirmed activation clears a rebind record left without a restore recor expect(getAndroidTestImeOwnership(DEVICE)?.rebindUnconfirmed).toBe(false); }); +test('a displaced helper restore record uses the current user keyboard before switching', async () => { + const host = activationHost(); + const currentIme = 'com.android.inputmethod.latin/.LatinIME'; + const state: FakeImeDeviceState = { + settings: new Map([ + ['default_input_method', currentIme], + ['agent_device_ime_helper_previous_ime', LEGACY_HELPER_SERVICE], + [REBIND_DISPLACED, '1'], + ]), + }; + + const activation = await activateWith(state); + + expect(activation).toMatchObject({ activated: true, previousIme: currentIme }); + expect(state.settings.get('agent_device_ime_helper_previous_ime')).toBe(currentIme); + expect(state.settings.get('default_input_method')).toBe(HELPER_SERVICE); + expect(state.settings.has(REBIND_DISPLACED)).toBe(false); + + const restoration = await withDeviceAdb( + fakeImeDeviceAdb(state), + async () => await restoreAndroidTestIme(DEVICE, { stateDir: STATE_DIR }), + ); + + expect(restoration).toMatchObject({ restored: true, previousIme: currentIme, reason: 'ok' }); + expect(state.settings.get('default_input_method')).toBe(currentIme); + expect(state.settings.has('agent_device_ime_helper_previous_ime')).toBe(false); + expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([]); +}); + test('activation claims ownership before settling an earlier rebind record', async () => { activationHost(); const state: FakeImeDeviceState = { diff --git a/packages/platform-android/src/ime-activation.ts b/packages/platform-android/src/ime-activation.ts index 182740a1070..e9fa9c55d69 100644 --- a/packages/platform-android/src/ime-activation.ts +++ b/packages/platform-android/src/ime-activation.ts @@ -7,6 +7,7 @@ import { runAdbShell } from './adb-executor.ts'; import { ensureAndroidImeHelper, getAndroidImeHelperDeviceKey, + isAndroidImeHelperServiceComponent, selectAndroidImeHelperArtifact, } from './ime-helper.ts'; import { @@ -113,6 +114,24 @@ async function activateAndroidTestImeAfterStartupRecovery( helperPackageName: manifest.packageName, }; } + if ( + isAndroidImeHelperServiceComponent(currentIme) && + (record.kind === 'absent' || isAndroidImeHelperServiceComponent(record.previousIme)) + ) { + emitAndroidAdbDiagnostic({ + level: 'warn', + phase: 'android_test_ime_restore_target_invalid', + data: { device: device.id, currentIme }, + }); + return { + outcome: 'settled', + activated: false, + alreadyActive: false, + persistFailed: true, + helperServiceComponent: manifest.serviceComponent, + helperPackageName: manifest.packageName, + }; + } const { previousIme, priorPersistedIme } = activationRestoreTarget(record, currentIme); if (!(await writePersistedPreviousIme(adb, previousIme))) { await restorePriorPersistedIme(adb, priorPersistedIme, device.id); @@ -246,7 +265,11 @@ function activationRestoreTarget( ): { previousIme: string; priorPersistedIme: string | undefined } { if (record.kind === 'absent') return { previousIme: currentIme, priorPersistedIme: undefined }; return { - previousIme: record.rebindDisplaced ? record.previousIme : currentIme, + previousIme: + (record.rebindDisplaced && !isAndroidImeHelperServiceComponent(record.previousIme)) || + isAndroidImeHelperServiceComponent(currentIme) + ? record.previousIme + : currentIme, priorPersistedIme: record.previousIme, }; } diff --git a/packages/platform-android/src/ime-helper.ts b/packages/platform-android/src/ime-helper.ts index 97836fc16e7..520f496d2b4 100644 --- a/packages/platform-android/src/ime-helper.ts +++ b/packages/platform-android/src/ime-helper.ts @@ -22,13 +22,24 @@ import { requireAndroidAdbHost } from './adb-host.ts'; const HELPER_LABEL = 'Android IME helper'; const ANDROID_IME_HELPER_NAME = 'android-ime-helper'; -const ANDROID_IME_HELPER_PACKAGE = 'com.callstack.agentdevice.imehelper'; -const ANDROID_IME_HELPER_SERVICE = 'com.callstack.agentdevice.imehelper/.TestInputMethodService'; +const ANDROID_IME_HELPER_PACKAGE = 'com.callstack.agentdevice.imehelper.v2'; +const ANDROID_IME_LEGACY_HELPER_PACKAGE = 'com.callstack.agentdevice.imehelper'; +const ANDROID_IME_HELPER_SERVICE = + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService'; const ANDROID_IME_HELPER_PROTOCOL = 'android-ime-helper-v2'; // Stable service-component id, matched literally by the manifest parser. Exported so the restore // lifecycle can compare the device's active IME without reading the packaged artifact from disk. export const ANDROID_IME_HELPER_SERVICE_COMPONENT = ANDROID_IME_HELPER_SERVICE; +const ANDROID_IME_HELPER_SERVICE_COMPONENTS = new Set([ + ANDROID_IME_HELPER_SERVICE_COMPONENT, + 'com.callstack.agentdevice.imehelper/.TestInputMethodService', + 'com.callstack.agentdevice.imehelper/com.callstack.agentdevice.imehelper.TestInputMethodService', +]); + +export function isAndroidImeHelperServiceComponent(component: string): boolean { + return ANDROID_IME_HELPER_SERVICE_COMPONENTS.has(component); +} const ANDROID_IME_HELPER_INSTALL_TIMEOUT_MS = 30_000; const ANDROID_IME_HELPER_BROADCAST_TIMEOUT_MS = 10_000; const ANDROID_IME_HELPER_REGISTRATION_TIMEOUT_MS = 5_000; @@ -253,7 +264,9 @@ export function getAndroidImeHelperDeviceKey(device: DeviceInfo): string { * carries the helper all leave the channel available with an empty activation cache. */ export function isAndroidImeHelperPackage(packageName: string | undefined): packageName is string { - return packageName === ANDROID_IME_HELPER_PACKAGE; + return ( + packageName === ANDROID_IME_HELPER_PACKAGE || packageName === ANDROID_IME_LEGACY_HELPER_PACKAGE + ); } // --- Broadcast text-entry channel ----------------------------------------------------------- diff --git a/packages/platform-android/src/ime-host.fixtures.ts b/packages/platform-android/src/ime-host.fixtures.ts index 731d253b472..8198c158672 100644 --- a/packages/platform-android/src/ime-host.fixtures.ts +++ b/packages/platform-android/src/ime-host.fixtures.ts @@ -79,7 +79,7 @@ export function bindAndroidImeTestHost(): (stateDir: string) => string[] { read: async (stateDir, serial) => flushRecords.get(`${stateDir}\u0000${serial}`), }, ensureHelperInstalled: async () => ({ - packageName: 'com.callstack.agentdevice.imehelper', + packageName: 'com.callstack.agentdevice.imehelper.v2', versionCode: 1, installed: false, reason: 'current', diff --git a/packages/platform-android/src/ime-rebind.test.ts b/packages/platform-android/src/ime-rebind.test.ts index 8e7fe180354..607f966c391 100644 --- a/packages/platform-android/src/ime-rebind.test.ts +++ b/packages/platform-android/src/ime-rebind.test.ts @@ -17,7 +17,8 @@ import { } from './ime-state.ts'; import { resetAndroidImeHelperInstallCache } from './ime-helper.ts'; -const HELPER_SERVICE = 'com.callstack.agentdevice.imehelper/.TestInputMethodService'; +const HELPER_SERVICE = + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService'; const STATE_DIR = '/state'; const ARTIFACT: AndroidImeHelperArtifact = { @@ -27,7 +28,7 @@ const ARTIFACT: AndroidImeHelperArtifact = { version: '0.0.0', assetName: 'helper.apk', sha256: 'f'.repeat(64), - packageName: 'com.callstack.agentdevice.imehelper', + packageName: 'com.callstack.agentdevice.imehelper.v2', versionCode: 1, serviceComponent: HELPER_SERVICE, broadcastProtocol: 'android-ime-helper-v2', diff --git a/packages/platform-android/src/ime-restore.test.ts b/packages/platform-android/src/ime-restore.test.ts index aaf3a14197e..75d2f6d87cb 100644 --- a/packages/platform-android/src/ime-restore.test.ts +++ b/packages/platform-android/src/ime-restore.test.ts @@ -35,7 +35,9 @@ const DEVICE: DeviceInfo = { kind: 'emulator', booted: true, }; -const HELPER_SERVICE = 'com.callstack.agentdevice.imehelper/.TestInputMethodService'; +const HELPER_SERVICE = + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService'; +const LEGACY_HELPER_SERVICE = 'com.callstack.agentdevice.imehelper/.TestInputMethodService'; const STATE_DIR = '/state'; function stuckDeviceState(): FakeImeDeviceState { @@ -83,6 +85,62 @@ test.each([false, true])('close restores the previous IME with displaced=%s', as expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([]); }); +test('startup restores the user keyboard when the retired helper is active', async () => { + const host = bindAndroidAdbHostStub(); + await host.imeRecoveryMarkers.write(STATE_DIR, DEVICE.id); + const state = stuckDeviceState(); + state.settings.set('default_input_method', LEGACY_HELPER_SERVICE); + + await withAndroidAdbProvider( + { exec: fakeImeDeviceAdb(state) }, + { serial: DEVICE.id }, + async () => + await restoreOrphanedAndroidTestImeOnDaemonStartup({ + stateDir: STATE_DIR, + listSerials: async () => [DEVICE.id], + }), + ); + + expect(state.settings.get('default_input_method')).toBe('com.samsung/.Keyboard'); + expect(state.settings.has('agent_device_ime_helper_previous_ime')).toBe(false); + expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([]); +}); + +test('restore retains an invalid helper restore target for recovery', async () => { + const host = bindAndroidAdbHostStub(); + await host.imeRecoveryMarkers.write(STATE_DIR, DEVICE.id); + setAndroidTestImeActiveForTests(DEVICE, true); + const state = stuckDeviceState(); + state.settings.set('agent_device_ime_helper_previous_ime', LEGACY_HELPER_SERVICE); + + const result = await restoreWith(state); + + expect(result).toMatchObject({ restored: false, reason: 'invalid-restore-target' }); + expect(host.diagnostics).toContainEqual({ + phase: 'android_test_ime_restore_target_invalid', + level: 'warn', + }); + expect(state.settings.get('default_input_method')).toBe(HELPER_SERVICE); + expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([DEVICE.id]); +}); + +test('a stale helper restore target clears its marker after the user keyboard is active', async () => { + const host = bindAndroidAdbHostStub(); + await host.imeRecoveryMarkers.write(STATE_DIR, DEVICE.id); + setAndroidTestImeActiveForTests(DEVICE, true); + const state = stuckDeviceState(); + state.settings.set('default_input_method', 'com.android.inputmethod.latin/.LatinIME'); + state.settings.set('agent_device_ime_helper_previous_ime', LEGACY_HELPER_SERVICE); + + const result = await restoreWith(state); + + expect(result).toMatchObject({ restored: false, reason: 'helper-not-active' }); + expect(state.settings.get('default_input_method')).toBe( + 'com.android.inputmethod.latin/.LatinIME', + ); + expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([]); +}); + test('an unreadable rebind record keeps the restore record and the marker for a retry', async () => { const host = bindAndroidAdbHostStub(); await host.imeRecoveryMarkers.write(STATE_DIR, DEVICE.id); diff --git a/packages/platform-android/src/ime-restore.ts b/packages/platform-android/src/ime-restore.ts index 1005013f639..4d17be5edca 100644 --- a/packages/platform-android/src/ime-restore.ts +++ b/packages/platform-android/src/ime-restore.ts @@ -4,10 +4,7 @@ import { emitAndroidAdbDiagnostic, requireAndroidAdbHost } from './adb-host.ts'; import { resolveAndroidAdbExecutor } from './adb-provider-scope.ts'; import { runAdbShell } from './adb-executor.ts'; import type { AndroidAdbExecutor } from './adb-transport.ts'; -import { - ANDROID_IME_HELPER_SERVICE_COMPONENT, - getAndroidImeHelperDeviceKey, -} from './ime-helper.ts'; +import { getAndroidImeHelperDeviceKey, isAndroidImeHelperServiceComponent } from './ime-helper.ts'; import { clearPersistedPreviousIme, clearPersistedRebindDisplacement, @@ -30,6 +27,7 @@ export type AndroidTestImeRestoreReason = | 'not-activated-here' | 'no-record' | 'record-unreadable' + | 'invalid-restore-target' | 'helper-not-active' | 'owned-by-live-session' | 'set-failed' @@ -98,8 +96,9 @@ async function restoreOwnedAndroidTestIme( // The device was inspected and the helper is confirmed off it (restored, already not the active // IME, or no rebind record). A `set-failed` (still stuck), `record-unreadable` (the device may be -// on Android's fallback IME), `owned-by-live-session` (a live session will restore it on close) -// or `not-activated-here` (nothing was inspected) keeps its pending marker for a later retry. +// on Android's fallback IME), `owned-by-live-session` (a live session will restore it on close), +// `invalid-restore-target` (kept for manual recovery), or `not-activated-here` (nothing was +// inspected) keeps its pending marker for a later retry. function isDeviceRecoveryComplete(reason: AndroidTestImeRestoreReason): boolean { return reason === 'ok' || reason === 'helper-not-active' || reason === 'no-record'; } @@ -135,9 +134,9 @@ async function restoreAndroidTestImeFor( if (record.kind === 'absent') { return { restored: false, reason: 'no-record' }; } - const { previousIme } = record; const currentIme = await readAndroidDefaultInputMethod(adb); - if (currentIme !== ANDROID_IME_HELPER_SERVICE_COMPONENT && !record.rebindDisplaced) { + const { previousIme } = record; + if (!isAndroidImeHelperServiceComponent(currentIme) && !record.rebindDisplaced) { // Helper is not active — the user switched away, or the helper was never really set. Do not // overwrite the current IME, and do not clear the device record (a concurrent activation could // have just written it). @@ -148,6 +147,14 @@ async function restoreAndroidTestImeFor( }); return { restored: false, previousIme, reason: 'helper-not-active' }; } + if (isAndroidImeHelperServiceComponent(previousIme)) { + emitAndroidAdbDiagnostic({ + level: 'warn', + phase: 'android_test_ime_restore_target_invalid', + data: { device: deviceLabel, currentIme, previousIme }, + }); + return { restored: false, previousIme, reason: 'invalid-restore-target' }; + } // The provider's window opens when the device accepts this write, so the pending entry // opens before issuing it: a kill-bound waiter drains in-flight writes before consulting // records and never reads the gap as "nothing owed". A `finally` close runs after the try diff --git a/packages/platform-android/src/launch-observation.test.ts b/packages/platform-android/src/launch-observation.test.ts index fc29dddd02b..480d46910ef 100644 --- a/packages/platform-android/src/launch-observation.test.ts +++ b/packages/platform-android/src/launch-observation.test.ts @@ -73,10 +73,10 @@ async function helperNotCurrentError(): Promise { version: '0.13.3', apkUrl: null, sha256, - packageName: 'com.callstack.agentdevice.snapshothelper', + packageName: 'com.callstack.agentdevice.snapshothelper.v2', versionCode: 13003, instrumentationRunner: - 'com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation', + 'com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation', minSdk: 23, targetSdk: 36, outputFormat: 'uiautomator-xml', diff --git a/packages/platform-android/src/snapshot-helper-capture.ts b/packages/platform-android/src/snapshot-helper-capture.ts index 77dd5befd6d..37059171a8c 100644 --- a/packages/platform-android/src/snapshot-helper-capture.ts +++ b/packages/platform-android/src/snapshot-helper-capture.ts @@ -17,6 +17,7 @@ import { } from './instrumentation-helper.ts'; import { ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS, + ANDROID_SNAPSHOT_HELPER_INSTRUMENTATION_CLASS, ANDROID_SNAPSHOT_HELPER_SESSION_MODE, ANDROID_SNAPSHOT_HELPER_SHORT_IDLE_TIMEOUT_MS, ANDROID_SNAPSHOT_HELPER_COMMAND_OVERHEAD_MS, @@ -232,7 +233,12 @@ export function resolveAndroidSnapshotHelperCaptureOptions( // `truncated` disclosure. Android acquisition is scope-blind (C2), so no hint can narrow it. maxNodes: withDefault(options.maxNodes, 5_000), packageName, - runner: withDefault(options.instrumentationRunner, `${packageName}/.SnapshotInstrumentation`), + runner: withDefault( + options.instrumentationRunner, + packageName === ANDROID_SNAPSHOT_HELPER_PACKAGE + ? `${packageName}/${ANDROID_SNAPSHOT_HELPER_INSTRUMENTATION_CLASS}` + : `${packageName}/.SnapshotInstrumentation`, + ), ...(options.emitChunks !== undefined ? { emitChunks: options.emitChunks } : {}), }; } diff --git a/packages/platform-android/src/snapshot-helper-types.ts b/packages/platform-android/src/snapshot-helper-types.ts index aeee2fffb1c..edc0ed86fdb 100644 --- a/packages/platform-android/src/snapshot-helper-types.ts +++ b/packages/platform-android/src/snapshot-helper-types.ts @@ -12,7 +12,9 @@ export type AndroidSnapshotHelperInstallReason = | 'skipped'; export const ANDROID_SNAPSHOT_HELPER_NAME = 'android-snapshot-helper'; -export const ANDROID_SNAPSHOT_HELPER_PACKAGE = 'com.callstack.agentdevice.snapshothelper'; +export const ANDROID_SNAPSHOT_HELPER_PACKAGE = 'com.callstack.agentdevice.snapshothelper.v2'; +export const ANDROID_SNAPSHOT_HELPER_INSTRUMENTATION_CLASS = + 'com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation'; export const ANDROID_SNAPSHOT_HELPER_PROTOCOL = 'android-snapshot-helper-v1'; export const ANDROID_SNAPSHOT_HELPER_OUTPUT_FORMAT = 'uiautomator-xml'; // Keep common snapshots biased toward post-microinteraction reliability. The diff --git a/scripts/build-android-helper.sh b/scripts/build-android-helper.sh index 2b360f2b35e..37137f2cb90 100755 --- a/scripts/build-android-helper.sh +++ b/scripts/build-android-helper.sh @@ -20,7 +20,8 @@ BUILD_TOOLS_VERSION="${3:-${AGENT_DEVICE_ANDROID_BUILD_TOOLS:-}}" PROJECT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)" MIN_SDK=23 TARGET_SDK=36 -KEYSTORE="$PROJECT_DIR/android/snapshot-helper/debug.keystore" +KEYSTORE="${AGENT_DEVICE_ANDROID_KEYSTORE:-}" +KEY_ALIAS="${AGENT_DEVICE_ANDROID_KEY_ALIAS:-}" # Per-helper config: HELPER_DIR/PACKAGE_NAME/APK name always differ; RUN_TEST_CLASS is # only set for the snapshot helper (it has a unit test to compile+run); RESOURCE_DIR is @@ -28,13 +29,13 @@ KEYSTORE="$PROJECT_DIR/android/snapshot-helper/debug.keystore" case "$HELPER" in snapshot) HELPER_DIR="$PROJECT_DIR/android/snapshot-helper" - PACKAGE_NAME="com.callstack.agentdevice.snapshothelper" + PACKAGE_NAME="com.callstack.agentdevice.snapshothelper.v2" RUN_TEST_CLASS="com.callstack.agentdevice.snapshothelper.SnapshotHelperTestSuite" RESOURCE_DIR="" ;; ime) HELPER_DIR="$PROJECT_DIR/android/ime-helper" - PACKAGE_NAME="com.callstack.agentdevice.imehelper" + PACKAGE_NAME="com.callstack.agentdevice.imehelper.v2" RUN_TEST_CLASS="" RESOURCE_DIR="$PROJECT_DIR/android/ime-helper/res" ;; @@ -96,6 +97,15 @@ for BUILD_TOOL in aapt2 d8 zipalign apksigner; do fi done +if [ -z "$KEYSTORE" ] || [ ! -f "$KEYSTORE" ]; then + echo "AGENT_DEVICE_ANDROID_KEYSTORE must name an existing Android helper signing keystore" >&2 + exit 1 +fi +if [ -z "$KEY_ALIAS" ] || [ -z "${AGENT_DEVICE_ANDROID_KEYSTORE_PASSWORD:-}" ] || [ -z "${AGENT_DEVICE_ANDROID_KEY_PASSWORD:-}" ]; then + echo "Android helper signing requires AGENT_DEVICE_ANDROID_KEY_ALIAS, AGENT_DEVICE_ANDROID_KEYSTORE_PASSWORD, and AGENT_DEVICE_ANDROID_KEY_PASSWORD" >&2 + exit 1 +fi + # A prerelease shares its base release's code, so a nightly or -dev helper replaces an older # release; an equal code reinstalls by checksum. VERSION_CODE="$( @@ -173,15 +183,11 @@ zip -q -j "$UNSIGNED_APK" "$DEX_DIR/classes.dex" "$BUILD_TOOLS_DIR/zipalign" -f 4 "$UNSIGNED_APK" "$ALIGNED_APK" -if [ ! -f "$KEYSTORE" ]; then - echo "Missing Android helper signing keystore: $KEYSTORE" >&2 - exit 1 -fi - "$BUILD_TOOLS_DIR/apksigner" sign \ --ks "$KEYSTORE" \ - --ks-pass pass:android \ - --key-pass pass:android \ + --ks-key-alias "$KEY_ALIAS" \ + --ks-pass env:AGENT_DEVICE_ANDROID_KEYSTORE_PASSWORD \ + --key-pass env:AGENT_DEVICE_ANDROID_KEY_PASSWORD \ --out "$APK_PATH" \ "$ALIGNED_APK" diff --git a/scripts/package-android-helper.sh b/scripts/package-android-helper.sh index 3228c78e09d..60b32c86e76 100755 --- a/scripts/package-android-helper.sh +++ b/scripts/package-android-helper.sh @@ -47,8 +47,8 @@ if [ "$HAS_RELEASE_TAG" = 1 ]; then fi case "$HELPER" in - snapshot) PACKAGE_NAME="com.callstack.agentdevice.snapshothelper" ;; - ime) PACKAGE_NAME="com.callstack.agentdevice.imehelper" ;; + snapshot) PACKAGE_NAME="com.callstack.agentdevice.snapshothelper.v2" ;; + ime) PACKAGE_NAME="com.callstack.agentdevice.imehelper.v2" ;; esac MIN_SDK=23 @@ -91,13 +91,13 @@ case "$HELPER" in node - "$VERSION" "$RELEASE_TAG" "$APK_BASENAME" "$APK_URL" "$SHA256" "$CHECKSUM_BASENAME" "$PACKAGE_NAME" "$VERSION_CODE" "$MIN_SDK" "$TARGET_SDK" > "$MANIFEST_PATH" <<'NODE' const [version, releaseTag, assetName, apkUrl, sha256, checksumName, packageName, versionCode, minSdk, targetSdk] = process.argv.slice(2); -console.log(JSON.stringify({ name: 'android-snapshot-helper', version, releaseTag, assetName, apkUrl: apkUrl || null, sha256, checksumName, packageName, versionCode: Number(versionCode), instrumentationRunner: `${packageName}/.SnapshotInstrumentation`, minSdk: Number(minSdk), targetSdk: Number(targetSdk), outputFormat: 'uiautomator-xml', statusProtocol: 'android-snapshot-helper-v1' }, null, 2)); +console.log(JSON.stringify({ name: 'android-snapshot-helper', version, releaseTag, assetName, apkUrl: apkUrl || null, sha256, checksumName, packageName, versionCode: Number(versionCode), instrumentationRunner: `${packageName}/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation`, minSdk: Number(minSdk), targetSdk: Number(targetSdk), outputFormat: 'uiautomator-xml', statusProtocol: 'android-snapshot-helper-v1' }, null, 2)); NODE ;; ime) node - "$VERSION" "$APK_BASENAME" "$SHA256" "$PACKAGE_NAME" "$VERSION_CODE" > "$MANIFEST_PATH" <<'NODE' const [version, assetName, sha256, packageName, versionCode] = process.argv.slice(2); -console.log(JSON.stringify({ name: 'android-ime-helper', version, assetName, sha256, packageName, versionCode: Number(versionCode), serviceComponent: `${packageName}/.TestInputMethodService`, broadcastProtocol: 'android-ime-helper-v2' }, null, 2)); +console.log(JSON.stringify({ name: 'android-ime-helper', version, assetName, sha256, packageName, versionCode: Number(versionCode), serviceComponent: `${packageName}/com.callstack.agentdevice.imehelper.TestInputMethodService`, broadcastProtocol: 'android-ime-helper-v2' }, null, 2)); NODE ;; esac diff --git a/src/__tests__/android-snapshot-occlusion-context.test.ts b/src/__tests__/android-snapshot-occlusion-context.test.ts index 29525e0a8aa..b5b8701831a 100644 --- a/src/__tests__/android-snapshot-occlusion-context.test.ts +++ b/src/__tests__/android-snapshot-occlusion-context.test.ts @@ -71,7 +71,7 @@ function oneShotHelper(xml: string): AndroidAdbExecutor { if (args.includes('--show-versioncode')) { return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:999999', + stdout: `package:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName} versionCode:999999`, stderr: '', }; } diff --git a/src/__tests__/test-utils/android-ime-helper.ts b/src/__tests__/test-utils/android-ime-helper.ts index 8108318bf19..c0a56b73864 100644 --- a/src/__tests__/test-utils/android-ime-helper.ts +++ b/src/__tests__/test-utils/android-ime-helper.ts @@ -1,7 +1,7 @@ import { fileURLToPath } from 'node:url'; import type { AndroidImeHelperArtifact } from '@agent-device/platform-android/mechanics'; -const IME_HELPER_PACKAGE = 'com.callstack.agentdevice.imehelper'; +const IME_HELPER_PACKAGE = 'com.callstack.agentdevice.imehelper.v2'; const IME_HELPER_FIXTURE_APK_PATH = fileURLToPath( new URL('./fixtures/android-helper-apk.fixture', import.meta.url), ); @@ -21,7 +21,7 @@ export const ANDROID_IME_HELPER_FIXTURE_ARTIFACT: AndroidImeHelperArtifact = { sha256: IME_HELPER_FIXTURE_APK_SHA256, packageName: IME_HELPER_PACKAGE, versionCode: 13003, - serviceComponent: `${IME_HELPER_PACKAGE}/.TestInputMethodService`, + serviceComponent: `${IME_HELPER_PACKAGE}/com.callstack.agentdevice.imehelper.TestInputMethodService`, broadcastProtocol: 'android-ime-helper-v2', }, }; diff --git a/src/__tests__/test-utils/android-snapshot-helper.ts b/src/__tests__/test-utils/android-snapshot-helper.ts index 55d38858977..11c525000bc 100644 --- a/src/__tests__/test-utils/android-snapshot-helper.ts +++ b/src/__tests__/test-utils/android-snapshot-helper.ts @@ -1,7 +1,7 @@ import type { AndroidSnapshotHelperArtifact } from '@agent-device/platform-android/mechanics'; import { fileURLToPath } from 'node:url'; -const SNAPSHOT_HELPER_PACKAGE = 'com.callstack.agentdevice.snapshothelper'; +const SNAPSHOT_HELPER_PACKAGE = 'com.callstack.agentdevice.snapshothelper.v2'; const SNAPSHOT_HELPER_FIXTURE_APK_PATH = fileURLToPath( new URL('./fixtures/android-helper-apk.fixture', import.meta.url), ); @@ -17,7 +17,7 @@ export const ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT: AndroidSnapshotHelperArti sha256: SNAPSHOT_HELPER_FIXTURE_APK_SHA256, packageName: SNAPSHOT_HELPER_PACKAGE, versionCode: 13003, - instrumentationRunner: `${SNAPSHOT_HELPER_PACKAGE}/.SnapshotInstrumentation`, + instrumentationRunner: `${SNAPSHOT_HELPER_PACKAGE}/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation`, minSdk: 23, targetSdk: 36, outputFormat: 'uiautomator-xml', diff --git a/src/platform-runtime-android-application-tools.test.ts b/src/platform-runtime-android-application-tools.test.ts index c9182024391..829aa4e24da 100644 --- a/src/platform-runtime-android-application-tools.test.ts +++ b/src/platform-runtime-android-application-tools.test.ts @@ -5,11 +5,18 @@ const runtimeHints = vi.hoisted(() => ({ evaluated: false, clearRuntimeHintValues: vi.fn(async () => {}), })); +const restoreAndroidTestIme = vi.hoisted(() => + vi.fn(async () => ({ restored: false, reason: 'invalid-restore-target' as const })), +); vi.mock('./platform-runtime-runtime-hints.ts', () => { runtimeHints.evaluated = true; return { clearRuntimeHintValues: runtimeHints.clearRuntimeHintValues }; }); +vi.mock('@agent-device/platform-android/mechanics', async (importOriginal) => ({ + ...(await importOriginal()), + restoreAndroidTestIme, +})); const device: DeviceInfo = { platform: 'android', @@ -24,6 +31,7 @@ beforeEach(() => { vi.resetModules(); runtimeHints.evaluated = false; runtimeHints.clearRuntimeHintValues.mockClear(); + restoreAndroidTestIme.mockClear(); }); async function createTools() { @@ -56,3 +64,27 @@ test('clearing runtime hints loads the runtime-hints operation and hands it the }), ); }); + +test('close reports an invalid Android test IME restore target as incomplete', async () => { + const tools = await createTools(); + + await expect( + tools.restoreTestIme(device, { + stateDir: '/state', + shutdownTarget: false, + signal: new AbortController().signal, + }), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { + reason: 'android_test_ime_restore_incomplete', + deviceId: device.id, + hint: expect.stringContaining('Select a normal keyboard'), + }, + }); + expect(restoreAndroidTestIme).toHaveBeenCalledExactlyOnceWith(device, { + stateDir: '/state', + shutdownTarget: false, + signal: expect.any(AbortSignal), + }); +}); diff --git a/src/platform-runtime-android-application-tools.ts b/src/platform-runtime-android-application-tools.ts index 4c2c9f6e68a..2a9adaa96dd 100644 --- a/src/platform-runtime-android-application-tools.ts +++ b/src/platform-runtime-android-application-tools.ts @@ -104,11 +104,24 @@ export function createAndroidApplicationTools(): AndroidApplicationTools { shutdownTarget: input.shutdownTarget, signal: input.signal, }); - if (result.reason !== 'set-failed' && result.reason !== 'record-unreadable') return; + if ( + result.reason !== 'set-failed' && + result.reason !== 'record-unreadable' && + result.reason !== 'invalid-restore-target' + ) + return; throw new AppError( 'COMMAND_FAILED', `Android test IME could not be restored on ${device.name ?? device.id}.`, - { reason: ANDROID_TEST_IME_RESTORE_REASONS.restoreIncomplete.reason, deviceId: device.id }, + { + reason: ANDROID_TEST_IME_RESTORE_REASONS.restoreIncomplete.reason, + deviceId: device.id, + ...(result.reason === 'invalid-restore-target' + ? { + hint: 'The saved keyboard is another agent-device helper. Select a normal keyboard and clear the stale IME recovery settings before retrying.', + } + : {}), + }, ); }, recoverTestImeStartup: async (input) => { diff --git a/test/ci/release-workflow.test.ts b/test/ci/release-workflow.test.ts index f67b9f43f99..1e0203a3d11 100644 --- a/test/ci/release-workflow.test.ts +++ b/test/ci/release-workflow.test.ts @@ -9,6 +9,7 @@ const source = fs.readFileSync(path.join(repoRoot, '.github/workflows/release.ym type Job = { 'cache-mode'?: string; 'runs-on'?: string; + needs?: string[]; environment?: string; permissions?: Record; steps?: Array<{ @@ -59,6 +60,32 @@ test('the publisher authenticates through OIDC alone', () => { expect(setupNode?.with).not.toHaveProperty('registry-url'); }); +test('the build uses a disposable key only for dry runs until isolated release signing exists', () => { + const steps = workflow.jobs.build?.steps ?? []; + const refusal = steps.find( + (step) => step.name === 'Pause nightly and stable release until helper signing is isolated', + ); + const checkout = steps.find((step) => step.name === 'Checkout'); + expect(refusal?.if).toBe("needs.plan.outputs.mode != 'dry-run'"); + expect(steps.indexOf(refusal!)).toBeLessThan(steps.indexOf(checkout!)); + expect(workflow.jobs.publish?.needs).toEqual(['plan', 'build']); + const sdk = steps.find((step) => step.uses === './.github/actions/setup-android-sdk'); + expect(sdk?.with?.['ephemeral-helper-signing']).toBe('true'); + + const assetWorkflow = parse( + fs.readFileSync( + path.join(repoRoot, '.github/workflows/release-android-snapshot-helper.yml'), + 'utf8', + ), + ) as { permissions: unknown; jobs: Record }; + expect(assetWorkflow.permissions).toEqual({}); + const assetJob = assetWorkflow.jobs['publish-android-snapshot-helper']; + expect(assetJob?.steps?.map((step) => step.name)).toEqual([ + 'Refuse source checkout with the production signing key', + ]); + expect(secretsOf(assetJob ?? {})).toEqual([]); +}); + test('the release build uses a GitHub-hosted runner and restores no dependency cache', () => { expect(workflow.jobs.build?.['runs-on']).toBe('macos-26'); expect(workflow.jobs.build?.['cache-mode']).toBe('none'); diff --git a/test/integration/android-emulator-e2e/live-form-scenario.ts b/test/integration/android-emulator-e2e/live-form-scenario.ts index d7251c07dec..66ef8b7d4e8 100644 --- a/test/integration/android-emulator-e2e/live-form-scenario.ts +++ b/test/integration/android-emulator-e2e/live-form-scenario.ts @@ -15,8 +15,8 @@ import { type LiveContext, runStep, verifyBehavior, verifyCommand } from './live import { waitForImeWindow } from './live-ime-window.ts'; const C = PUBLIC_COMMANDS; -export const ANDROID_TEST_IME_PACKAGE = 'com.callstack.agentdevice.imehelper'; -const ANDROID_TEST_IME_SERVICE = `${ANDROID_TEST_IME_PACKAGE}/.TestInputMethodService`; +export const ANDROID_TEST_IME_PACKAGE = 'com.callstack.agentdevice.imehelper.v2'; +const ANDROID_TEST_IME_SERVICE = `${ANDROID_TEST_IME_PACKAGE}/com.callstack.agentdevice.imehelper.TestInputMethodService`; const KEYBOARD_VISIBILITY_TIMEOUT_MS = 10_000; const KEYBOARD_VISIBILITY_POLL_MS = 250; 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..4fd9ddd4d79 100644 --- a/test/integration/provider-scenarios/android-fill-capture-evidence.test.ts +++ b/test/integration/provider-scenarios/android-fill-capture-evidence.test.ts @@ -466,7 +466,7 @@ function adbStdout(key: string): string { 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 `package:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName} versionCode:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.versionCode}\n`; } return ''; } diff --git a/test/integration/provider-scenarios/android-ime-lifecycle-world.ts b/test/integration/provider-scenarios/android-ime-lifecycle-world.ts index 9ef2cac415b..281081f4984 100644 --- a/test/integration/provider-scenarios/android-ime-lifecycle-world.ts +++ b/test/integration/provider-scenarios/android-ime-lifecycle-world.ts @@ -14,7 +14,7 @@ export type AndroidProviderShellState = { const IME_INPUT_TEXT_ACTION = 'com.callstack.agentdevice.imehelper.ACTION_INPUT_TEXT_B64'; const IME_CLEAR_TEXT_ACTION = 'com.callstack.agentdevice.imehelper.ACTION_CLEAR_TEXT'; -const IME_PACKAGE = 'com.callstack.agentdevice.imehelper'; +const IME_PACKAGE = 'com.callstack.agentdevice.imehelper.v2'; const IME_PROTOCOL = 'android-ime-helper-v2'; /** @@ -90,12 +90,13 @@ export function androidImeLifecycleAdbResult( state: AndroidProviderShellState | undefined, ): AndroidImeAdbResult | undefined { if ( - key === 'shell cmd package list packages --show-versioncode com.callstack.agentdevice.imehelper' + key === + 'shell cmd package list packages --show-versioncode com.callstack.agentdevice.imehelper.v2' ) { // A newer provider-installed helper takes the actual durable activation/recovery path without // adding an unrelated helper-installation fixture to each scenario. return { - stdout: 'package:com.callstack.agentdevice.imehelper versionCode:999999\n', + stdout: 'package:com.callstack.agentdevice.imehelper.v2 versionCode:999999\n', stderr: '', exitCode: 0, }; diff --git a/test/integration/provider-scenarios/android-lifecycle.test.ts b/test/integration/provider-scenarios/android-lifecycle.test.ts index 928db618516..aa355678029 100644 --- a/test/integration/provider-scenarios/android-lifecycle.test.ts +++ b/test/integration/provider-scenarios/android-lifecycle.test.ts @@ -979,10 +979,8 @@ async function runAndroidCaptureInteractionAndReplayWorkflow( const logsBeforeClose = await client.observability.logs({ action: 'start', ...selection }); assert.equal(logsBeforeClose.started, true); - // close --save-script now requires the session to have been armed at open (recording-time - // target-v1 evidence cannot be reconstructed retroactively for a session that never recorded - // it). End this long-lived unarmed session plainly, then arm a fresh one before exercising - // close --save-script + shutdown below. + // End this unarmed session plainly. Then arm a fresh session before close --save-script and + // shutdown because recording evidence cannot be reconstructed after open. const plainCloseBeforeArm = await daemon.callCommand('close'); assert.equal(plainCloseBeforeArm.statusCode, 200, JSON.stringify(plainCloseBeforeArm.json)); assert.equal(await daemon.hasSession(), false); @@ -1163,7 +1161,9 @@ function assertAndroidInteractionContract(world: AndroidSettingsWorld): void { call[0] === 'shell' && call[1] === 'am' && call[2] === 'instrument' && - call.includes('com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation'), + call.includes( + 'com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation', + ), ), JSON.stringify(adbCalls), ); diff --git a/test/integration/provider-scenarios/android-tv-remote.test.ts b/test/integration/provider-scenarios/android-tv-remote.test.ts index e59c7ec5569..ff83cc962bd 100644 --- a/test/integration/provider-scenarios/android-tv-remote.test.ts +++ b/test/integration/provider-scenarios/android-tv-remote.test.ts @@ -22,7 +22,8 @@ test('Provider-backed integration Android TV remote flow sends navigation, hardw adbCalls.push([...args]); if (args.join(' ') === 'shell ime list -a -s') { return { - stdout: 'com.callstack.agentdevice.imehelper/.TestInputMethodService\n', + stdout: + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService\n', stderr: '', exitCode: 0, }; diff --git a/test/integration/provider-scenarios/android-world.ts b/test/integration/provider-scenarios/android-world.ts index e58e7711b5a..c04cae4076b 100644 --- a/test/integration/provider-scenarios/android-world.ts +++ b/test/integration/provider-scenarios/android-world.ts @@ -668,7 +668,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' + 'shell cmd package list packages --show-versioncode com.callstack.agentdevice.snapshothelper.v2' ) { return { stdout: '', stderr: '', exitCode: 1 }; } diff --git a/test/integration/provider-scenarios/composite-deadline.test.ts b/test/integration/provider-scenarios/composite-deadline.test.ts index ef2487f230b..80de16c7bf8 100644 --- a/test/integration/provider-scenarios/composite-deadline.test.ts +++ b/test/integration/provider-scenarios/composite-deadline.test.ts @@ -47,7 +47,7 @@ function deadlineAdbInfrastructureResponse( if (args.includes('--show-versioncode')) return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:999999', + stdout: `package:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName} versionCode:999999`, stderr: '', }; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'start') @@ -290,7 +290,7 @@ test('annotated replay capture aborts within its deadline without post-failure f if (args.includes('--show-versioncode')) return { exitCode: 0, - stdout: 'package:com.callstack.agentdevice.snapshothelper versionCode:999999', + stdout: `package:${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName} versionCode:999999`, stderr: '', }; if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'start') diff --git a/test/repo-guards/release-assets.test.ts b/test/repo-guards/release-assets.test.ts index c75768bc275..3ad6fea0506 100644 --- a/test/repo-guards/release-assets.test.ts +++ b/test/repo-guards/release-assets.test.ts @@ -7,7 +7,7 @@ import { parse } from 'yaml'; import { mkdtempForTestSync } from '@agent-device/test-kit'; const repo = path.resolve(import.meta.dirname, '../..'); -const workflows = ['release-ios-runner.yml', 'release-android-snapshot-helper.yml']; +const metadataWorkflows = ['release-ios-runner.yml']; const test = vitestTest.skipIf(process.platform === 'win32'); type Step = { @@ -142,7 +142,8 @@ printf signed > "$output"`, } const snapshot = path.join(f.root, 'android', 'snapshot-helper'); fs.mkdirSync(snapshot, { recursive: true }); - fs.writeFileSync(path.join(snapshot, 'debug.keystore'), ''); + const keystore = path.join(f.root, 'android-helper.jks'); + fs.writeFileSync(keystore, ''); for (const sourceSet of ['main', 'test']) { fs.mkdirSync(path.join(f.root, 'android', `${helper}-helper`, 'src', sourceSet, 'java'), { recursive: true, @@ -155,6 +156,10 @@ printf signed > "$output"`, ANDROID_HOME: sdk, AGENT_DEVICE_ANDROID_BUILD_TOOLS: '36.0.0', AGENT_DEVICE_ANDROID_HELPER: helper, + AGENT_DEVICE_ANDROID_KEYSTORE: keystore, + AGENT_DEVICE_ANDROID_KEY_ALIAS: 'android-helper', + AGENT_DEVICE_ANDROID_KEYSTORE_PASSWORD: 'fixture-store-password', + AGENT_DEVICE_ANDROID_KEY_PASSWORD: 'fixture-key-password', FIXTURE_AAPT_ARGS: path.join(f.root, 'aapt-args'), }, }; @@ -179,7 +184,7 @@ function metadataStep(workflow: string): Step { return step; } -for (const workflow of workflows) { +for (const workflow of metadataWorkflows) { for (const [label, makeTag, valid] of [ ['stable', () => 'v1.2.3', true], ['development', () => 'v1.2.3-dev', true], @@ -248,6 +253,23 @@ for (const workflow of workflows) { } } +test('Android helper release refuses before source checkout or metadata execution', () => { + const steps = workflowSteps('release-android-snapshot-helper.yml'); + assert.deepEqual( + steps.map((step) => step.name), + ['Refuse source checkout with the production signing key'], + ); + const f = fixture(); + const result = spawnSync('/bin/bash', ['-e', '-c', steps[0]!.run!], { + cwd: f.root, + env: f.env, + encoding: 'utf8', + }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /isolated signer and a stable external key/); + assert.equal(fs.existsSync(f.env.FIXTURE_BUILD_MARKER), false); +}); + test('package scripts reject invalid input before build or output', () => { const f = fixture(); for (const tag of ['v1.2.3-01', 'v1.2.3\n', 'v1.2.3"bad', `v1.2.3$(touch ${f.marker})`]) { @@ -312,15 +334,23 @@ for (const [version, tag] of [ } else { assert.equal(manifest.versionCode, 123); assert.equal(manifest.assetName, `agent-device-android-${helper}-helper-${version}.apk`); + assert.equal( + manifest.packageName, + `com.callstack.agentdevice.${helper === 'snapshot' ? 'snapshothelper' : 'imehelper'}.v2`, + ); if (helper === 'snapshot') { assert.equal(manifest.releaseTag, tag); assert.equal(manifest.minSdk, 23); assert.equal(manifest.targetSdk, 36); assert.equal(manifest.apkUrl, assetUrl(manifest.assetName)); + assert.equal( + manifest.instrumentationRunner, + 'com.callstack.agentdevice.snapshothelper.v2/com.callstack.agentdevice.snapshothelper.SnapshotInstrumentation', + ); } else { assert.equal( manifest.serviceComponent, - 'com.callstack.agentdevice.imehelper/.TestInputMethodService', + 'com.callstack.agentdevice.imehelper.v2/com.callstack.agentdevice.imehelper.TestInputMethodService', ); } } @@ -329,6 +359,20 @@ for (const [version, tag] of [ } } +test('Android helper signing inputs fail before Java compilation', () => { + const f = androidBuildFixture('snapshot'); + f.tool('javac', 'printf compiled > "$FIXTURE_BUILD_MARKER"'); + const result = run( + f.root, + { ...f.env, AGENT_DEVICE_ANDROID_KEYSTORE: '' }, + path.join(f.scripts, 'build-android-helper.sh'), + ['1.2.3', path.join(f.root, 'output')], + ); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /AGENT_DEVICE_ANDROID_KEYSTORE must name/); + assert.equal(fs.existsSync(f.env.FIXTURE_BUILD_MARKER), false); +}); + for (const helper of ['snapshot', 'ime'] as const) { for (const version of ['1.2.3', '1.2.3-dev', '1.2.3+build.42', '1.2.3-rc.1+build.42']) { test(`${helper} ${version} preserves the base release version code`, () => {