Compare commits

...
Author SHA1 Message Date
Vojtech NovakandClaude Opus 5.5 236f79a196 [build-tools] Remove comments that repeat the code
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 11:51:59 +01:00
Vojtech NovakandClaude Opus 5.5 6919d74615 [build-tools] One test for each endDeviceApps rule: the shared per-device loop is tested once, on iOS
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 11:50:22 +01:00
Vojtech NovakandClaude Opus 5.5 972e23316a [build-tools] Review fixes: device commands in the device utils, a 30 s deadline, one failing device does not stop the others
- `IosSimulatorUtils.terminateUserAppsAsync` and `AndroidEmulatorUtils.forceStopUserAppsAsync`
  hold the per-device commands; `endDeviceAppsAsync` lists the booted devices with the existing
  helpers and loops over them.
- One `AbortSignal.timeout(30 s)` bounds every device command, so a wedged device cannot hold
  the job after the session stopped.
- Each device gets its turn; the failures are thrown together as one AggregateError, which
  `finishRemoteSessionAsync` logs and reports.
- `finishRemoteSessionAsync` keeps one task list; the device apps task waits for the others.
- An exhaustive switch on the runtime platform.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 11:21:09 +01:00
Vojtech NovakandClaude Opus 5.5 3a1853d0ca [build-tools] End the device apps when a remote device run session stops
`eas simulator:stop` only marks the session stopped. The job then stops its own tools, and the VM
is deleted from the host. Nothing ends the app first, so its connections never close: a dev server
reached through the Expo tunnel lists the app's debugger page for about 16 minutes, and its idle
sockets stay open until the dev server restarts.

`finishRemoteSessionAsync` now ends the running apps on every booted Simulator or emulator, after
every other teardown task. A failure is logged and reported, and does not fail the session.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 11:21:09 +01:00
16 changed files with 306 additions and 5 deletions

No files matched your search

@@ -0,0 +1,5 @@
---
'@expo/build-tools': patch
---
Remote device run sessions now end the running apps on the Simulator or emulator when the session stops, so a dev server reached through a tunnel drops the app's debugger page instead of listing it until the dev server restarts.
@@ -30,6 +30,7 @@ import { createStartAppiumRemoteSessionBuildFunction } from '../startAppiumRemot
import { createStartArgentRemoteSessionBuildFunction } from '../startArgentRemoteSession';
import { createStartWebPreviewRemoteSessionBuildFunction } from '../startWebPreviewRemoteSession';
jest.mock('../../utils/endDeviceApps');
jest.mock('@expo/turtle-spawn');
jest.mock('../../../utils/IosSimulatorUtils');
jest.mock('../../../utils/processes');
@@ -31,6 +31,7 @@ import { runAgentDeviceRemoteSessionAsync } from '../startAgentDeviceRemoteSessi
// The daemon entry path and the state directory are resolved from the home directory when
// the module loads, so point it at a temp home we can populate.
jest.mock('../../utils/endDeviceApps');
jest.mock('node:os', () => {
const actual = jest.requireActual('node:os');
const actualPath = jest.requireActual('node:path');
@@ -10,6 +10,7 @@ import {
stopAgentDeviceEventCollectionSafelyAsync,
} from '../startAgentDeviceRemoteSession';
jest.mock('../../utils/endDeviceApps');
jest.mock('../../../sentry');
jest.mock('@expo/turtle-spawn', () => ({ __esModule: true, default: jest.fn() }));
jest.mock('../../utils/remoteDeviceRunSession', () => ({
@@ -29,6 +29,7 @@ import { createStartAgentDeviceSessionBuildFunction } from '../startAgentDeviceS
import { startAndroidEmulatorAsync } from '../startAndroidEmulator';
import { bootIosSimulatorAsync } from '../startIosSimulator';
jest.mock('../../utils/endDeviceApps');
jest.mock('../../utils/localEgress', () => ({
stopLocalEgressResourcesAsync: jest.fn().mockResolvedValue(undefined),
}));
@@ -42,6 +42,7 @@ import {
resolveAppiumDeviceAsync,
} from '../startAppiumRemoteSession';
jest.mock('../../utils/endDeviceApps');
jest.mock('node:timers/promises', () => ({
...jest.requireActual('node:timers/promises'),
setTimeout: jest.fn(jest.requireActual('node:timers/promises').setTimeout),
@@ -34,6 +34,7 @@ import { createStartupWatchMock } from '../../../__tests__/utils/startupWatch';
import { createStartArgentRemoteSessionBuildFunction } from '../startArgentRemoteSession';
import { readIosApplicationIdentifierAsync } from '../../utils/iosAppArtifact';
jest.mock('../../utils/endDeviceApps');
// Redirect ~/.argent (where the tool-server writes its state file and event log) to a temp
// home so waitForArgentToolServerStateAsync — which lives in the module under test and cannot
// be mocked directly — can read a real state file we control.
@@ -346,6 +346,7 @@ export async function runAgentDeviceRemoteSessionAsync(
})();
await finishRemoteSessionAsync({
logger,
device: { runtimePlatform, env },
sessionFailed,
teardown: [
...startupResults.flatMap((result): [string, Promise<unknown>][] =>
@@ -415,6 +415,7 @@ export function createStartAppiumRemoteSessionBuildFunction(
})();
await finishRemoteSessionAsync({
logger,
device: { runtimePlatform, env },
sessionFailed,
teardown: [
['Appium tunnel', appiumTunnel?.stopAsync(), TOOL_TUNNEL_TEARDOWN_OPTIONS],
@@ -481,6 +481,7 @@ export function createStartArgentRemoteSessionBuildFunction(
})();
await finishRemoteSessionAsync({
logger,
device: { runtimePlatform, env },
sessionFailed,
teardown: [
['Argent tunnel', toolsTunnel?.stopAsync(), TOOL_TUNNEL_TEARDOWN_OPTIONS],
@@ -0,0 +1,102 @@
import { createLogger } from '@expo/logger';
import { BuildRuntimePlatform, type BuildStepEnv } from '@expo/steps';
import spawn from '@expo/turtle-spawn';
import { endDeviceAppsAsync } from '../endDeviceApps';
jest.mock('@expo/turtle-spawn');
const env = {} as BuildStepEnv;
const logger = createLogger({ name: 'test', level: 'fatal' });
const A = '4F15B69B-95F9-450D-BAF1-6B7985797355';
const B = '9C0A3E1D-2B47-4F38-8E6A-1D5F0C2B7A64';
function fakeSpawn(answers: Record<string, string | Error>): void {
jest.mocked(spawn).mockImplementation(((command: string, args: string[]) => {
const answer = answers[[command, ...args].join(' ')] ?? '';
return (
answer instanceof Error ? Promise.reject(answer) : Promise.resolve({ stdout: answer })
) as never;
}) as never);
}
function deviceCommands(): { argv: string[]; signal: unknown }[] {
return jest
.mocked(spawn)
.mock.calls.map(([command, args, options]) => ({
argv: [command, ...args],
signal: (options as { signal?: unknown }).signal,
}))
.filter(({ argv }) => argv.includes('terminate') || argv.includes('shell'));
}
const bootedList = JSON.stringify({
devices: { 'com.apple.CoreSimulator.SimRuntime.iOS-26-0': [{ udid: A }, { udid: B }] },
});
describe(endDeviceAppsAsync, () => {
beforeEach(() => {
jest.mocked(spawn).mockReset();
});
it('terminates the non-system apps on every Simulator, past an app and a Simulator that fail', async () => {
const wedged = new Error('timed out');
fakeSpawn({
'xcrun simctl list devices --json --no-escape-slashes booted': bootedList,
[`xcrun simctl spawn ${A} launchctl list`]: wedged,
[`xcrun simctl spawn ${B} launchctl list`]: [
'PID\tStatus\tLabel',
'80297\t0\tUIKitApplication:com.apple.Spotlight[9ec9][rb-legacy]',
'80300\t0\tUIKitApplication:dev.expo.easexample[ca71][rb-legacy]',
'80301\t0\tUIKitApplication:host.exp.Exponent[a1b2][rb-legacy]',
'-\t0\tcom.apple.mobilesafari.webcontent',
].join('\n'),
// Exited between the list and the terminate.
[`xcrun simctl terminate ${B} dev.expo.easexample`]: new Error('found nothing to terminate'),
});
const error = await endDeviceAppsAsync({
runtimePlatform: BuildRuntimePlatform.DARWIN,
env,
logger,
}).catch((err: unknown) => err);
expect(deviceCommands()).toEqual([
{
argv: ['xcrun', 'simctl', 'terminate', B, 'dev.expo.easexample'],
signal: expect.any(AbortSignal),
},
{
argv: ['xcrun', 'simctl', 'terminate', B, 'host.exp.Exponent'],
signal: expect.any(AbortSignal),
},
]);
expect(error).toBeInstanceOf(AggregateError);
expect((error as AggregateError).errors.map((err: Error) => [err.message, err.cause])).toEqual([
[`Could not end the apps on the Simulator ${A}.`, wedged],
]);
});
it('force-stops the installed apps on each online emulator', async () => {
jest.mocked(spawn).mockImplementation(((_command: string, args: string[]) =>
Promise.resolve({
stdout:
args[0] === 'devices'
? [
'List of devices attached',
'emulator-5554 device product:sdk_gphone64_x86_64',
'emulator-5556 offline',
'emulator-5558 device product:sdk_gphone64_x86_64',
'',
].join('\n')
: '',
})) as never);
await endDeviceAppsAsync({ runtimePlatform: BuildRuntimePlatform.LINUX, env, logger });
expect(deviceCommands().map(({ argv, signal }) => [argv.slice(0, 4), signal])).toEqual([
[['adb', '-s', 'emulator-5554', 'shell'], expect.any(AbortSignal)],
[['adb', '-s', 'emulator-5558', 'shell'], expect.any(AbortSignal)],
]);
});
});
@@ -25,6 +25,7 @@ import {
} from '../IosSimulatorRecordingUtils';
import * as remoteDeviceRunSession from '../remoteDeviceRunSession';
import { readServeSimServersAsync } from '../serveSimMetricsRecorder';
import { endDeviceAppsAsync } from '../endDeviceApps';
import { sleepAsync } from '../../../utils/retry';
import { uploadDeviceRunSessionScreenRecordingsAsync } from '../deviceRunSessionScreenRecordings';
import { DEVICE_RUN_SESSION_TOKEN_HEADER } from '../deviceRunSessionWorkerApi';
@@ -65,6 +66,7 @@ import {
import { parseNetworkCaptureFieldsInput, parseNetworkCaptureInputs } from '../networkCaptureFields';
jest.mock('@ngrok/ngrok');
jest.mock('../endDeviceApps');
jest.mock('../localEgress', () => ({
...jest.requireActual('../localEgress'),
readLocalEgressHandoffAsync: jest.fn().mockResolvedValue(null),
@@ -231,9 +233,46 @@ function createEnvMock(): BuildStepEnv {
describe(finishRemoteSessionAsync, () => {
const tunnelError = new Error('tunnel stop timed out');
const serverError = new Error('server stop failed');
const device = { runtimePlatform: BuildRuntimePlatform.DARWIN, env: createEnvMock() };
beforeEach(() => {
jest.mocked(Sentry).capture.mockReset();
jest.mocked(endDeviceAppsAsync).mockReset().mockResolvedValue();
});
it('ends the device apps after every other task, and does not fail a session on it', async () => {
const logger = { warn: jest.fn() } as unknown as bunyan;
const order: string[] = [];
let stopServer!: () => void;
const server = new Promise<void>(resolve => {
stopServer = resolve;
}).then(() => {
order.push('Appium server');
});
const appsError = new Error('simctl failed');
jest.mocked(endDeviceAppsAsync).mockImplementation(async () => {
order.push('device apps');
throw appsError;
});
const finish = finishRemoteSessionAsync({
logger,
device,
sessionFailed: false,
teardown: [['Appium server', server]],
});
stopServer();
await expect(finish).resolves.toBeUndefined();
expect(order).toEqual(['Appium server', 'device apps']);
expect(endDeviceAppsAsync).toHaveBeenCalledWith({ ...device, logger });
expect(jest.mocked(Sentry).capture.mock.calls).toEqual([
[
'Could not stop the device apps after the remote session ended',
appsError,
{ level: 'warning' },
],
]);
});
it('does not fail a successful session when only a tunnel cannot stop', async () => {
@@ -241,6 +280,7 @@ describe(finishRemoteSessionAsync, () => {
await expect(
finishRemoteSessionAsync({
logger,
device,
sessionFailed: false,
teardown: [
['Appium tunnel', Promise.reject(tunnelError), TOOL_TUNNEL_TEARDOWN_OPTIONS],
@@ -266,6 +306,7 @@ describe(finishRemoteSessionAsync, () => {
await expect(
finishRemoteSessionAsync({
logger,
device,
sessionFailed: false,
teardown: [
['Appium tunnel', Promise.reject(tunnelError), TOOL_TUNNEL_TEARDOWN_OPTIONS],
@@ -288,6 +329,7 @@ describe(finishRemoteSessionAsync, () => {
await expect(
finishRemoteSessionAsync({
logger,
device,
sessionFailed: true,
teardown: [
['Appium tunnel', Promise.reject(tunnelError), TOOL_TUNNEL_TEARDOWN_OPTIONS],
@@ -0,0 +1,72 @@
import { type bunyan } from '@expo/logger';
import { BuildRuntimePlatform, type BuildStepEnv } from '@expo/steps';
import { AndroidEmulatorUtils } from '../../utils/AndroidEmulatorUtils';
import { IosSimulatorUtils } from '../../utils/IosSimulatorUtils';
/** A wedged device must not hold the job: the session is already stopped. */
const END_DEVICE_APPS_TIMEOUT_MS = 30_000;
/**
* Ends the apps on every booted Simulator or emulator. An app that ends closes its connections,
* so a dev server reached through a tunnel drops the app's debugger page. The VM delete after the
* job closes nothing: the page then stays listed until the dev server restarts.
*/
export async function endDeviceAppsAsync({
runtimePlatform,
env,
logger,
}: {
runtimePlatform: BuildRuntimePlatform;
env: BuildStepEnv;
logger: bunyan;
}): Promise<void> {
const signal = AbortSignal.timeout(END_DEVICE_APPS_TIMEOUT_MS);
switch (runtimePlatform) {
case BuildRuntimePlatform.DARWIN: {
const simulators = await IosSimulatorUtils.getAvailableDevicesAsync({
env,
filter: 'booted',
});
await endOnEachDeviceAsync(
simulators.map(({ udid }) => [
`Simulator ${udid}`,
() => IosSimulatorUtils.terminateUserAppsAsync({ udid, env, logger, signal }),
])
);
return;
}
case BuildRuntimePlatform.LINUX: {
const emulators = await AndroidEmulatorUtils.getAttachedDevicesAsync({ env });
await endOnEachDeviceAsync(
emulators
.filter(({ state }) => state === 'device')
.map(({ serialId }) => [
`emulator ${serialId}`,
async () => {
await AndroidEmulatorUtils.forceStopUserAppsAsync({ serialId, env, signal });
logger.info(`Ended the installed apps on the emulator ${serialId}.`);
},
])
);
return;
}
}
}
/** Every device gets its turn; one that fails does not keep the apps of the others running. */
async function endOnEachDeviceAsync(
devices: [name: string, endAsync: () => Promise<void>][]
): Promise<void> {
const errors: Error[] = [];
for (const [name, endAsync] of devices) {
try {
await endAsync();
} catch (err) {
errors.push(new Error(`Could not end the apps on the ${name}.`, { cause: err }));
}
}
if (errors.length > 0) {
throw new AggregateError(errors, `Could not end the apps on ${errors.length} device(s).`);
}
}
@@ -26,6 +26,7 @@ import { Sentry } from '../../sentry';
import { isProcessGroupRunning, killProcessGroup } from '../../utils/processes';
import { sleepAsync } from '../../utils/retry';
import { createProcessOutput } from './processOutput';
import { endDeviceAppsAsync } from './endDeviceApps';
import { withDeviceRunSessionTimeoutAsync } from './deviceRunSessionTimeout';
import {
type DeviceRunSessionStatus,
@@ -671,25 +672,37 @@ export type RemoteSessionTeardown = [
];
/**
* Runs every named teardown to completion and logs each failure. The first failure of a task that
* fails the session is rethrown only when the session body succeeded, so a teardown error cannot
* replace the error that ended it.
* Runs every named teardown to completion, then ends the apps on the device, and logs each
* failure. The first failure of a task that fails the session is rethrown only when the session
* body succeeded, so a teardown error cannot replace the error that ended it.
*/
export async function finishRemoteSessionAsync({
teardown,
device,
sessionFailed,
logger,
}: {
teardown: RemoteSessionTeardown[];
device: { runtimePlatform: BuildRuntimePlatform; env: BuildStepEnv };
sessionFailed: boolean;
logger: bunyan;
}): Promise<void> {
const results = await Promise.allSettled(teardown.map(([, task]) => task));
const others = Promise.allSettled(teardown.map(([, task]) => task));
const tasks: RemoteSessionTeardown[] = [
...teardown,
// Last, because the tools above may still read the app.
[
'device apps',
others.then(() => endDeviceAppsAsync({ ...device, logger })),
{ failsSession: false },
],
];
const results = await Promise.allSettled(tasks.map(([, task]) => task));
const failures = results.flatMap((result, index) => {
if (result.status !== 'rejected') {
return [];
}
const [name, , options] = teardown[index];
const [name, , options] = tasks[index];
return [{ name, err: result.reason, failsSession: options?.failsSession ?? true }];
});
for (const { name, err, failsSession } of failures) {
@@ -655,6 +655,28 @@ export namespace AndroidEmulatorUtils {
});
}
/** Force-stops every installed third-party app. */
export async function forceStopUserAppsAsync({
serialId,
env,
signal,
}: {
serialId: AndroidDeviceSerialId;
env: NodeJS.ProcessEnv;
signal?: AbortSignal;
}): Promise<void> {
await spawn(
'adb',
[
'-s',
serialId,
'shell',
'for p in $(pm list packages -3 | cut -d: -f2); do am force-stop "$p"; done',
],
{ env, signal }
);
}
export async function stopAsync({
serialId,
env,
@@ -1,4 +1,5 @@
import { ExpoError, SystemError, UserError } from '@expo/eas-build-job';
import { type bunyan } from '@expo/logger';
import spawn, { SpawnPromise, SpawnResult } from '@expo/turtle-spawn';
import fs from 'node:fs';
import os from 'node:os';
@@ -10,6 +11,8 @@ import { z } from 'zod';
import { retryAsync } from './retry';
import { waitForWarmSimulatorCleanupAsync } from './warmSimulatorCleanup';
const RUNNING_APP_LABEL = /\tUIKitApplication:([^[\s]+)\[/;
export type IosSimulatorUuid = string & z.BRAND<'IosSimulatorUuid'>;
export type IosSimulatorName = string & z.BRAND<'IosSimulatorName'>;
@@ -101,6 +104,39 @@ export namespace IosSimulatorUtils {
return allAvailableDevices;
}
export async function terminateUserAppsAsync({
udid,
env,
logger,
signal,
}: {
udid: IosSimulatorUuid;
env: NodeJS.ProcessEnv;
logger: bunyan;
signal?: AbortSignal;
}): Promise<void> {
const { stdout } = await spawn('xcrun', ['simctl', 'spawn', udid, 'launchctl', 'list'], {
env,
signal,
});
const apps = new Set(
stdout
.split('\n')
.map(line => RUNNING_APP_LABEL.exec(line)?.[1])
.filter((app): app is string => !!app && !app.startsWith('com.apple.'))
);
for (const app of apps) {
try {
await spawn('xcrun', ['simctl', 'terminate', udid, app], { env, signal });
logger.info(`Ended ${app} on the Simulator ${udid}.`);
} catch (err) {
signal?.throwIfAborted();
// "found nothing to terminate" when the app exited after the list.
logger.warn({ err }, `Could not end ${app} on the Simulator ${udid}.`);
}
}
}
export async function getDeviceAsync({
udid,
env,