Skip to content

Commit 182156a

Browse files
thymikeeclaude
andcommitted
refactor(mobile): set permissions on the app by name, without an open first
agent-device 0.21.21 takes an explicit app on settings permission (callstack/agent-device#3179), so a permission needs no open to put the session on the app. Drops the session-app bookkeeping, the sessions list at worker start, the refusal-text retry, and the binding's sessionApp. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 449fa93 commit 182156a

9 files changed

Lines changed: 78 additions & 233 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@e2e-dev/mobile": patch
3+
---
4+
5+
Permissions are set on the app by name, with agent-device's `settings permission --app` (0.21.21). `device.setPermission()` and the permissions a launch presets no longer open the app first to put agent-device's session on it, so a permission goes in before the app's first launch with no foreground open. `device.setPermission()` always acts on the pinned app, as documented, not on whichever app the session last opened. The warm-up in `prepare` still opens the pinned app, and a worker no longer lists agent-device's sessions at start.

‎docs/reference/mobile.mdx‎

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -161,16 +161,10 @@ process (`ProcessInfo.processInfo.arguments`); Android appends them to
161161
`am start`, so `['--ez', 'e2e', 'true']` is a boolean intent extra. `deny` is
162162
a recorded refusal on iOS, where the app is told no without a prompt, and a
163163
revocation on Android, where the OS asks again when the app requests the
164-
permission. The permissions are set before the app starts,
165-
since iOS terminates a running app whose permission changed and Android one
166-
whose permission was revoked. agent-device sets them on the app its session
167-
is on, and only an open puts a session on an app: the warm-up's open in
168-
`prepare` does that under the session the worker resumes, so a worker's
169-
launches set them straight away. A run without `prepare`, the first launch
170-
after `device.closeApp`, and an app the session has not opened get one
171-
foreground open first; that open is the one process start no permission can
172-
precede, and the relaunch after it has them. The warm-up passes no launch
173-
argument and touches no permission.
164+
permission. The permissions are set on the app by name before it starts,
165+
with no open first, since iOS terminates a running app whose permission
166+
changed and Android one whose permission was revoked. The warm-up passes no
167+
launch argument and touches no permission.
174168
`device.openApp(app, { relaunch: true, launchArguments, permissions })` does
175169
the same for one launch of any app. A permission name outside
176170
`DevicePermission` (naming the nearest one when it is a likely typo) or a
@@ -238,10 +232,9 @@ export interface Device {
238232
/** Toggles airplane mode. */
239233
setAirplaneMode(enabled: boolean): Promise<void>;
240234
/**
241-
* Grants, denies, or resets one permission for the pinned app, brought to
242-
* the foreground first when the session is on no app. A change terminates
243-
* a running app on iOS, a revoke one on Android, so it goes before the
244-
* `app.open()` a test starts with.
235+
* Grants, denies, or resets one permission for the pinned app, which need
236+
* not be running. A change terminates a running app on iOS, a revoke one
237+
* on Android, so it goes before the `app.open()` a test starts with.
245238
*/
246239
setPermission(permission: DevicePermission, state: PermissionState): Promise<void>;
247240
/** Sets the simulated location, switching location services on first on Android. */

‎packages/mobile/src/bindings.ts‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,6 @@ export interface SlotBinding {
5151
* lease: with it the worker hands the lease to the provider's `record`.
5252
*/
5353
readonly leaseId?: string | undefined;
54-
/**
55-
* App the warm-up in `prepare` opened in the slot's session, which the
56-
* worker resumes: a permission command there already acts on it. Absent
57-
* when nothing was opened, or the open failed. Every worker of the slot
58-
* reads it, but only a worker that finds the session still open keeps it:
59-
* one retired after a failing test closed it.
60-
*/
61-
readonly sessionApp?: string | undefined;
6254
}
6355

6456
/**
@@ -119,7 +111,6 @@ export function encodeBindings(bindings: readonly SlotBinding[]): string {
119111
client: binding.client,
120112
installedApp: binding.installedApp,
121113
leaseId: binding.leaseId,
122-
sessionApp: binding.sessionApp,
123114
}),
124115
),
125116
);
@@ -153,13 +144,12 @@ function isOptionalString(value: unknown): value is string | undefined {
153144
/** A binding as JSON parses it back, or as a provider returned it: nothing the engine did not write is trusted. */
154145
export function isSlotBinding(value: unknown): value is SlotBinding {
155146
if (typeof value !== 'object' || value === null) return false;
156-
const { device, deviceId, daemon, client, installedApp, leaseId, sessionApp } = value as Record<keyof SlotBinding, unknown>;
147+
const { device, deviceId, daemon, client, installedApp, leaseId } = value as Record<keyof SlotBinding, unknown>;
157148
return (
158149
isOptionalString(device) &&
159150
isOptionalString(deviceId) &&
160151
isOptionalString(installedApp) &&
161152
isOptionalString(leaseId) &&
162-
isOptionalString(sessionApp) &&
163153
(daemon === undefined || isDaemon(daemon)) &&
164154
(client === undefined || isClientConfig(client))
165155
);

‎packages/mobile/src/device.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,9 @@ export interface Device {
3333
/** Toggles airplane mode. */
3434
setAirplaneMode(enabled: boolean): Promise<void>;
3535
/**
36-
* Grants, denies, or resets one permission for the pinned app, brought to
37-
* the foreground first when the session is on no app. A change terminates
38-
* a running app on iOS, a revoke one on Android, so it goes before the
39-
* `app.open()` a test starts with.
36+
* Grants, denies, or resets one permission for the pinned app, which need
37+
* not be running. A change terminates a running app on iOS, a revoke one
38+
* on Android, so it goes before the `app.open()` a test starts with.
4039
*/
4140
setPermission(permission: DevicePermission, state: PermissionState): Promise<void>;
4241
/** Sets the simulated location, switching location services on first on Android. */

‎packages/mobile/src/errors.ts‎

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -207,17 +207,6 @@ export function isRunnerFailure(error: unknown): boolean {
207207
return error instanceof Error && runnerState(error.cause) !== undefined;
208208
}
209209

210-
const NO_SESSION_APP_PATTERN = /requires an active app in (?:the )?session/i;
211-
212-
/**
213-
* True for a translated settings command agent-device refused because its
214-
* session is on no app: the one refusal a foreground open of the pinned app
215-
* answers.
216-
*/
217-
export function isNoSessionApp(error: unknown): boolean {
218-
return error instanceof Error && NO_SESSION_APP_PATTERN.test(normalizeAgentDeviceError(error.cause).message);
219-
}
220-
221210
/**
222211
* True for a translated snapshot the iOS runner acquired but could not
223212
* present. The check is per capture and the capture is a read, so one retry

‎packages/mobile/src/pool.ts‎

Lines changed: 10 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -193,14 +193,14 @@ export class DevicePool {
193193
/**
194194
* Binds a device to every worker slot the run will use and warms each,
195195
* once per run and outside every launch budget, so `init` finds a booted
196-
* device. The bindings, each naming the app its session is on, are
197-
* reported back as the target's worker cap and left in the environment
198-
* for the workers. A target nothing runs on binds
196+
* device. The bindings are reported back as the target's worker cap and
197+
* left in the environment for the workers. A target nothing runs on binds
199198
* nothing: a hosted session is billed from the moment it starts.
200199
*/
201200
async prepare(info: EnginePrepareInfo): Promise<EnginePrepareResult> {
202201
if (info.slots === 0) return {};
203-
const bindings = await this.warm(await this.source.bind(info), info);
202+
const bindings = await this.source.bind(info);
203+
await this.warm(bindings, info);
204204
this.bound.set(info.targetName, bindings);
205205
return { workers: bindings.length, env: { [bindingsVariable(info.targetName)]: encodeBindings(bindings) } };
206206
}
@@ -227,9 +227,8 @@ export class DevicePool {
227227

228228
/**
229229
* Boots every bound device, starts the iOS automation runner on it, and
230-
* opens the pinned app on it once, so the slot's session is on the app,
231-
* which the returned binding records for the worker: a permission it
232-
* presets there needs no open first. A plain foreground open, with none of the engine's
230+
* opens the pinned app on it once, so a test that starts without
231+
* `app.open()` finds it on screen. A plain foreground open, with none of the engine's
233232
* launch options: an app still running from an earlier run keeps its
234233
* process either way, and a test's `app.open()` relaunches it with them.
235234
* One slot after another, on purpose: workers
@@ -242,13 +241,11 @@ export class DevicePool {
242241
* its first observation with the app blamed, and the message names the
243242
* recovery, which a wait of up to the runner's recycle window would only
244243
* hide. A runner that did not start leaves the slot unopened: the open
245-
* would start it again under a shorter budget, and its timeout resets the
246-
* daemon every earlier slot is on. A build `appPath` installs in `init` is
244+
* would start it again under a shorter budget. A build `appPath` installs in `init` is
247245
* not on the device yet, so that slot boots and starts the runner only,
248246
* unless a lease says the build is already there.
249247
*/
250-
private async warm(bindings: readonly SlotBinding[], info: EnginePrepareInfo): Promise<readonly SlotBinding[]> {
251-
const warmed: SlotBinding[] = [];
248+
private async warm(bindings: readonly SlotBinding[], info: EnginePrepareInfo): Promise<void> {
252249
for (const [slot, binding] of bindings.entries()) {
253250
const label = deviceLabel(binding) ?? `a booted ${this.options.platform} device`;
254251
const where = deviceSelection(this.options.platform, binding);
@@ -260,27 +257,20 @@ export class DevicePool {
260257
await runCommand('boot', () => client.devices.boot(where), info.signal, at);
261258
const runnerUp = this.options.platform !== 'ios' || (await prepareRunner(client, where, info, at));
262259
const app = pinnedApp(info.app, binding.installedApp);
263-
if (app === undefined || !runnerUp) {
264-
warmed.push(binding);
265-
continue;
266-
}
260+
if (app === undefined || !runnerUp) continue;
267261
// A build the suite installs itself is not on the device yet, so there
268262
// is nothing to open: the first attempt installs it.
269263
if (info.app.appPath !== undefined && binding.installedApp === undefined) {
270264
info.log(`${label}: ${app} awaits the suite's device.installApp()`);
271-
warmed.push(binding);
272265
continue;
273266
}
274267
try {
275268
await runCommand(`open ${app}`, () => client.apps.open({ app, ...where }), info.signal, at);
276-
warmed.push({ ...binding, sessionApp: app });
277269
} catch (cause) {
278270
if (info.signal.aborted || isRunnerFailure(cause)) throw cause;
279271
info.log(`${label}: ${app} did not open (${message(cause)}); the first attempt opens it`);
280-
warmed.push(binding);
281272
}
282273
}
283-
return warmed;
284274
}
285275

286276
/** Holds a warm-up client for `finish`, before its first command: a boot that fails still opened the session. */
@@ -295,8 +285,7 @@ export class DevicePool {
295285
* Starts the slot's iOS automation runner under `prepare ios-runner`, whose
296286
* startup budget covers a cold simulator. Left to the first `open`, the
297287
* start runs inside that request's 90 s envelope, which a cold runner on a
298-
* loaded CI Mac outlasts; a timed-out `open` resets the daemon, ending every
299-
* other slot's session with it. A runner that is busy or wedged ends the run
288+
* loaded CI Mac outlasts. A runner that is busy or wedged ends the run
300289
* here, like a warm-up open that meets one; any other failure is logged and
301290
* left to the first attempt. True when the runner is up.
302291
*/

‎packages/mobile/src/surface.ts‎

Lines changed: 11 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ import {
4444
ConfigurationError,
4545
TestError,
4646
} from 'e2e/engine';
47-
import { isNoSessionApp, isSnapshotPresentationFailure, runCommand, staleOr } from './errors.ts';
47+
import { isSnapshotPresentationFailure, runCommand, staleOr } from './errors.ts';
4848
import { pointerInteraction, DEFAULT_LONG_PRESS_MS } from './actions.ts';
4949
import { resolveExpression } from './locate.ts';
5050
import {
@@ -360,14 +360,6 @@ export class AgentDeviceSurface {
360360
private readonly located = new Map<string, NodeBinding>();
361361
private idCounter = 0;
362362
private appIdentity: string | undefined;
363-
/**
364-
* The app this worker's agent-device session is on, and so the app a
365-
* permission command there acts on: what the warm-up in `prepare` opened
366-
* under the session this worker resumed, while that session is still open,
367-
* then whatever this surface last opened. Undefined while nothing has been opened in the session, and once
368-
* `closeApp` ended it.
369-
*/
370-
private sessionApp: string | undefined;
371363
/** The app the build `appPath` installed, once `init` has, itself or through a lease. */
372364
private installedApp: string | undefined;
373365
/** The target's app, as `init` received it. */
@@ -509,31 +501,12 @@ export class AgentDeviceSurface {
509501
? undefined
510502
: { provider, lease, runId: info.runId, targetName: info.targetName, env: info.env };
511503
await this.command('boot', (client) => client.devices.boot(this.selection()), info.signal);
512-
this.sessionApp = binding?.sessionApp === undefined ? undefined : await this.resumedSessionApp(session, binding.sessionApp, info.signal);
513504
// Nothing is installed here: a device provider that installed the build
514505
// from `appPath` says so on the binding, and otherwise the suite installs
515506
// it where it wants to, with `device.installApp()`.
516507
this.installedApp = binding?.installedApp;
517508
}
518509

519-
/**
520-
* The app the warm-up left the slot's session on, while agent-device still
521-
* holds that session. Only the slot's first worker finds it: a worker
522-
* retired after a failing test closed it in `dispose`, and a permission
523-
* command on a closed session reaches no device. A session not listed, or
524-
* a list that fails, leaves the app unknown, and the first permission
525-
* change opens it again.
526-
*/
527-
private async resumedSessionApp(session: string, app: string, signal: AbortSignal): Promise<string | undefined> {
528-
const sessions: unknown = await this.command('sessions', (client) => client.sessions.list(), signal).catch((cause: unknown) => {
529-
if (signal.aborted) throw cause;
530-
return undefined;
531-
});
532-
if (!Array.isArray(sessions)) return undefined;
533-
const open = sessions.some((entry: { name?: unknown; address?: unknown }) => (entry.address ?? entry.name) === session);
534-
return open ? app : undefined;
535-
}
536-
537510
async startAttempt(context: EngineAttemptContext): Promise<void> {
538511
if (this.attempt !== undefined) {
539512
throw invalidState('an attempt is already running on this agent-device engine');
@@ -644,7 +617,6 @@ export class AgentDeviceSurface {
644617
private async stopScreenRecording(signal: AbortSignal): Promise<{ readonly outPath?: unknown }> {
645618
const result = await this.command('stop video recording', (client) => client.recording.record({ action: 'stop' }), signal);
646619
if (result.recordOnlySession === true) {
647-
this.sessionApp = undefined;
648620
this.screenReplaced();
649621
}
650622
return result;
@@ -685,7 +657,6 @@ export class AgentDeviceSurface {
685657
this.generation = new Map();
686658
this.located.clear();
687659
this.appIdentity = undefined;
688-
this.sessionApp = undefined;
689660
this.installedApp = undefined;
690661
this.knownViewport = undefined;
691662
if (client === undefined) return;
@@ -725,53 +696,32 @@ export class AgentDeviceSurface {
725696
}),
726697
signal,
727698
);
728-
this.sessionApp = app;
729699
this.launched(result.appBundleId ?? result.appName ?? app);
730700
}
731701

732702
/**
733-
* Puts an app's permissions in place before it launches. agent-device sets
734-
* a permission on the app its session is on, so a session on another app,
735-
* or on none yet, is first brought onto this one with a foreground open;
736-
* the warm-up in `prepare` did that for the pinned app under the session
737-
* this worker resumed, so its first launch needs none. Before the launch,
738-
* never after: iOS terminates a running app whose
739-
* permission changed, and Android one whose permission was revoked, so a
740-
* change after the launch would leave the test on no screen.
703+
* Puts an app's permissions in place before it launches, never after: iOS
704+
* terminates a running app whose permission changed, and Android one whose
705+
* permission was revoked, so a change after the launch would leave the
706+
* test on no screen.
741707
*/
742708
private async presetPermissions(app: string, permissions: LaunchPermissions, signal: AbortSignal): Promise<void> {
743709
const entries = Object.entries(permissions).filter(
744710
(entry): entry is [DevicePermission, PermissionState] => entry[1] !== undefined,
745711
);
746-
if (entries.length === 0) return;
747-
if (this.sessionApp !== app) await this.open(app, false, undefined, signal);
748-
for (const [permission, state] of entries) await this.permission(permission, state, signal);
712+
for (const [permission, state] of entries) await this.permission(permission, state, app, signal);
749713
}
750714

751-
/**
752-
* One permission change for `device.setPermission`: on the app the session
753-
* is on, which is what agent-device acts on. With none known here (nothing
754-
* opened yet, `closeApp`, a worker resumed on a bare session) the pinned
755-
* app is brought to the foreground first. agent-device's own refusal, met
756-
* when its session lost the app since (a failed attempt left it on none),
757-
* gets the same foreground open and the command once more.
758-
*/
715+
/** One permission change for `device.setPermission`: on the pinned app, else on the app agent-device's session is on. */
759716
async setPermission(permission: DevicePermission, state: PermissionState, signal: AbortSignal): Promise<void> {
760-
const app = this.pinnedApp;
761-
if (this.sessionApp === undefined && app !== undefined) await this.open(app, false, undefined, signal);
762-
try {
763-
await this.permission(permission, state, signal);
764-
} catch (cause) {
765-
if (signal.aborted || app === undefined || !isNoSessionApp(cause)) throw cause;
766-
await this.open(app, false, undefined, signal);
767-
await this.permission(permission, state, signal);
768-
}
717+
await this.permission(permission, state, this.pinnedApp, signal);
769718
}
770719

771-
private async permission(permission: DevicePermission, state: PermissionState, signal: AbortSignal): Promise<void> {
720+
/** One permission change on `app`, which needs no running app and no open in the session. */
721+
private async permission(permission: DevicePermission, state: PermissionState, app: string | undefined, signal: AbortSignal): Promise<void> {
772722
await this.command(
773723
`permission ${permission} ${state}`,
774-
(client) => client.settings.update({ setting: 'permission', permission, state }),
724+
(client) => client.settings.update({ setting: 'permission', permission, state, ...this.selection(), ...(app === undefined ? {} : { app }) }),
775725
signal,
776726
);
777727
}
@@ -806,7 +756,6 @@ export class AgentDeviceSurface {
806756
}),
807757
signal,
808758
);
809-
this.sessionApp = target;
810759
this.launched(result.appBundleId ?? (target === undefined ? undefined : (result.appName ?? target)));
811760
}
812761

@@ -843,7 +792,6 @@ export class AgentDeviceSurface {
843792
async closeApp(signal: AbortSignal): Promise<void> {
844793
const app = this.appIdentity ?? this.pinnedApp;
845794
await this.command('device.closeApp', (client) => client.apps.close(app === undefined ? {} : { app }), signal);
846-
this.sessionApp = undefined;
847795
this.screenReplaced();
848796
}
849797

0 commit comments

Comments
 (0)