|
| 1 | +import { resolveCommandTimeoutPolicy } from '@agent-device/command-registry/registry'; |
| 2 | +import { resolveCommandRequestTimeoutMs } from '@agent-device/command-registry/timeout-policy'; |
| 3 | +import { LONG_PRESS_DURATION_MAX_MS } from '@agent-device/contracts/gesture-plan-types'; |
| 4 | +import type { |
| 5 | + AndroidAdbExecutorOptions, |
| 6 | + AndroidAdbExecutorResult, |
| 7 | + AndroidAdbProvider, |
| 8 | +} from '@agent-device/platform-android/mechanics'; |
| 9 | +import assert from 'node:assert/strict'; |
| 10 | +import fs from 'node:fs'; |
| 11 | +import { test, vi } from 'vitest'; |
| 12 | +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; |
| 13 | +import { respondToAndroidSettingsAdbCommand } from './android-world.ts'; |
| 14 | +import { assertRpcOk } from './assertions.ts'; |
| 15 | +import { PROVIDER_SCENARIO_ANDROID } from './fixtures.ts'; |
| 16 | +import { createProviderScenarioHarness } from './harness.ts'; |
| 17 | + |
| 18 | +// The longpress envelope must outlast the Android cold-helper route's worst case plus the margin |
| 19 | +// that lets the daemon's own typed result arrive first; otherwise the client gives up on a request |
| 20 | +// the device is still finishing. This test proves that bound against the real route: it imports no platform-android step figure, so it stays true |
| 21 | +// however the route's steps change. The only imported figure is the hold cap the validator reads. |
| 22 | +type LongPressLedgerCall = Readonly<{ |
| 23 | + tool: 'exec' | 'install' | 'pull'; |
| 24 | + args: readonly string[]; |
| 25 | + timeoutMs: number; |
| 26 | +}>; |
| 27 | + |
| 28 | +const HELPER = ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest; |
| 29 | +const HELPER_REMOTE_APK = `/data/app/~~ledger/${HELPER.packageName}/base.apk`; |
| 30 | +const ok: AndroidAdbExecutorResult = { stdout: '', stderr: '', exitCode: 0 }; |
| 31 | + |
| 32 | +function gestureHelperOutput(): string { |
| 33 | + return [ |
| 34 | + `INSTRUMENTATION_RESULT: agentDeviceProtocol=${HELPER.statusProtocol}`, |
| 35 | + 'INSTRUMENTATION_RESULT: helperApiVersion=1', |
| 36 | + 'INSTRUMENTATION_RESULT: ok=true', |
| 37 | + 'INSTRUMENTATION_RESULT: kind=swipe', |
| 38 | + 'INSTRUMENTATION_CODE: 0', |
| 39 | + ].join('\n'); |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * The slowest cold-helper branch the route allows: the installed helper reports the bundled |
| 44 | + * versionCode, so identity falls through to the APK checksum (`pm path` + pull); the pulled APK |
| 45 | + * mismatches, so the helper is replaced; the first replace is rejected as |
| 46 | + * INSTALL_FAILED_UPDATE_INCOMPATIBLE, so the route uninstalls and installs again; then the hold runs |
| 47 | + * one-shot because no live helper session exists. |
| 48 | + */ |
| 49 | +function createLongPressLedgerAdbProvider(params: { |
| 50 | + isTracking: () => boolean; |
| 51 | + onCall: (call: LongPressLedgerCall) => void; |
| 52 | +}): { provider: AndroidAdbProvider; ledger: LongPressLedgerCall[] } { |
| 53 | + const ledger: LongPressLedgerCall[] = []; |
| 54 | + let installAttempts = 0; |
| 55 | + // A call without a bounded timeoutMs is not a worst case the envelope assertion can see, so it |
| 56 | + // fails the test rather than costing 0 virtual ms. |
| 57 | + const record = ( |
| 58 | + tool: LongPressLedgerCall['tool'], |
| 59 | + args: readonly string[], |
| 60 | + options?: AndroidAdbExecutorOptions, |
| 61 | + ): void => { |
| 62 | + if (!params.isTracking()) return; |
| 63 | + assert.ok( |
| 64 | + Number.isFinite(options?.timeoutMs) && options!.timeoutMs! > 0, |
| 65 | + `longpress ledger call has no bounded timeoutMs: ${tool} ${args.join(' ')}`, |
| 66 | + ); |
| 67 | + const call: LongPressLedgerCall = { tool, args: [...args], timeoutMs: options!.timeoutMs! }; |
| 68 | + ledger.push(call); |
| 69 | + params.onCall(call); |
| 70 | + }; |
| 71 | + const provider: AndroidAdbProvider = { |
| 72 | + snapshotHelperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, |
| 73 | + exec: async (args, options) => { |
| 74 | + record('exec', args, options); |
| 75 | + if (args.includes('--show-versioncode') && args.includes(HELPER.packageName)) { |
| 76 | + return { |
| 77 | + ...ok, |
| 78 | + stdout: `package:${HELPER.packageName} versionCode:${HELPER.versionCode}\n`, |
| 79 | + }; |
| 80 | + } |
| 81 | + if (args[0] === 'shell' && args[1] === 'pm' && args[2] === 'path') { |
| 82 | + return { ...ok, stdout: `package:${HELPER_REMOTE_APK}\n` }; |
| 83 | + } |
| 84 | + if (args[0] === 'uninstall' && args[1] === HELPER.packageName) { |
| 85 | + return { ...ok, stdout: 'Success\n' }; |
| 86 | + } |
| 87 | + if (args.includes('instrument') && args.includes('gesture')) { |
| 88 | + return { ...ok, stdout: gestureHelperOutput() }; |
| 89 | + } |
| 90 | + if (args[0] === 'shell' && args[1] === 'am' && args[2] === 'start') { |
| 91 | + return { ...ok, stdout: 'Starting: Intent' }; |
| 92 | + } |
| 93 | + return respondToAndroidSettingsAdbCommand([...args], '', '', {}); |
| 94 | + }, |
| 95 | + pull: async (remotePath, localPath, options) => { |
| 96 | + record('pull', [remotePath, localPath], options); |
| 97 | + fs.writeFileSync(localPath, 'a previously installed helper build'); |
| 98 | + return ok; |
| 99 | + }, |
| 100 | + install: async (apkPath, options) => { |
| 101 | + record('install', [apkPath], options); |
| 102 | + installAttempts += 1; |
| 103 | + if (installAttempts === 1) { |
| 104 | + return { |
| 105 | + stdout: '', |
| 106 | + stderr: 'Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE: signatures do not match]', |
| 107 | + exitCode: 1, |
| 108 | + }; |
| 109 | + } |
| 110 | + return { ...ok, stdout: 'Success\n' }; |
| 111 | + }, |
| 112 | + }; |
| 113 | + return { provider, ledger }; |
| 114 | +} |
| 115 | + |
| 116 | +function gestureDurationMs(call: LongPressLedgerCall): number | undefined { |
| 117 | + const payloadIndex = call.args.indexOf('payloadBase64'); |
| 118 | + if (payloadIndex < 0) return undefined; |
| 119 | + const payload = JSON.parse( |
| 120 | + Buffer.from(call.args[payloadIndex + 1]!, 'base64').toString('utf8'), |
| 121 | + ) as { durationMs?: unknown }; |
| 122 | + return typeof payload.durationMs === 'number' ? payload.durationMs : undefined; |
| 123 | +} |
| 124 | + |
| 125 | +function assertLongPressLedgerPhaseCoverage(ledger: readonly LongPressLedgerCall[]): void { |
| 126 | + const printed = `\nLedger:\n${JSON.stringify(ledger, null, 2)}`; |
| 127 | + const isVersionRead = (call: LongPressLedgerCall) => |
| 128 | + call.tool === 'exec' && call.args.includes('--show-versioncode'); |
| 129 | + const isApkPathRead = (call: LongPressLedgerCall) => |
| 130 | + call.tool === 'exec' && call.args.includes('pm') && call.args.includes('path'); |
| 131 | + const isGesture = (call: LongPressLedgerCall) => |
| 132 | + call.tool === 'exec' && call.args.includes('instrument') && call.args.includes('gesture'); |
| 133 | + |
| 134 | + assert.ok(ledger.some(isVersionRead), `ledger is missing the helper version read${printed}`); |
| 135 | + assert.ok(ledger.some(isApkPathRead), `ledger is missing the helper APK path read${printed}`); |
| 136 | + assert.ok( |
| 137 | + ledger.some((call) => call.tool === 'pull'), |
| 138 | + `ledger is missing the helper APK pull${printed}`, |
| 139 | + ); |
| 140 | + assert.equal( |
| 141 | + ledger.filter((call) => call.tool === 'install').length, |
| 142 | + 2, |
| 143 | + `ledger must record the rejected helper install and its retry${printed}`, |
| 144 | + ); |
| 145 | + assert.ok( |
| 146 | + ledger.some((call) => call.args[0] === 'uninstall'), |
| 147 | + `ledger is missing the incompatible-helper uninstall${printed}`, |
| 148 | + ); |
| 149 | + const gestures = ledger.filter(isGesture); |
| 150 | + assert.equal(gestures.length, 1, `ledger must record exactly one gesture dispatch${printed}`); |
| 151 | + assert.equal( |
| 152 | + gestureDurationMs(gestures[0]!), |
| 153 | + LONG_PRESS_DURATION_MAX_MS, |
| 154 | + `the gesture dispatch must carry the maximum hold${printed}`, |
| 155 | + ); |
| 156 | +} |
| 157 | + |
| 158 | +test('longpress cold-helper worst-case ledger covers the client envelope with the daemon-result margin', async () => { |
| 159 | + // Matches REQUEST_TIMEOUT_BUDGET_MARGIN_MS, packages/command-registry/src/timeout-policy.ts. |
| 160 | + // Not imported: it is not exported (fallow would flag an export used only by a test). |
| 161 | + const REQUIRED_DAEMON_RESULT_MARGIN_MS = 30_000; |
| 162 | + |
| 163 | + let virtualElapsedMs = 0; |
| 164 | + let tracking = false; |
| 165 | + const { provider, ledger } = createLongPressLedgerAdbProvider({ |
| 166 | + isTracking: () => tracking, |
| 167 | + onCall: (call) => { |
| 168 | + virtualElapsedMs += Math.max(0, call.timeoutMs - 1); |
| 169 | + }, |
| 170 | + }); |
| 171 | + const dateSpy = vi.spyOn(Date, 'now'); |
| 172 | + const daemon = await createProviderScenarioHarness({ |
| 173 | + deviceInventoryProvider: async () => [PROVIDER_SCENARIO_ANDROID], |
| 174 | + androidAdbProvider: () => provider, |
| 175 | + }); |
| 176 | + const selection = { platform: 'android', serial: PROVIDER_SCENARIO_ANDROID.id } as const; |
| 177 | + const positionals = ['195', '320', String(LONG_PRESS_DURATION_MAX_MS)]; |
| 178 | + try { |
| 179 | + await daemon.client().apps.open({ app: 'com.android.settings', ...selection, testIme: false }); |
| 180 | + tracking = true; |
| 181 | + const originNowMs = Date.now(); |
| 182 | + dateSpy.mockImplementation(() => originNowMs + virtualElapsedMs); |
| 183 | + assertRpcOk(await daemon.callCommand('longpress', positionals, selection)); |
| 184 | + } finally { |
| 185 | + dateSpy.mockRestore(); |
| 186 | + await daemon.close(); |
| 187 | + } |
| 188 | + |
| 189 | + assertLongPressLedgerPhaseCoverage(ledger); |
| 190 | + |
| 191 | + const envelopeMs = resolveCommandRequestTimeoutMs(resolveCommandTimeoutPolicy('longpress'), { |
| 192 | + positionals, |
| 193 | + flags: {}, |
| 194 | + }); |
| 195 | + assert.ok(envelopeMs !== undefined, 'longpress must declare a bounded envelope'); |
| 196 | + assert.ok( |
| 197 | + virtualElapsedMs + REQUIRED_DAEMON_RESULT_MARGIN_MS <= envelopeMs, |
| 198 | + `longpress ledger worst case (${virtualElapsedMs}ms) + ${REQUIRED_DAEMON_RESULT_MARGIN_MS}ms ` + |
| 199 | + `margin exceeds the ${envelopeMs}ms envelope.\nLedger:\n${JSON.stringify(ledger, null, 2)}`, |
| 200 | + ); |
| 201 | +}, 20_000); |
0 commit comments