Skip to content

Commit 9c13215

Browse files
committed
fix(android): invalidate helper session after APK replacement; recycle viewport windows; align ADR 0002 (PR #1281 re-review)
- prepareAndroidTouchHelper now mirrors the snapshot path: when ensureAndroidSnapshotHelper replaces the APK (install.installed), the persistent session started against the previous binary is stopped before any touch command, so gestures run one-shot against the fresh install instead of a dead/stale session socket. Regression: 'an APK replacement stops the stale session and the gesture runs one-shot' drives a live fake session through an outdated-install probe (new outdatedVersionAdb fixture) and asserts the session socket receives no gesture, the one-shot instrumentation path executes, and the session is gone. - GestureViewportReader.read no longer leaks AccessibilityWindowInfo: a single pass copies the active/focused and first-application bounds into locals, every window is recycled in a finally, and the existing precedence (active/focused app bounds, root-in-active-window, fallback app bounds, IllegalStateException) is applied afterwards, unchanged. - ADR 0002's touch-synthesis paragraph is amended (2026-07, issue #1275) to the shared-helper model, consistent with ADR 0013: a live persistent helper session executes touch commands directly, one-shot otherwise; the old stop-before-gesture requirement is kept as historical context.
1 parent ab1743c commit 9c13215

5 files changed

Lines changed: 107 additions & 15 deletions

File tree

‎android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/GestureViewportReader.java‎

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,30 @@ static Rect read(UiAutomation automation) {
1818
} catch (TimeoutException ignored) {
1919
// Window/root state can still be usable when the app is animating continuously.
2020
}
21+
// UiAutomation.getWindows() transfers recyclable AccessibilityWindowInfo instances, and this
22+
// read runs repeatedly inside the persistent helper session: copy the bounds the precedence
23+
// below needs, then recycle every window before resolving.
24+
Rect activeBounds = null;
25+
Rect fallbackBounds = null;
2126
List<AccessibilityWindowInfo> windows = automation.getWindows();
22-
AccessibilityWindowInfo fallback = null;
23-
for (AccessibilityWindowInfo window : windows) {
24-
if (window.getType() != AccessibilityWindowInfo.TYPE_APPLICATION) continue;
25-
if (window.isActive() || window.isFocused()) {
27+
try {
28+
for (AccessibilityWindowInfo window : windows) {
29+
if (window.getType() != AccessibilityWindowInfo.TYPE_APPLICATION) continue;
2630
Rect bounds = new Rect();
2731
window.getBoundsInScreen(bounds);
28-
if (!bounds.isEmpty()) return bounds;
32+
if (activeBounds == null
33+
&& (window.isActive() || window.isFocused())
34+
&& !bounds.isEmpty()) {
35+
activeBounds = bounds;
36+
}
37+
if (fallbackBounds == null) fallbackBounds = bounds;
38+
}
39+
} finally {
40+
for (AccessibilityWindowInfo window : windows) {
41+
window.recycle();
2942
}
30-
if (fallback == null) fallback = window;
3143
}
44+
if (activeBounds != null) return activeBounds;
3245
AccessibilityNodeInfo activeRoot = automation.getRootInActiveWindow();
3346
if (activeRoot != null) {
3447
try {
@@ -39,11 +52,7 @@ static Rect read(UiAutomation automation) {
3952
activeRoot.recycle();
4053
}
4154
}
42-
if (fallback != null) {
43-
Rect bounds = new Rect();
44-
fallback.getBoundsInScreen(bounds);
45-
if (!bounds.isEmpty()) return bounds;
46-
}
55+
if (fallbackBounds != null && !fallbackBounds.isEmpty()) return fallbackBounds;
4756
throw new IllegalStateException("Active application interaction viewport is unavailable");
4857
}
4958
}

‎docs/adr/0002-persistent-platform-helper-sessions.md‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,14 @@ socket, protocol, and request failures. Both transports execute the same package
5353
agent-device must fail closed when that helper is unavailable or invalid instead of substituting
5454
the legacy `adb uiautomator dump` snapshot engine.
5555

56-
Android permits only one reliable instrumentation-owned `UiAutomation` context per device. Before
57-
starting a different instrumentation helper, such as touch synthesis, the daemon must stop the
58-
persistent snapshot helper session and let the next snapshot restart it lazily. Helper reuse must
59-
never turn process ownership into cross-command interference.
56+
Android permits only one reliable instrumentation-owned `UiAutomation` context per device. Snapshot
57+
capture, gesture viewport resolution, and planned-touch injection therefore share one bundled
58+
automation helper: a live persistent helper session executes touch commands directly over its
59+
session socket, and without one the same helper runs one-shot (amended 2026-07, issue #1275,
60+
consistent with ADR 0013; previously touch synthesis shipped as a separate instrumentation helper,
61+
so the daemon had to stop the persistent snapshot session before every gesture and let the next
62+
snapshot restart it lazily). Helper reuse must never turn process ownership into cross-command
63+
interference.
6064

6165
For iOS, keep the XCTest runner session as the reference implementation for lifecycle and
6266
invalidation behavior. Android does not need to copy iOS internals, but it should reuse the same

‎src/platforms/android/__tests__/touch-helper-session.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
currentVersionAdb,
3131
flingPlan,
3232
makeIsolatedDevice,
33+
outdatedVersionAdb,
3334
} from './touch-helper.fixtures.ts';
3435

3536
vi.mock('../helper-package-install.ts', async (importOriginal) => {
@@ -204,6 +205,59 @@ test('gesture uses the persistent snapshot-helper session and does not stop it',
204205
assert.equal(await session.isSessionAlive(), true);
205206
});
206207

208+
test('an APK replacement stops the stale session and the gesture runs one-shot', async () => {
209+
const device = makeIsolatedDevice();
210+
let sessionGestureCallCount = 0;
211+
const session = await startFakeTouchHelperSession(device, (command, requestId) => {
212+
if (command.startsWith('gesture')) {
213+
sessionGestureCallCount += 1;
214+
return sessionHeaderResponse({
215+
agentDeviceProtocol: 'android-snapshot-helper-v1',
216+
requestId,
217+
ok: 'true',
218+
kind: 'swipe',
219+
injectedEvents: '6',
220+
elapsedMs: '9',
221+
});
222+
}
223+
return sessionHeaderResponse({
224+
agentDeviceProtocol: 'android-snapshot-helper-v1',
225+
requestId,
226+
ok: 'true',
227+
});
228+
});
229+
230+
let oneShotArgs: string[] | undefined;
231+
const result = await withAndroidAdbProvider(
232+
{
233+
// The install probe reports an outdated helper, so prepareAndroidTouchHelper replaces the
234+
// APK. That replacement kills the instrumentation the live session socket belongs to; the
235+
// gesture must not be sent there and must run one-shot against the fresh binary instead.
236+
exec: outdatedVersionAdb(async (args) => {
237+
assert.ok(args.includes('instrument'), `unexpected adb call: ${args.join(' ')}`);
238+
oneShotArgs = args;
239+
return {
240+
exitCode: 0,
241+
stdout: [
242+
resultRecord({ ok: 'true', kind: 'swipe', injectedEvents: '4', elapsedMs: '12' }),
243+
'INSTRUMENTATION_CODE: 0',
244+
].join('\n'),
245+
stderr: '',
246+
};
247+
}),
248+
},
249+
{ serial: device.id },
250+
async () => await executeAndroidTouchHelperPlan(device, flingPlan()),
251+
);
252+
253+
assert.equal(result.installReason, 'outdated');
254+
assert.equal(result.helperTransport, 'instrumentation');
255+
assert.equal(result.helperKind, 'swipe');
256+
assert.ok(oneShotArgs?.includes('gesture'));
257+
assert.equal(sessionGestureCallCount, 0);
258+
assert.equal(await session.isSessionAlive(), false);
259+
});
260+
207261
test('a structured ok=false session gesture response throws but leaves the session alive', async () => {
208262
const device = makeIsolatedDevice();
209263
const session = await startFakeTouchHelperSession(device, (command, requestId) => {

‎src/platforms/android/__tests__/touch-helper.fixtures.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export const ANDROID_TOUCH_HELPER_MANIFEST = {
1616
versionCode: 17000,
1717
instrumentationRunner: 'com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation',
1818
statusProtocol: 'android-snapshot-helper-v1' as const,
19+
installArgs: ['install', '-r', '-t'],
1920
};
2021

2122
export function androidTouchHelperResultRecord(values: Record<string, string>): string {
@@ -78,3 +79,22 @@ export function currentVersionAdb(handleInstrument: AndroidAdbExecutor): Android
7879
return handleInstrument(args, options);
7980
};
8081
}
82+
83+
// Wraps an executor that answers the install-decision probe as "outdated" (an older installed
84+
// versionCode) and accepts the resulting `adb install`, so ensureAndroidSnapshotHelper actually
85+
// replaces the APK (install.installed === true) before the wrapped call runs.
86+
export function outdatedVersionAdb(handleInstrument: AndroidAdbExecutor): AndroidAdbExecutor {
87+
return async (args, options) => {
88+
if (args.includes('--show-versioncode')) {
89+
return {
90+
exitCode: 0,
91+
stdout: `package:${ANDROID_TOUCH_HELPER_MANIFEST.packageName} versionCode:1`,
92+
stderr: '',
93+
};
94+
}
95+
if (args[0] === 'install') {
96+
return { exitCode: 0, stdout: 'Success', stderr: '' };
97+
}
98+
return handleInstrument(args, options);
99+
};
100+
}

‎src/platforms/android/touch-helper.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,11 @@ async function prepareAndroidTouchHelper(device: DeviceInfo): Promise<PreparedAn
155155
phase: 'android_touch_helper_install_decision',
156156
data: install,
157157
});
158+
if (install.installed) {
159+
// An APK replacement kills the running instrumentation, so a persistent session started
160+
// against the previous binary must not serve this command; the next snapshot restarts it.
161+
await stopAndroidSnapshotHelperSession(deviceKey);
162+
}
158163
return { adb: adbProvider.exec, artifact, install, deviceKey };
159164
}
160165

0 commit comments

Comments
 (0)