Skip to content

Commit 5acb488

Browse files
committed
fix(apple): bound and abort the launch URL owner lookup
The settle's URL-owner lookup ran simctl listapps and one plutil per installed app with no timeout and no signal, so a wedged CoreSimulator held open --launch-url without limit. The lookup now shares one 10 s deadline across every spawn and the open's signal aborts it.
1 parent 8f8ac7c commit 5acb488

4 files changed

Lines changed: 134 additions & 30 deletions

File tree

‎packages/platform-apple/src/core/app-resolution.ts‎

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { runAppleToolCommand } from './tool-provider.ts';
1616
import { runSimctlForDevice } from './simctl.ts';
1717
import { resolveIosPhysicalDeviceControl } from './physical-device-control.ts';
1818
import { createTtlMemo } from '@agent-device/kernel/ttl-memo';
19+
import { Deadline } from '@agent-device/host-kit/retry';
1920

2021
const ALIASES: Record<string, string> = {
2122
settings: 'com.apple.Preferences',
@@ -168,20 +169,30 @@ type SimulatorAppMetadata = {
168169
applicationType?: string;
169170
};
170171

172+
/**
173+
* The installed app that owns `url`'s scheme, when exactly one does. `timeoutMs` is one deadline
174+
* shared by the app listing and every Info.plist read; a spawn it cuts short or `signal` aborts
175+
* rejects the lookup.
176+
*/
171177
export async function resolveIosSimulatorDeepLinkBundleId(
172178
device: DeviceInfo,
173179
url: string,
180+
options: SimulatorAppListOptions = {},
174181
): Promise<string | undefined> {
175182
if (!isIosFamily(device) || device.kind !== 'simulator') return undefined;
176183
const scheme = parseUrlScheme(url);
177184
if (!scheme) return undefined;
178185

179-
const apps = await listSimulatorAppMetadata(device);
186+
const remaining = remainingLookupBudget(options);
187+
const apps = await listSimulatorAppMetadata(device, remaining());
180188
const matches: SimulatorAppMetadata[] = [];
181189
for (const app of apps) {
182190
if (app.bundleId.startsWith(AGENT_DEVICE_RUNNER_BUNDLE_PREFIX)) continue;
183191
if (!app.path) continue;
184-
const schemes = await readIosSimulatorAppUrlSchemes(path.join(app.path, 'Info.plist'));
192+
const schemes = await readIosSimulatorAppUrlSchemes(
193+
path.join(app.path, 'Info.plist'),
194+
remaining(),
195+
);
185196
if (schemes.has(scheme)) {
186197
matches.push(app);
187198
}
@@ -193,6 +204,16 @@ export async function resolveIosSimulatorDeepLinkBundleId(
193204
return matches.length === 1 ? matches[0]?.bundleId : undefined;
194205
}
195206

207+
function remainingLookupBudget({
208+
timeoutMs,
209+
signal,
210+
}: SimulatorAppListOptions): () => SimulatorAppListOptions {
211+
const abortable = signal ? { signal } : {};
212+
if (timeoutMs === undefined) return () => abortable;
213+
const deadline = Deadline.fromTimeoutMs(timeoutMs);
214+
return () => ({ timeoutMs: Math.max(1, deadline.remainingMs()), ...abortable });
215+
}
216+
196217
function parseUrlScheme(url: string): string | undefined {
197218
const match = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(url.trim());
198219
return match?.[1]?.toLowerCase();
@@ -209,10 +230,11 @@ export async function listIosApps(device: DeviceInfo, filter: AppsFilter): Promi
209230
return await resolveIosPhysicalDeviceControl(device).listApps(device, filter);
210231
}
211232

212-
type SimulatorAppListOptions = {
233+
type SimulatorAppListOptions = Readonly<{
213234
/** Unset (default) preserves prior unbounded behavior for normal command flow. */
214235
timeoutMs?: number;
215-
};
236+
signal?: AbortSignal;
237+
}>;
216238

217239
async function listSimulatorApps(
218240
device: DeviceInfo,
@@ -232,6 +254,7 @@ async function listSimulatorAppMetadata(
232254
const result = await runSimctlForDevice(device, ['listapps', device.id], {
233255
allowFailure: true,
234256
timeoutMs: options?.timeoutMs,
257+
signal: options?.signal,
235258
});
236259
const stdout = result.stdout as string;
237260
const trimmed = stdout.trim();
@@ -270,6 +293,7 @@ async function listSimulatorAppMetadata(
270293
allowFailure: true,
271294
stdin: trimmed,
272295
timeoutMs: options?.timeoutMs,
296+
signal: options?.signal,
273297
});
274298
if (converted.exitCode === 0 && converted.stdout.trim().startsWith('{')) {
275299
parsed = JSON.parse(converted.stdout) as Record<
@@ -322,19 +346,22 @@ const iosSimulatorAppUrlSchemeMemo = createTtlMemo<string, Set<string>>({
322346
scheduleExpiry: true,
323347
});
324348

325-
async function readIosSimulatorAppUrlSchemes(infoPlistPath: string): Promise<Set<string>> {
349+
async function readIosSimulatorAppUrlSchemes(
350+
infoPlistPath: string,
351+
options: SimulatorAppListOptions,
352+
): Promise<Set<string>> {
326353
let cacheKey: string | undefined;
327354
try {
328355
cacheKey = `${infoPlistPath}:${(await hostFileStat(infoPlistPath)).mtimeMs}`;
329356
} catch {
330357
cacheKey = undefined;
331358
}
332359
if (cacheKey === undefined) {
333-
return (await readIosSimulatorAppUrlSchemesUncached(infoPlistPath)) ?? new Set();
360+
return (await readIosSimulatorAppUrlSchemesUncached(infoPlistPath, options)) ?? new Set();
334361
}
335362
const cached = iosSimulatorAppUrlSchemeMemo.get(cacheKey);
336363
if (cached) return cached;
337-
const schemes = await readIosSimulatorAppUrlSchemesUncached(infoPlistPath);
364+
const schemes = await readIosSimulatorAppUrlSchemesUncached(infoPlistPath, options);
338365
if (schemes) iosSimulatorAppUrlSchemeMemo.set(cacheKey, schemes);
339366
return schemes ?? new Set();
340367
}
@@ -345,13 +372,12 @@ async function readIosSimulatorAppUrlSchemes(infoPlistPath: string): Promise<Set
345372
*/
346373
async function readIosSimulatorAppUrlSchemesUncached(
347374
infoPlistPath: string,
375+
options: SimulatorAppListOptions,
348376
): Promise<Set<string> | undefined> {
349377
const result = await runAppleToolCommand(
350378
'plutil',
351379
['-convert', 'json', '-o', '-', infoPlistPath],
352-
{
353-
allowFailure: true,
354-
},
380+
{ allowFailure: true, ...options },
355381
);
356382
if (result.exitCode !== 0) return undefined;
357383
try {

‎packages/platform-apple/src/launch-confirmation.test.ts‎

Lines changed: 81 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ import type { Interactor } from '@agent-device/contracts/interactor-types';
44
import type { DeviceInfo } from '@agent-device/kernel/device';
55
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
66
import { AppError } from '@agent-device/kernel/errors';
7+
import type { ExecOptions, ExecResult } from '@agent-device/host-kit/command';
78
import { resolveIosSimulatorDeepLinkBundleId } from './core/app-resolution.ts';
9+
import { IOS_APP_LAUNCH_TIMEOUT_MS } from './core/config.ts';
10+
import { type AppleToolProvider, withAppleToolProvider } from './core/tool-provider.ts';
811
import {
912
answerLaunchConfirmation,
1013
answerSimulatorLaunchConfirmation,
@@ -18,9 +21,13 @@ vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => {
1821
return { ...actual, emitDiagnostic: vi.fn() };
1922
});
2023

21-
vi.mock('./core/app-resolution.ts', () => ({
22-
resolveIosSimulatorDeepLinkBundleId: vi.fn(async () => 'com.example.app'),
23-
}));
24+
vi.mock('./core/app-resolution.ts', async (importOriginal) => {
25+
const actual = await importOriginal<typeof import('./core/app-resolution.ts')>();
26+
return {
27+
...actual,
28+
resolveIosSimulatorDeepLinkBundleId: vi.fn(actual.resolveIosSimulatorDeepLinkBundleId),
29+
};
30+
});
2431

2532
const simulator: DeviceInfo = {
2633
platform: 'apple',
@@ -186,40 +193,93 @@ test.each([
186193
await expect(answerLaunchConfirmation(device)).resolves.toBeUndefined();
187194
});
188195

189-
test('the answer returns only after its accept settled, however long the accept takes', async () => {
196+
/**
197+
* A CoreSimulator that never answers: each spawn settles only when its exec timeout fires or its
198+
* signal aborts, the way `exec.ts` ends a wedged child.
199+
*/
200+
function wedgedCoreSimulator(): AppleToolProvider & { spawns: () => number } {
201+
let spawns = 0;
202+
const hang = async (options?: ExecOptions): Promise<ExecResult> =>
203+
await new Promise((_resolve, reject) => {
204+
spawns += 1;
205+
if (options?.timeoutMs) {
206+
setTimeout(() => reject(spawnTimeout()), options.timeoutMs);
207+
}
208+
options?.signal?.addEventListener('abort', () => reject(options.signal?.reason), {
209+
once: true,
210+
});
211+
});
212+
return {
213+
whichCommand: async () => true,
214+
runCommand: async (_cmd, _args, options) => await hang(options),
215+
simctl: { run: async (_args, options) => await hang(options) },
216+
devicectl: { run: async (_args, options) => await hang(options) },
217+
spawns: () => spawns,
218+
};
219+
}
220+
221+
function confirmationRunner() {
222+
const acceptAlert = vi.fn(async () => ({}));
223+
const interactor = { readAlert: async () => CONFIRMATION, acceptAlert } as unknown as Interactor;
224+
return { interactor, acceptAlert };
225+
}
226+
227+
test('a hung URL owner lookup leaves the open unanswered within the launch budget', async () => {
190228
vi.useFakeTimers();
191229
try {
192-
const acceptMs = 70_000;
193-
const { port: device, acceptAlert } = port(async () => CONFIRMATION, {
194-
acceptAlert: async () =>
195-
await new Promise((resolve) => {
196-
setTimeout(() => resolve({}), acceptMs);
197-
}),
198-
});
230+
const { interactor, acceptAlert } = confirmationRunner();
199231
let answered: unknown = 'pending';
200-
const answer = answerLaunchConfirmation(device).then((value) => (answered = value));
201-
202-
await vi.advanceTimersByTimeAsync(acceptMs - 1);
203-
expect(acceptAlert).toHaveBeenCalledOnce();
204-
expect(answered).toBe('pending');
232+
const answer = withAppleToolProvider(wedgedCoreSimulator(), async () =>
233+
answerSimulatorLaunchConfirmation(
234+
simulator,
235+
{ url: 'example://automation', appBundleId: 'com.example.app' },
236+
Promise.resolve(interactor),
237+
new AbortController().signal,
238+
).then((value) => (answered = value)),
239+
);
205240

206-
await vi.advanceTimersByTimeAsync(1);
241+
await vi.advanceTimersByTimeAsync(IOS_APP_LAUNCH_TIMEOUT_MS - 1);
242+
expect(answered).toBeUndefined();
207243
await answer;
208-
expect(answered).toBe('accepted');
244+
expect(acceptAlert).not.toHaveBeenCalled();
209245
} finally {
210246
vi.useRealTimers();
211247
}
212248
});
213249

250+
test('the open aborting ends the URL owner lookup', async () => {
251+
const { interactor, acceptAlert } = confirmationRunner();
252+
const open = new AbortController();
253+
const coreSimulator = wedgedCoreSimulator();
254+
const answer = withAppleToolProvider(coreSimulator, async () =>
255+
answerSimulatorLaunchConfirmation(
256+
simulator,
257+
{ url: 'example://automation', appBundleId: 'com.example.app' },
258+
Promise.resolve(interactor),
259+
open.signal,
260+
),
261+
);
262+
263+
await vi.waitFor(() => expect(coreSimulator.spawns()).toBe(1));
264+
open.abort(new AppError('COMMAND_FAILED', 'request canceled'));
265+
266+
await expect(answer).resolves.toBeUndefined();
267+
expect(acceptAlert).not.toHaveBeenCalled();
268+
});
269+
214270
test('the port reads and accepts the alert for the session app and asks the scheme owner', async () => {
215271
const readAlert = vi.fn(async () => CONFIRMATION);
216272
const acceptAlert = vi.fn(async () => ({}));
217273
const interactor = { readAlert, acceptAlert } as unknown as Interactor;
218274

275+
const signal = new AbortController().signal;
276+
vi.mocked(resolveIosSimulatorDeepLinkBundleId).mockResolvedValueOnce('com.example.app');
277+
219278
const device = createLaunchConfirmationPort(
220279
simulator,
221280
{ url: 'example://automation', appBundleId: 'com.example.app' },
222281
interactor,
282+
signal,
223283
);
224284
await device.readAlert();
225285
await device.acceptAlert();
@@ -231,6 +291,7 @@ test('the port reads and accepts the alert for the session app and asks the sche
231291
expect(resolveIosSimulatorDeepLinkBundleId).toHaveBeenCalledWith(
232292
simulator,
233293
'example://automation',
294+
{ timeoutMs: expect.any(Number), signal },
234295
);
235296
});
236297

@@ -248,6 +309,7 @@ test('the port reads a typed absence as no alert and keeps any other failure', a
248309
simulator,
249310
{ url: 'example://automation', appBundleId: 'com.example.app' },
250311
interactor,
312+
new AbortController().signal,
251313
);
252314

253315
await expect(device.readAlert()).resolves.toBeUndefined();
@@ -260,6 +322,7 @@ test('a runner that cannot be resolved leaves the open unanswered', async () =>
260322
simulator,
261323
{ url: 'example://automation', appBundleId: 'com.example.app' },
262324
Promise.reject(new AppError('COMMAND_FAILED', 'xcrun timed out', { timeoutMs: 10_000 })),
325+
new AbortController().signal,
263326
),
264327
).resolves.toBeUndefined();
265328
});

‎packages/platform-apple/src/launch-confirmation.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@ export const LAUNCH_CONFIRMATION_FOREIGN_APP_REASON = 'launch_confirmation_forei
1717
*/
1818
const LAUNCH_CONFIRMATION_TITLE = /^Open in [“"].+[”"]\?$/u;
1919

20+
/**
21+
* One shared deadline for the URL-owner lookup (the app listing and every Info.plist read). The
22+
* alert read and accept are each bounded by the runner's `DEFAULT_ALERT_TIMEOUT_MS`; the lookup gets
23+
* the same bound, well inside `IOS_APP_LAUNCH_TIMEOUT_MS`, so a wedged CoreSimulator leaves the open
24+
* unanswered instead of holding it.
25+
*/
26+
const URL_OWNER_LOOKUP_TIMEOUT_MS = 10_000;
27+
2028
/** A custom-scheme launch URL SpringBoard may hold for the session app it was checked for. */
2129
export type LaunchConfirmationTarget = Readonly<{ url: string; appBundleId: string }>;
2230

@@ -101,18 +109,20 @@ export async function answerSimulatorLaunchConfirmation(
101109
device: DeviceInfo,
102110
confirmation: LaunchConfirmationTarget,
103111
interactor: Promise<Interactor>,
112+
signal: AbortSignal,
104113
): Promise<LaunchConfirmation | undefined> {
105114
const resolved = await interactor.catch(failed('runner'));
106115
if (!resolved) return undefined;
107116
return await answerLaunchConfirmation(
108-
createLaunchConfirmationPort(device, confirmation, resolved),
117+
createLaunchConfirmationPort(device, confirmation, resolved, signal),
109118
);
110119
}
111120

112121
export function createLaunchConfirmationPort(
113122
device: DeviceInfo,
114123
{ url, appBundleId }: LaunchConfirmationTarget,
115124
interactor: Interactor,
125+
signal: AbortSignal,
116126
): LaunchConfirmationPort {
117127
const readAlert = interactor.readAlert?.bind(interactor);
118128
const acceptAlert = interactor.acceptAlert?.bind(interactor);
@@ -124,6 +134,10 @@ export function createLaunchConfirmationPort(
124134
appBundleId,
125135
readAlert: async () => await alertIfPresent(readAlert(target)),
126136
acceptAlert: async () => await acceptAlert(target),
127-
resolveUrlOwner: async () => await resolveIosSimulatorDeepLinkBundleId(device, url),
137+
resolveUrlOwner: async () =>
138+
await resolveIosSimulatorDeepLinkBundleId(device, url, {
139+
timeoutMs: URL_OWNER_LOOKUP_TIMEOUT_MS,
140+
signal,
141+
}),
128142
});
129143
}

‎packages/platform-apple/src/lifecycle.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,7 @@ function confirmationAnswer(
272272
binding.device,
273273
confirmation,
274274
binding.resolveInteractor(input.execution, confirmation.appBundleId),
275+
binding.signal,
275276
);
276277
};
277278
}

0 commit comments

Comments
 (0)