Skip to content

Commit 72ce59f

Browse files
committed
fix(android): reinstall and reselect the test IME helper after it disappears
1 parent 3d48bb9 commit 72ce59f

3 files changed

Lines changed: 164 additions & 8 deletions

File tree

‎packages/platform-android/src/__tests__/ime-helper.test.ts‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import type { AndroidAdbExecutor, AndroidAdbProvider } from '../adb-executor.ts'
1515
import { mkdtempForTest } from './test-utils/tmp-dir.ts';
1616

1717
const PACKAGE = 'com.callstack.agentdevice.imehelper';
18+
const LATIN_IME = 'com.google.android.inputmethod.latin/com.android.inputmethod.latin.LatinIME';
1819

1920
const manifest = {
2021
name: 'android-ime-helper' as const,
@@ -90,6 +91,9 @@ test('ensureAndroidImeHelper installs with semantic provider install options', a
9091
if (args.includes('--show-versioncode')) {
9192
return { exitCode: 1, stdout: '', stderr: 'not found' };
9293
}
94+
if (isImeListCall(args)) {
95+
return { exitCode: 0, stdout: `${manifest.serviceComponent}\n`, stderr: '' };
96+
}
9397
throw new Error(`unexpected adb call: ${args.join(' ')}`);
9498
};
9599
const adbProvider: AndroidAdbProvider = {
@@ -147,6 +151,118 @@ test('ensureAndroidImeHelper skips install when a newer version is already prese
147151
assert.equal(result.reason, 'current');
148152
});
149153

154+
test('ensureAndroidImeHelper returns from an install once the IME is registered', async () => {
155+
const tmpDir = await mkdtempForTest('ime-helper-registration-');
156+
const apkPath = path.join(tmpDir, 'helper.apk');
157+
await fs.writeFile(apkPath, 'helper-apk');
158+
let imeListCalls = 0;
159+
const adb: AndroidAdbExecutor = async (args) => {
160+
if (args.includes('--show-versioncode')) {
161+
return { exitCode: 0, stdout: '', stderr: '' };
162+
}
163+
if (isImeListCall(args)) {
164+
imeListCalls += 1;
165+
const helper = imeListCalls > 1 ? `${manifest.serviceComponent}\n` : '';
166+
return { exitCode: 0, stdout: `${LATIN_IME}\n${helper}`, stderr: '' };
167+
}
168+
throw new Error(`unexpected adb call: ${args.join(' ')}`);
169+
};
170+
const adbProvider: AndroidAdbProvider = {
171+
exec: adb,
172+
install: async () => ({ exitCode: 0, stdout: 'Success', stderr: '' }),
173+
};
174+
175+
const result = await ensureAndroidImeHelper({
176+
adb,
177+
adbProvider,
178+
artifact: { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } },
179+
deviceKey: 'android:emulator-5554',
180+
});
181+
182+
assert.equal(result.installed, true);
183+
assert.equal(imeListCalls, 2);
184+
});
185+
186+
test('ensureAndroidImeHelper returns the install when the registration listing times out', async () => {
187+
const tmpDir = await mkdtempForTest('ime-helper-registration-timeout-');
188+
const apkPath = path.join(tmpDir, 'helper.apk');
189+
await fs.writeFile(apkPath, 'helper-apk');
190+
const adb: AndroidAdbExecutor = async (args) => {
191+
if (args.includes('--show-versioncode')) {
192+
return { exitCode: 0, stdout: '', stderr: '' };
193+
}
194+
if (isImeListCall(args)) {
195+
throw new AppError('COMMAND_FAILED', 'adb timed out after 5000ms', {
196+
stdout: '',
197+
stderr: '',
198+
exitCode: 1,
199+
timeoutMs: 5_000,
200+
});
201+
}
202+
throw new Error(`unexpected adb call: ${args.join(' ')}`);
203+
};
204+
const adbProvider: AndroidAdbProvider = {
205+
exec: adb,
206+
install: async () => ({ exitCode: 0, stdout: 'Success', stderr: '' }),
207+
};
208+
209+
const result = await ensureAndroidImeHelper({
210+
adb,
211+
adbProvider,
212+
artifact: { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } },
213+
deviceKey: 'android:emulator-5554',
214+
});
215+
216+
assert.equal(result.installed, true);
217+
});
218+
219+
test('ensureAndroidImeHelper reinstalls a remembered helper the device no longer has', async () => {
220+
const tmpDir = await mkdtempForTest('ime-helper-removed-');
221+
const apkPath = path.join(tmpDir, 'helper.apk');
222+
await fs.writeFile(apkPath, 'helper-apk');
223+
let present = false;
224+
const adb: AndroidAdbExecutor = async (args) => {
225+
if (args.includes('--show-versioncode')) {
226+
return present
227+
? {
228+
exitCode: 0,
229+
stdout: `package:${manifest.packageName} versionCode:${manifest.versionCode}`,
230+
stderr: '',
231+
}
232+
: { exitCode: 0, stdout: '', stderr: '' };
233+
}
234+
if (isImeListCall(args)) {
235+
return { exitCode: 0, stdout: `${manifest.serviceComponent}\n`, stderr: '' };
236+
}
237+
throw new Error(`unexpected adb call: ${args.join(' ')}`);
238+
};
239+
let installs = 0;
240+
const adbProvider: AndroidAdbProvider = {
241+
exec: adb,
242+
install: async () => {
243+
installs += 1;
244+
present = true;
245+
return { exitCode: 0, stdout: '', stderr: '' };
246+
},
247+
};
248+
const ensure = () =>
249+
ensureAndroidImeHelper({
250+
adb,
251+
adbProvider,
252+
artifact: { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } },
253+
deviceKey: 'android:emulator-5554',
254+
});
255+
256+
assert.equal((await ensure()).installed, true);
257+
assert.equal((await ensure()).installed, false);
258+
present = false;
259+
const result = await ensure();
260+
261+
assert.equal(result.installed, true);
262+
assert.equal(result.reason, 'missing');
263+
assert.equal(installs, 2);
264+
});
265+
150266
test('ensureAndroidImeHelper install timeout points at the OEM install dialog', async () => {
151267
const tmpDir = await mkdtempForTest('ime-helper-install-timeout-');
152268
const apkPath = path.join(tmpDir, 'helper.apk');
@@ -189,6 +305,10 @@ test('ensureAndroidImeHelper install timeout points at the OEM install dialog',
189305
);
190306
});
191307

308+
function isImeListCall(args: readonly string[]): boolean {
309+
return args.includes('ime') && args.includes('list');
310+
}
311+
192312
function sha256Text(text: string): string {
193313
return crypto.createHash('sha256').update(text).digest('hex');
194314
}

‎packages/platform-android/src/helper-package-install.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -66,13 +66,18 @@ async function ensureAndroidHelperPackageInstalled(options: {
6666
} = options;
6767
const cacheKey = `${deviceKey}\0${packageName}\0${versionCode}\0${sha256}`;
6868
if (cache.has(cacheKey)) {
69-
return {
70-
packageName,
71-
versionCode,
72-
installedSha256: sha256,
73-
installed: false,
74-
reason: 'current',
75-
};
69+
// The cache skips the checksums, never the presence check: an emulator that is wiped or
70+
// restored from a snapshot keeps its serial but may no longer have the helper.
71+
const installedVersionCode = await readInstalledAndroidPackageVersionCode(adb, packageName);
72+
if (installedVersionCode !== undefined && installedVersionCode >= versionCode) {
73+
return {
74+
packageName,
75+
versionCode,
76+
installedSha256: sha256,
77+
installed: false,
78+
reason: 'current',
79+
};
80+
}
7681
}
7782
await verifyAndroidHelperApkChecksum(apkPath, sha256, helperLabel);
7883
const state = await inspectInstalledAndroidHelper({

‎packages/platform-android/src/ime-helper.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { AppError } from '@agent-device/kernel/errors';
22
import type { DeviceInfo } from '@agent-device/kernel/device';
3+
import { isCommandTimeoutError } from '@agent-device/host-kit/command';
4+
import { sleep } from '@agent-device/host-kit/retry';
35
import {
46
readAndroidHelperManifestInteger,
57
readAndroidHelperManifestLiteral,
@@ -28,6 +30,8 @@ const ANDROID_IME_HELPER_PROTOCOL = 'android-ime-helper-v1';
2830
export const ANDROID_IME_HELPER_SERVICE_COMPONENT = ANDROID_IME_HELPER_SERVICE;
2931
const ANDROID_IME_HELPER_INSTALL_TIMEOUT_MS = 30_000;
3032
const ANDROID_IME_HELPER_BROADCAST_TIMEOUT_MS = 10_000;
33+
const ANDROID_IME_HELPER_REGISTRATION_TIMEOUT_MS = 5_000;
34+
const ANDROID_IME_HELPER_REGISTRATION_POLL_MS = 100;
3135

3236
const ACTION_INPUT_TEXT_B64 = 'com.callstack.agentdevice.imehelper.ACTION_INPUT_TEXT_B64';
3337
const ACTION_CLEAR_TEXT = 'com.callstack.agentdevice.imehelper.ACTION_CLEAR_TEXT';
@@ -109,14 +113,41 @@ export async function ensureAndroidImeHelper(options: {
109113
artifact: AndroidImeHelperArtifact;
110114
deviceKey: string;
111115
}): Promise<AndroidHelperInstallDecision> {
112-
return await requireAndroidAdbHost().ensureHelperInstalled(
116+
const decision = await requireAndroidAdbHost().ensureHelperInstalled(
113117
{
114118
cache: installedImeHelpers,
115119
installTimeoutMs: ANDROID_IME_HELPER_INSTALL_TIMEOUT_MS,
116120
helperLabel: HELPER_LABEL,
117121
},
118122
options,
119123
);
124+
if (decision.installed) {
125+
await waitForAndroidImeRegistration(options.adb, options.artifact.manifest.serviceComponent);
126+
}
127+
return decision;
128+
}
129+
130+
// `adb install` returns before the input method manager registers the new service, and until it
131+
// does, `ime enable` and `ime set` reject it as unknown. The wait is best-effort: once its budget
132+
// runs out, the activation's read-back reports the refusal.
133+
async function waitForAndroidImeRegistration(
134+
adb: AndroidAdbExecutor,
135+
serviceComponent: string,
136+
): Promise<void> {
137+
const deadline = Date.now() + ANDROID_IME_HELPER_REGISTRATION_TIMEOUT_MS;
138+
while (Date.now() < deadline) {
139+
try {
140+
const result = await runAdbShell(adb, ['ime', 'list', '-a', '-s'], {
141+
allowFailure: true,
142+
timeoutMs: Math.max(1, deadline - Date.now()),
143+
});
144+
if (result.stdout.split(/\r?\n/).includes(serviceComponent)) return;
145+
} catch (error) {
146+
if (isCommandTimeoutError(error)) return;
147+
throw error;
148+
}
149+
await sleep(ANDROID_IME_HELPER_REGISTRATION_POLL_MS);
150+
}
120151
}
121152

122153
/**

0 commit comments

Comments
 (0)