Skip to content

Commit a8acc11

Browse files
committed
refactor(android): reduce IME lifecycle branching
1 parent 937eea9 commit a8acc11

4 files changed

Lines changed: 88 additions & 111 deletions

File tree

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

Lines changed: 46 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
readAndroidTestImeDeviceRecord,
1616
restorePriorPersistedIme,
1717
writePersistedPreviousIme,
18+
type AndroidTestImeDeviceRecord,
1819
} from './ime-settings-record.ts';
1920
import { activeTestImeDevices, withAndroidTestImeRecoveryLock } from './ime-state.ts';
2021

@@ -93,26 +94,7 @@ async function activateAndroidTestImeAfterStartupRecovery(
9394

9495
const currentIme = await readAndroidDefaultInputMethod(adb);
9596
if (currentIme === manifest.serviceComponent) {
96-
// Already active (idempotent call, or a previous crashed daemon left it active); keep the
97-
// existing persisted previous-IME record rather than overwriting it, but make sure this
98-
// process's crash is covered by a recovery marker.
99-
const markerPersisted = await markers.write(options.stateDir, device.id);
100-
const record = await readAndroidTestImeDeviceRecord(adb);
101-
if (markerPersisted) {
102-
// A rebind the device record marks, or may mark, still needs a confirmed one before text entry.
103-
const rebindUnconfirmed = record.kind === 'unreadable' || record.rebindDisplaced;
104-
activeTestImeDevices.set(deviceKey, { stateDir: options.stateDir, rebindUnconfirmed });
105-
}
106-
const previousIme = record.kind === 'owned' ? record.previousIme : undefined;
107-
return {
108-
outcome: 'settled',
109-
activated: false,
110-
alreadyActive: true,
111-
...(markerPersisted ? {} : { persistFailed: true }),
112-
previousIme,
113-
helperServiceComponent: manifest.serviceComponent,
114-
helperPackageName: manifest.packageName,
115-
};
97+
return await claimAlreadyActiveTestIme(device, manifest, options.stateDir);
11698
}
11799

118100
const record = await readAndroidTestImeDeviceRecord(adb);
@@ -131,10 +113,7 @@ async function activateAndroidTestImeAfterStartupRecovery(
131113
helperPackageName: manifest.packageName,
132114
};
133115
}
134-
const priorPersistedIme = record.kind === 'owned' ? record.previousIme : undefined;
135-
// Android's fallback after a failed rebind must not replace the user's restore target.
136-
const previousIme =
137-
record.kind === 'owned' && record.rebindDisplaced ? record.previousIme : currentIme;
116+
const { previousIme, priorPersistedIme } = activationRestoreTarget(record, currentIme);
138117
if (!(await writePersistedPreviousIme(adb, previousIme))) {
139118
await restorePriorPersistedIme(adb, priorPersistedIme, device.id);
140119
emitAndroidAdbDiagnostic({
@@ -228,3 +207,46 @@ async function activateAndroidTestImeAfterStartupRecovery(
228207
helperPackageName: manifest.packageName,
229208
};
230209
}
210+
211+
async function claimAlreadyActiveTestIme(
212+
device: DeviceInfo,
213+
manifest: Awaited<ReturnType<typeof selectAndroidImeHelperArtifact>>['manifest'],
214+
stateDir: string,
215+
): Promise<AndroidTestImeActivationResult> {
216+
const adb = resolveAndroidAdbExecutor(device);
217+
const deviceKey = getAndroidImeHelperDeviceKey(device);
218+
// Already active (idempotent call, or a previous crashed daemon left it active); keep the
219+
// existing persisted previous-IME record rather than overwriting it, but make sure this
220+
// process's crash is covered by a recovery marker.
221+
const markerPersisted = await requireAndroidAdbHost().imeRecoveryMarkers.write(
222+
stateDir,
223+
device.id,
224+
);
225+
const record = await readAndroidTestImeDeviceRecord(adb);
226+
if (markerPersisted) {
227+
// A rebind the device record marks, or may mark, still needs a confirmed one before text entry.
228+
const rebindUnconfirmed = record.kind === 'unreadable' || record.rebindDisplaced;
229+
activeTestImeDevices.set(deviceKey, { stateDir, rebindUnconfirmed });
230+
}
231+
const previousIme = record.kind === 'owned' ? record.previousIme : undefined;
232+
return {
233+
outcome: 'settled',
234+
activated: false,
235+
alreadyActive: true,
236+
...(markerPersisted ? {} : { persistFailed: true }),
237+
previousIme,
238+
helperServiceComponent: manifest.serviceComponent,
239+
helperPackageName: manifest.packageName,
240+
};
241+
}
242+
243+
function activationRestoreTarget(
244+
record: Exclude<AndroidTestImeDeviceRecord, { kind: 'unreadable' }>,
245+
currentIme: string,
246+
): { previousIme: string; priorPersistedIme: string | undefined } {
247+
if (record.kind === 'absent') return { previousIme: currentIme, priorPersistedIme: undefined };
248+
return {
249+
previousIme: record.rebindDisplaced ? record.previousIme : currentIme,
250+
priorPersistedIme: record.previousIme,
251+
};
252+
}

‎packages/platform-android/src/ime-rebind.test.ts‎

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,6 @@ test("a rebind that displaces the helper keeps ownership and the user's IME as r
7575
expect(isAndroidTestImeActive(DEVICE)).toBe(true);
7676
expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([DEVICE.id]);
7777
expect(state.settings.get('agent_device_ime_helper_rebind_displaced')).toBe('1');
78-
expect(host.diagnostics).toContainEqual({
79-
phase: 'android_test_ime_rebind_failed',
80-
level: 'warn',
81-
});
8278

8379
// The next open finds Android's fallback IME current; it must not become the restore target.
8480
state.imeSetFails = false;
@@ -116,18 +112,14 @@ test('a close-time restore waits for an in-flight rebind instead of racing it',
116112
helperSetReached = resolve;
117113
});
118114

119-
await withAndroidAdbProvider(
120-
{
121-
exec: async (args) => {
122-
if (args[2] === 'set' && args[3] === HELPER_SERVICE) {
123-
helperSetReached();
124-
await helperSetGate;
125-
}
126-
return await deviceAdb(args);
127-
},
128-
imeHelperArtifact: ARTIFACT,
115+
await withDeviceAdb(
116+
async (args) => {
117+
if (args[2] === 'set' && args[3] === HELPER_SERVICE) {
118+
helperSetReached();
119+
await helperSetGate;
120+
}
121+
return await deviceAdb(args);
129122
},
130-
{ serial: DEVICE.id },
131123
async () => {
132124
const rebind = rebindAndroidTestIme(DEVICE);
133125
await reachedHelperSet;
@@ -207,10 +199,6 @@ test('a confirmed rebind whose device record stays set is retried at the next en
207199
expect(state.settings.get('agent_device_ime_helper_previous_ime')).toBe('com.samsung/.Keyboard');
208200
expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([DEVICE.id]);
209201
expect(state.settings.get(REBIND_DISPLACED)).toBe('1');
210-
expect(host.diagnostics).toContainEqual({
211-
phase: 'android_test_ime_rebind_record_clear_failed',
212-
level: 'warn',
213-
});
214202
const calls: string[] = [];
215203
await withDeviceAdb(
216204
async (args) => {

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

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -40,31 +40,23 @@ export async function rebindAndroidTestIme(
4040
let cause: Extract<AndroidTestImeRebindOutcome, { kind: 'unconfirmed' }>['cause'] =
4141
'record-write';
4242
try {
43-
if (await writePersistedRebindDisplacement(adb)) {
44-
cause = 'command-failed';
45-
for (const verb of ['disable', 'enable', 'set'] as const) {
46-
const result = await runAdbShell(adb, ['ime', verb, manifest.serviceComponent], {
47-
allowFailure: true,
48-
timeoutMs: 10_000,
49-
});
50-
if (result.exitCode !== 0) return unconfirmed(device.id, cause);
51-
}
52-
cause = 'read-failed';
53-
const activeIme = await readAndroidDefaultInputMethod(adb);
54-
if (activeIme === manifest.serviceComponent) {
55-
// A failed record clear keeps admission on the rebind path, even with the helper selected.
56-
ownership.rebindUnconfirmed = !(await clearPersistedRebindDisplacement(adb));
57-
if (ownership.rebindUnconfirmed) {
58-
emitAndroidAdbDiagnostic({
59-
level: 'warn',
60-
phase: 'android_test_ime_rebind_record_clear_failed',
61-
data: { device: device.id },
62-
});
63-
}
64-
return { kind: 'confirmed' };
65-
}
66-
cause = activeIme ? 'helper-not-selected' : 'read-failed';
43+
if (!(await writePersistedRebindDisplacement(adb))) return unconfirmed(device.id, cause);
44+
cause = 'command-failed';
45+
for (const verb of ['disable', 'enable', 'set'] as const) {
46+
const result = await runAdbShell(adb, ['ime', verb, manifest.serviceComponent], {
47+
allowFailure: true,
48+
timeoutMs: 10_000,
49+
});
50+
if (result.exitCode !== 0) return unconfirmed(device.id, cause);
6751
}
52+
cause = 'read-failed';
53+
const activeIme = await readAndroidDefaultInputMethod(adb);
54+
if (activeIme !== manifest.serviceComponent) {
55+
return unconfirmed(device.id, activeIme ? 'helper-not-selected' : 'read-failed');
56+
}
57+
// Failed cleanup keeps admission on the rebind path even with the helper selected.
58+
ownership.rebindUnconfirmed = !(await clearPersistedRebindDisplacement(adb));
59+
return { kind: 'confirmed' };
6860
} catch (error) {
6961
if (isRequestCanceledError(error)) throw error;
7062
}

‎packages/platform-android/src/ime-restore.test.ts‎

Lines changed: 19 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -43,17 +43,22 @@ beforeEach(() => {
4343
resetAndroidTestImeActivationCacheForTests();
4444
});
4545

46-
test('close-time restore puts the previous IME back and clears record and marker', async () => {
46+
test.each([false, true])('close restores the previous IME with displaced=%s', async (displaced) => {
4747
const host = bindAndroidAdbHostStub();
4848
await host.imeRecoveryMarkers.write(STATE_DIR, DEVICE.id);
4949
setAndroidTestImeActiveForTests(DEVICE, true);
5050
const state = stuckDeviceState();
51+
if (displaced) {
52+
state.settings.set('default_input_method', 'com.android.inputmethod.latin/.LatinIME');
53+
state.settings.set('agent_device_ime_helper_rebind_displaced', '1');
54+
}
5155

5256
const result = await restoreWith(state);
5357

5458
expect(result).toMatchObject({ restored: true, reason: 'ok' });
5559
expect(state.settings.get('default_input_method')).toBe('com.samsung/.Keyboard');
5660
expect(state.settings.has('agent_device_ime_helper_previous_ime')).toBe(false);
61+
expect(state.settings.has('agent_device_ime_helper_rebind_displaced')).toBe(false);
5762
expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([]);
5863
});
5964

@@ -97,26 +102,13 @@ test('a failed restore keeps the record and the marker for a later retry', async
97102
expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([DEVICE.id]);
98103
});
99104

100-
test("close-time restore undoes a rebind's fallback IME, but not the user's own switch", async () => {
101-
const host = bindAndroidAdbHostStub();
102-
await host.imeRecoveryMarkers.write(STATE_DIR, DEVICE.id);
103-
setAndroidTestImeActiveForTests(DEVICE, true);
104-
const displaced = stuckDeviceState();
105-
displaced.settings.set('default_input_method', 'com.android.inputmethod.latin/.LatinIME');
106-
displaced.settings.set('agent_device_ime_helper_rebind_displaced', '1');
107-
108-
expect(await restoreWith(displaced)).toMatchObject({ restored: true, reason: 'ok' });
109-
expect(displaced.settings.get('default_input_method')).toBe('com.samsung/.Keyboard');
110-
expect(displaced.settings.has('agent_device_ime_helper_previous_ime')).toBe(false);
111-
expect(displaced.settings.has('agent_device_ime_helper_rebind_displaced')).toBe(false);
112-
expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([]);
113-
105+
test('close leaves the user-selected keyboard alone', async () => {
106+
bindAndroidAdbHostStub();
114107
setAndroidTestImeActiveForTests(DEVICE, true);
115-
const switched = stuckDeviceState();
116-
switched.settings.set('default_input_method', 'com.android.inputmethod.latin/.LatinIME');
117-
118-
expect(await restoreWith(switched)).toMatchObject({ reason: 'helper-not-active' });
119-
expect(switched.settings.get('default_input_method')).toBe(
108+
const state = stuckDeviceState();
109+
state.settings.set('default_input_method', 'com.android.inputmethod.latin/.LatinIME');
110+
expect(await restoreWith(state)).toMatchObject({ reason: 'helper-not-active' });
111+
expect(state.settings.get('default_input_method')).toBe(
120112
'com.android.inputmethod.latin/.LatinIME',
121113
);
122114
});
@@ -147,10 +139,14 @@ test('startup recovery never scans devices without a pending marker, and retains
147139
expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([DEVICE.id]);
148140
});
149141

150-
test('startup recovery restores a stuck orphan through the scoped transport and clears its marker', async () => {
142+
test.each([false, true])('startup recovers a stuck orphan with displaced=%s', async (displaced) => {
151143
const host = bindAndroidAdbHostStub();
152144
await host.imeRecoveryMarkers.write(STATE_DIR, DEVICE.id);
153145
const state = stuckDeviceState();
146+
if (displaced) {
147+
state.settings.set('default_input_method', 'com.android.inputmethod.latin/.LatinIME');
148+
state.settings.set('agent_device_ime_helper_rebind_displaced', '1');
149+
}
154150

155151
await withAndroidAdbProvider(
156152
{ exec: fakeImeDeviceAdb(state) },
@@ -163,32 +159,11 @@ test('startup recovery restores a stuck orphan through the scoped transport and
163159
);
164160

165161
expect(state.settings.get('default_input_method')).toBe('com.samsung/.Keyboard');
162+
expect(state.settings.has('agent_device_ime_helper_rebind_displaced')).toBe(false);
163+
expect(state.settings.has('agent_device_ime_helper_previous_ime')).toBe(false);
166164
expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([]);
167165
expect(host.diagnostics).toContainEqual({
168166
phase: 'android_test_ime_orphan_restored',
169167
level: 'warn',
170168
});
171169
});
172-
173-
test("startup recovery undoes a crashed daemon's unconfirmed rebind", async () => {
174-
const host = bindAndroidAdbHostStub();
175-
await host.imeRecoveryMarkers.write(STATE_DIR, DEVICE.id);
176-
const state = stuckDeviceState();
177-
state.settings.set('default_input_method', 'com.android.inputmethod.latin/.LatinIME');
178-
state.settings.set('agent_device_ime_helper_rebind_displaced', '1');
179-
180-
await withAndroidAdbProvider(
181-
{ exec: fakeImeDeviceAdb(state) },
182-
{ serial: DEVICE.id },
183-
async () =>
184-
await restoreOrphanedAndroidTestImeOnDaemonStartup({
185-
stateDir: STATE_DIR,
186-
listSerials: async () => [DEVICE.id],
187-
}),
188-
);
189-
190-
expect(state.settings.get('default_input_method')).toBe('com.samsung/.Keyboard');
191-
expect(state.settings.has('agent_device_ime_helper_rebind_displaced')).toBe(false);
192-
expect(state.settings.has('agent_device_ime_helper_previous_ime')).toBe(false);
193-
expect([...(host.markerStore.get(STATE_DIR) ?? [])]).toEqual([]);
194-
});

0 commit comments

Comments
 (0)