Skip to content

Commit 19d113b

Browse files
thymikeeclaude
andcommitted
fix(android): take the intent owner from the launch report
am start -W names the activity the launch resumed. That component, not a later foreground read, is the owner, so a permission prompt over the launched app is never recorded. The foreground read remains only for a launch that names no activity. Deep-link and app-bound launches honor relaunch termination like intent and package launches. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 7c5c79f commit 19d113b

12 files changed

Lines changed: 164 additions & 48 deletions

‎packages/contracts/src/application-lifecycle-interaction.ts‎

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import {
66
import type { DeviceInfo } from '@agent-device/kernel/device';
77
import { isIosFamily } from '@agent-device/kernel/device';
88
import { AppError } from '@agent-device/kernel/errors';
9-
import type { Interactor, RunnerContext } from './interactor-types.ts';
9+
import type { ApplicationLaunchReport, Interactor, RunnerContext } from './interactor-types.ts';
1010
import type {
1111
ApplicationLifecycleExecution,
1212
ApplicationLifecycleProviderInteractorResolver,
@@ -142,7 +142,7 @@ export async function invokeApplicationOpen(
142142
execution: ApplicationLifecycleExecution;
143143
terminateRunningApp?: boolean;
144144
}>,
145-
): Promise<void> {
145+
): Promise<ApplicationLaunchReport | void> {
146146
const { device, positionals, execution } = params;
147147
assertOpenPositionals(positionals);
148148
const app = positionals[0];
@@ -152,11 +152,8 @@ export async function invokeApplicationOpen(
152152
return;
153153
}
154154
assertOpenDeviceSupport(device, execution);
155-
if (url !== undefined) {
156-
await invokeApplicationUrlOpen(params, app, url);
157-
return;
158-
}
159-
await invokeApplicationTargetOpen(params, app);
155+
if (url !== undefined) return await invokeApplicationUrlOpen(params, app, url);
156+
return await invokeApplicationTargetOpen(params, app);
160157
}
161158

162159
type DirectOpenParameters = Readonly<{
@@ -200,7 +197,7 @@ async function invokeApplicationUrlOpen(
200197
params: DirectOpenParameters,
201198
app: string,
202199
url: string,
203-
): Promise<void> {
200+
): Promise<ApplicationLaunchReport | void> {
204201
if (isDeepLinkTarget(app)) {
205202
throw new AppError(
206203
'INVALID_ARGS',
@@ -213,7 +210,7 @@ async function invokeApplicationUrlOpen(
213210
if (params.execution.launchConsole) {
214211
throw new AppError('INVALID_ARGS', LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE);
215212
}
216-
await params.interactor.open(app, {
213+
return await params.interactor.open(app, {
217214
activity: params.execution.activity,
218215
appBundleId: params.appBundleId,
219216
launchArgs: params.execution.launchArgs ? [...params.execution.launchArgs] : undefined,
@@ -225,7 +222,7 @@ async function invokeApplicationUrlOpen(
225222
async function invokeApplicationTargetOpen(
226223
params: DirectOpenParameters,
227224
app: string,
228-
): Promise<void> {
225+
): Promise<ApplicationLaunchReport | void> {
229226
const { execution, interactor } = params;
230227
if (execution.launchConsole && isDeepLinkTarget(app)) {
231228
throw new AppError('INVALID_ARGS', LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE);
@@ -239,7 +236,7 @@ async function invokeApplicationTargetOpen(
239236
}
240237
await interactor.setSetting('clear-app-state', 'clear', app);
241238
}
242-
await interactor.open(app, {
239+
return await interactor.open(app, {
243240
activity: execution.activity,
244241
appBundleId: params.appBundleId,
245242
launchConsole: execution.launchConsole,

‎packages/contracts/src/application-lifecycle-runtime.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,7 @@ export type AndroidApplicationTools = Readonly<{
391391
device: DeviceInfo,
392392
target: string | undefined,
393393
currentAppBundleId: string | undefined,
394+
launchedAppBundleId: string | undefined,
394395
): Promise<string | undefined>;
395396
resetFramePerfStats(device: DeviceInfo, appBundleId: string): Promise<void>;
396397
applyRuntimeHints(device: DeviceInfo, input: RuntimeHintsApplicationInput): Promise<void>;

‎packages/contracts/src/interactor-types.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,9 @@ export type SnapshotRuntimeAcquiredResult = Readonly<{
285285

286286
export type SnapshotRuntimeResult = SnapshotResult | SnapshotRuntimeAcquiredResult;
287287

288+
/** The application an owner's launch reports it started, when the launch names one. */
289+
export type ApplicationLaunchReport = Readonly<{ launchedAppBundleId?: string }>;
290+
288291
export type Interactor = {
289292
open(
290293
app: string,
@@ -296,7 +299,7 @@ export type Interactor = {
296299
terminateRunningApp?: boolean;
297300
url?: string;
298301
},
299-
): Promise<void>;
302+
): Promise<ApplicationLaunchReport | void>;
300303
openDevice(): Promise<void>;
301304
close(app: string): Promise<void>;
302305
tap(x: number, y: number): Promise<Record<string, unknown> | void>;

‎packages/platform-android/src/__tests__/app-lifecycle-open.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,37 @@ test('openAndroidApp has am force-stop the resolved intent handler when terminat
529529
});
530530
});
531531

532+
test('openAndroidApp returns the package am start reports it launched', async () => {
533+
const launched = (args: readonly string[]): FakeAdbResponse | undefined =>
534+
args[2] === 'start'
535+
? 'Starting: Intent { act=android.settings.SETTINGS }\nStatus: ok\nLaunchState: COLD\nActivity: com.android.settings/.homepage.SettingsHomepageActivity\nTotalTime: 412'
536+
: undefined;
537+
await withFakeAdb(launched, async ({ device }) => {
538+
assert.equal(await openAndroidApp(device, 'settings'), 'com.android.settings');
539+
});
540+
await withFakeAdb(androidOpenFakeAdb, async ({ device }) => {
541+
assert.equal(await openAndroidApp(device, 'settings'), undefined);
542+
});
543+
});
544+
545+
test('openAndroidApp has am force-stop a deep link handler when terminating a running app', async () => {
546+
await withFakeAdb(androidOpenFakeAdb, async ({ calls, device }) => {
547+
await openAndroidApp(device, 'myapp://item/42', { terminateRunningApp: true });
548+
assert.deepEqual(calls.at(-1)?.slice(0, 5), ['shell', 'am', 'start', '-W', '-S']);
549+
});
550+
});
551+
552+
test('openAndroidApp stops the bound package before an app-bound deep link when terminating', async () => {
553+
await withFakeAdb(androidOpenFakeAdb, async ({ calls, device }) => {
554+
await openAndroidApp(device, 'com.example.app', {
555+
url: 'example://bottom-tabs',
556+
terminateRunningApp: true,
557+
});
558+
assert.deepEqual(calls[0], ['shell', 'am', 'force-stop', 'com.example.app']);
559+
assert.deepEqual(calls.at(-1)?.slice(0, 4), ['shell', 'am', 'start', '-W']);
560+
});
561+
});
562+
532563
test('openAndroidApp stops a resolved package before launching it when terminating a running app', async () => {
533564
await withFakeAdb(androidOpenFakeAdb, async ({ calls, device }) => {
534565
await openAndroidApp(device, 'com.example.app', { terminateRunningApp: true });

‎packages/platform-android/src/app-lifecycle.ts‎

Lines changed: 44 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { isDeepLinkTarget } from '@agent-device/contracts/command';
77

88
import { waitForAndroidBoot } from './emulator-lifecycle.ts';
99
import { runAndroidShell } from './adb.ts';
10+
import type { AndroidAdbExecutorResult } from './adb-transport.ts';
1011
import {
1112
androidAdbResultError,
1213
createAndroidPortReverseManager,
@@ -194,11 +195,20 @@ function androidLaunchArgs(options: OpenAndroidAppOptions): string[] {
194195
return options.launchArgs ?? [];
195196
}
196197

198+
/** Opens the target and returns the package `am start -W` reports it launched, when reported. */
197199
export async function openAndroidApp(
198200
device: DeviceInfo,
199201
app: string,
200202
optionsOrActivity?: OpenAndroidAppOptions | string,
201-
): Promise<void> {
203+
): Promise<string | undefined> {
204+
return launchedAndroidPackage(await startAndroidApp(device, app, optionsOrActivity));
205+
}
206+
207+
async function startAndroidApp(
208+
device: DeviceInfo,
209+
app: string,
210+
optionsOrActivity?: OpenAndroidAppOptions | string,
211+
): Promise<AndroidAdbExecutorResult> {
202212
const options = normalizeOpenAndroidAppOptions(optionsOrActivity);
203213
const activity = options.activity;
204214
if (activity !== undefined) requireAndroidActivityComponent(activity);
@@ -207,43 +217,52 @@ export async function openAndroidApp(
207217
}
208218
const deepLinkTarget = app.trim();
209219
if (isDeepLinkTarget(deepLinkTarget)) {
210-
await openAndroidDeepLink(device, deepLinkTarget, options);
211-
return;
220+
return await openAndroidDeepLink(device, deepLinkTarget, options);
212221
}
213222
if (options.url !== undefined) {
214-
await openAndroidAppBoundDeepLink(device, app, options);
215-
return;
223+
return await openAndroidAppBoundDeepLink(device, app, options);
216224
}
217225
const resolved = await resolveAndroidApp(device, app);
218226
const launchCategory = resolveAndroidLauncherCategory(device);
219227
if (resolved.type === 'intent') {
220-
await openAndroidIntent(device, resolved.value, options);
221-
return;
228+
return await openAndroidIntent(device, resolved.value, options);
222229
}
223230
if (options.terminateRunningApp) await stopAndroidPackage(device, resolved.value);
224231
if (activity) {
225-
await openAndroidPackageActivity(device, resolved.value, activity, launchCategory, options);
226-
return;
232+
return await openAndroidPackageActivity(
233+
device,
234+
resolved.value,
235+
activity,
236+
launchCategory,
237+
options,
238+
);
227239
}
228-
await openAndroidPackage(device, resolved.value, launchCategory, options);
240+
return await openAndroidPackage(device, resolved.value, launchCategory, options);
241+
}
242+
243+
/** `am start -W` names the activity this launch resumed on its `Activity: <package>/<class>` line. */
244+
function launchedAndroidPackage(result: AndroidAdbExecutorResult): string | undefined {
245+
const line = result.stdout.split('\n').find((entry) => entry.trim().startsWith('Activity:'));
246+
return line?.split(':')[1]?.trim().split('/')[0] || undefined;
229247
}
230248

231249
async function openAndroidDeepLink(
232250
device: DeviceInfo,
233251
target: string,
234252
options: OpenAndroidAppOptions,
235-
): Promise<void> {
253+
): Promise<AndroidAdbExecutorResult> {
236254
if (options.activity) {
237255
throw new AppError(
238256
'INVALID_ARGS',
239257
'Activity override is not supported when opening a deep link URL',
240258
);
241259
}
242260
await ensureAndroidLocalhostReverse(device, target);
243-
await runAndroidShell(device, [
261+
return await runAndroidShell(device, [
244262
'am',
245263
'start',
246264
'-W',
265+
...(options.terminateRunningApp ? ['-S'] : []),
247266
'-a',
248267
'android.intent.action.VIEW',
249268
'-d',
@@ -257,7 +276,7 @@ async function openAndroidAppBoundDeepLink(
257276
device: DeviceInfo,
258277
app: string,
259278
options: OpenAndroidAppOptions,
260-
): Promise<void> {
279+
): Promise<AndroidAdbExecutorResult> {
261280
if (options.activity) {
262281
throw new AppError(
263282
'INVALID_ARGS',
@@ -270,7 +289,8 @@ async function openAndroidAppBoundDeepLink(
270289
}
271290
await ensureAndroidLocalhostReverse(device, deepLinkUrl);
272291
const resolved = await requireAndroidPackageForOpen(device, app, 'app-bound open');
273-
await runAndroidShell(device, [
292+
if (options.terminateRunningApp) await stopAndroidPackage(device, resolved);
293+
return await runAndroidShell(device, [
274294
'am',
275295
'start',
276296
'-W',
@@ -288,11 +308,11 @@ async function openAndroidIntent(
288308
device: DeviceInfo,
289309
intent: string,
290310
options: OpenAndroidAppOptions,
291-
): Promise<void> {
311+
): Promise<AndroidAdbExecutorResult> {
292312
if (options.activity) {
293313
throw new AppError('INVALID_ARGS', 'Activity override requires a package name, not an intent');
294314
}
295-
await runAndroidShell(device, [
315+
return await runAndroidShell(device, [
296316
'am',
297317
'start',
298318
'-W',
@@ -309,10 +329,10 @@ async function openAndroidPackageActivity(
309329
activity: string,
310330
launchCategory: string,
311331
options: OpenAndroidAppOptions,
312-
): Promise<void> {
332+
): Promise<AndroidAdbExecutorResult> {
313333
const component = androidActivityComponent(packageName, activity);
314334
try {
315-
await runAndroidShell(
335+
return await runAndroidShell(
316336
device,
317337
buildAndroidActivityLaunchArgs(component, launchCategory, options),
318338
);
@@ -327,7 +347,7 @@ async function openAndroidPackage(
327347
packageName: string,
328348
launchCategory: string,
329349
options: OpenAndroidAppOptions,
330-
): Promise<void> {
350+
): Promise<AndroidAdbExecutorResult> {
331351
const primaryResult = await runAndroidShell(
332352
device,
333353
[
@@ -347,7 +367,7 @@ async function openAndroidPackage(
347367
{ allowFailure: true },
348368
);
349369
if (primaryResult.exitCode === 0 && !isAmStartError(primaryResult.stdout, primaryResult.stderr)) {
350-
return;
370+
return primaryResult;
351371
}
352372
const component = await resolveAndroidLaunchComponent(device, packageName);
353373
if (!component) {
@@ -356,7 +376,10 @@ async function openAndroidPackage(
356376
}
357377
throw androidAdbResultError(`Failed to launch ${packageName}`, primaryResult);
358378
}
359-
await runAndroidShell(device, buildAndroidActivityLaunchArgs(component, launchCategory, options));
379+
return await runAndroidShell(
380+
device,
381+
buildAndroidActivityLaunchArgs(component, launchCategory, options),
382+
);
360383
}
361384

362385
function buildAndroidActivityLaunchArgs(

‎packages/platform-android/src/lifecycle.test.ts‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,15 @@ afterEach(() => {
2626
type LifecycleFixture = Readonly<{
2727
calls: string[];
2828
framePerfResets: string[];
29+
launchReports: Array<string | undefined>;
2930
lifecycle: ReturnType<typeof bindAndroidApplicationLifecycle>;
3031
}>;
3132

3233
function createLifecycle(
3334
params: Readonly<{
3435
snapshot?: (options: SnapshotOptions) => Promise<unknown>;
3536
openedAppBundleId?: string;
37+
launchedAppBundleId?: string;
3638
signal?: AbortSignal;
3739
restoreTestIme?: (
3840
device: DeviceInfo,
@@ -43,11 +45,13 @@ function createLifecycle(
4345
): LifecycleFixture {
4446
const calls: string[] = [];
4547
const framePerfResets: string[] = [];
48+
const launchReports: Array<string | undefined> = [];
4649
const localInteractors: LocalApplicationInteractorHost = {
4750
resolve: async () =>
4851
({
4952
open: async (app: string, options?: { terminateRunningApp?: boolean }) => {
5053
calls.push(`open:${app}${options?.terminateRunningApp ? ' (terminate running)' : ''}`);
54+
return { launchedAppBundleId: params.launchedAppBundleId };
5155
},
5256
openDevice: async () => {},
5357
close: async (app: string) => {
@@ -72,8 +76,15 @@ function createLifecycle(
7276
},
7377
androidApplications: {
7478
resolveOpenTarget: async () => ({}),
75-
inferOpenedAppBundleId: async () =>
76-
'openedAppBundleId' in params ? params.openedAppBundleId : 'com.example.app',
79+
inferOpenedAppBundleId: async (
80+
_device: DeviceInfo,
81+
_target: string | undefined,
82+
_current: string | undefined,
83+
launchedAppBundleId: string | undefined,
84+
) => {
85+
launchReports.push(launchedAppBundleId);
86+
return 'openedAppBundleId' in params ? params.openedAppBundleId : 'com.example.app';
87+
},
7788
resetFramePerfStats: async (_device: DeviceInfo, appBundleId: string) => {
7889
framePerfResets.push(appBundleId);
7990
},
@@ -99,7 +110,7 @@ function createLifecycle(
99110
device,
100111
signal: params.signal ?? new AbortController().signal,
101112
});
102-
return { calls, framePerfResets, lifecycle };
113+
return { calls, framePerfResets, launchReports, lifecycle };
103114
}
104115

105116
function openInput(overrides: Partial<OpenApplicationInput> = {}): OpenApplicationInput {
@@ -274,6 +285,23 @@ test('an Android intent relaunch has the launch terminate its handler and record
274285
expect(outcome.appBundleId).toBe('com.android.settings');
275286
});
276287

288+
test('the owner inference receives the package the primary launch reported', async () => {
289+
const { launchReports, lifecycle } = createLifecycle({
290+
launchedAppBundleId: 'com.android.settings',
291+
});
292+
293+
await lifecycle.openApplication(
294+
openInput({
295+
target: 'settings',
296+
positionals: ['settings'],
297+
appBundleId: undefined,
298+
runtimeLaunchUrl: 'example://after-open',
299+
}),
300+
);
301+
302+
expect(launchReports).toEqual(['com.android.settings']);
303+
});
304+
277305
test('an Android intent relaunch that resumes no app closes nothing and stays unidentified', async () => {
278306
const { calls, lifecycle } = createLifecycle({ openedAppBundleId: undefined });
279307

0 commit comments

Comments
 (0)