Skip to content

Commit a8758b3

Browse files
committed
fix(apple): preserve scoped simulator behavior through shared tools
1 parent b663be7 commit a8758b3

9 files changed

Lines changed: 142 additions & 72 deletions

File tree

‎packages/platform-apple/src/core/__tests__/app-resolution-deep-link.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,3 +142,37 @@ test('rewriting the Info.plist invalidates the cached scheme set', async () => {
142142
assert.equal(plutilProbes(), probesBeforeRewrite + 1);
143143
});
144144
});
145+
146+
test('deep-link ownership reads app metadata serially and still detects ambiguous owners', async () => {
147+
const { createLocalAppleToolProvider, withAppleToolProvider } =
148+
await import('../tool-provider.ts');
149+
let active = 0;
150+
let peak = 0;
151+
let reads = 0;
152+
const apps = Array.from({ length: 20 }, (_, index) => ({
153+
bundleId: `com.example.app${index}`,
154+
name: `App ${index}`,
155+
applicationType: 'User',
156+
}));
157+
const provider = createLocalAppleToolProvider({
158+
simulatorApps: {
159+
list: async () => ({ type: 'listed', apps }),
160+
readInfoPlist: async () => {
161+
active += 1;
162+
peak = Math.max(peak, active);
163+
reads += 1;
164+
await new Promise<void>((resolve) => setImmediate(resolve));
165+
active -= 1;
166+
return { CFBundleURLTypes: [{ CFBundleURLSchemes: ['shared'] }] };
167+
},
168+
},
169+
});
170+
await withAppleToolProvider(provider, async () => {
171+
assert.equal(
172+
await resolveIosSimulatorDeepLinkBundleId(IOS_TEST_SIMULATOR, 'shared://home'),
173+
undefined,
174+
);
175+
});
176+
assert.equal(reads, 20);
177+
assert.equal(peak, 1);
178+
});

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

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -213,16 +213,12 @@ export async function resolveIosSimulatorDeepLinkBundleId(
213213
const { remainingLookupBudget } = await import('./simulator-app-budget.ts');
214214
const remaining = remainingLookupBudget(options);
215215
const apps = await listSimulatorAppMetadata(device, remaining());
216-
const candidates = apps.filter(
217-
(app) => !app.bundleId.startsWith(AGENT_DEVICE_RUNNER_BUNDLE_PREFIX),
218-
);
219-
const claims = await Promise.all(
220-
candidates.map(async (app) => ({
221-
app,
222-
schemes: await readInstalledAppUrlSchemes(device, app.bundleId, remaining(), app.path),
223-
})),
224-
);
225-
const matches = claims.filter(({ schemes }) => schemes.has(scheme)).map(({ app }) => app);
216+
const matches: SimulatorAppMetadata[] = [];
217+
for (const app of apps) {
218+
if (app.bundleId.startsWith(AGENT_DEVICE_RUNNER_BUNDLE_PREFIX)) continue;
219+
const schemes = await readInstalledAppUrlSchemes(device, app.bundleId, remaining(), app.path);
220+
if (schemes.has(scheme)) matches.push(app);
221+
}
226222
const userMatches = matches.filter((app) => app.applicationType === 'User');
227223
if (userMatches.length === 1) return userMatches[0]?.bundleId;
228224
if (userMatches.length > 1) return undefined;

‎packages/platform-apple/src/core/local-simulator-files.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { readSimctlContainerPath, scopeSimctlArgsForDevice } from './simctl.ts';
1+
import {
2+
readSimctlContainerPath,
3+
scopeSimctlArgsForDevice,
4+
simulatorAddressFor,
5+
} from './simctl.ts';
26
import path from 'node:path';
37
import {
48
copyHostFile,
@@ -27,7 +31,11 @@ export async function copySimulatorFileToHost(
2731
await copyFromContainer('', request);
2832
return;
2933
}
30-
const key = JSON.stringify([request.device.id, request.bundleId, request.containerType]);
34+
const key = JSON.stringify([
35+
simulatorAddressFor(request.device),
36+
request.bundleId,
37+
request.containerType,
38+
]);
3139
const cached = containerPaths.get(key);
3240
if (cached) {
3341
try {

‎packages/platform-apple/src/core/simulator-files.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,3 +163,40 @@ test('an absolute simulator screenshot path does not require an app container lo
163163
expect(await fs.readFile(destinationPath)).toEqual(bytes);
164164
expect(run).not.toHaveBeenCalled();
165165
});
166+
167+
test('container copies distinguish the same simulator UDID in different simulator sets', async () => {
168+
const directory = await mkdtempForTest('simulator-file-set-identity-');
169+
const sets = [path.join(directory, 'first'), path.join(directory, 'second')];
170+
for (const [index, setPath] of sets.entries()) {
171+
await fs.mkdir(path.join(setPath, 'container'), { recursive: true });
172+
await fs.writeFile(path.join(setPath, 'container', 'file.bin'), `set ${index}`);
173+
}
174+
const run = vi.fn(async (args: readonly string[]) => ({
175+
stdout: path.join(args[1]!, 'container'),
176+
stderr: '',
177+
exitCode: 0,
178+
}));
179+
await withAppleToolProvider(createLocalAppleToolProvider({ simctl: { run } }), async () => {
180+
for (const index of [0, 1, 0]) {
181+
const destinationPath = path.join(directory, `copied-${index}.bin`);
182+
await copySimulatorFileToHost({
183+
device: {
184+
platform: 'apple',
185+
appleOs: 'ios',
186+
kind: 'simulator',
187+
id: directory,
188+
name: 'Same UDID',
189+
simulatorSetPath: sets[index],
190+
booted: true,
191+
},
192+
bundleId: 'com.example.app',
193+
containerType: 'data',
194+
sourcePath: 'file.bin',
195+
destinationPath,
196+
timeoutMs: 1000,
197+
});
198+
expect(await fs.readFile(destinationPath, 'utf8')).toBe(`set ${index}`);
199+
}
200+
});
201+
expect(run).toHaveBeenCalledTimes(2);
202+
});

‎packages/platform-apple/src/deployment/runtime.test.ts‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -714,8 +714,8 @@ test.each([false, true])(
714714
const host = deploymentHost(
715715
executor,
716716
xcrunLikeRun((request) => {
717-
if (request.args[0] === 'uninstall' || request.args[0] === 'install')
718-
events.push(request.args[0]);
717+
if (request.args[0] === 'uninstall') events.push('uninstall');
718+
if (request.args[0] === 'install') events.push('native-install');
719719
return bootedSimulatorListResult(request);
720720
}),
721721
);
@@ -726,7 +726,7 @@ test.each([false, true])(
726726
...(hosted
727727
? {
728728
install: async () => {
729-
events.push('install');
729+
events.push('hosted-install');
730730
return { bundleId: 'com.example.app' };
731731
},
732732
}
@@ -743,9 +743,43 @@ test.each([false, true])(
743743
'invalidate-before',
744744
'uninstall',
745745
'materialize',
746-
'install',
746+
hosted ? 'hosted-install' : 'native-install',
747747
'cleanup',
748748
'invalidate-after',
749749
]);
750750
},
751751
);
752+
753+
test.each([
754+
[{}, { bundleId: 'com.example.app', appName: 'Example', launchTarget: 'com.example.app' }],
755+
[
756+
{ bundleId: 'com.installed.app' },
757+
{ bundleId: 'com.installed.app', appName: 'Example', launchTarget: 'com.installed.app' },
758+
],
759+
[
760+
{ bundleId: 'com.installed.app', appName: 'Installed', launchTarget: 'installed://home' },
761+
{ bundleId: 'com.installed.app', appName: 'Installed', launchTarget: 'installed://home' },
762+
],
763+
])(
764+
'hosted install preserves metadata and fills artifact defaults: %j',
765+
async (result, expected) => {
766+
const run = xcrunLikeRun(bootedSimulatorListResult);
767+
const operations = createAppleAppDeploymentOperations({
768+
host: deploymentHost({} as AppleAppDeploymentExecutor, run),
769+
device: appleDevice(),
770+
signal: new AbortController().signal,
771+
install: async () => result,
772+
});
773+
await expect(
774+
operations.deployMaterializedApp!({
775+
artifact: {
776+
installablePath: '/tmp/Example.app',
777+
bundleId: 'com.example.app',
778+
appName: 'Example',
779+
cleanup: async () => {},
780+
},
781+
}),
782+
).resolves.toEqual(expected);
783+
expect(run).not.toHaveBeenCalled();
784+
},
785+
);

‎packages/platform-apple/src/deployment/runtime.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -164,12 +164,17 @@ async function deployPreparedAppleApp(
164164
signal: AbortSignal,
165165
install?: AppDeploymentInstaller,
166166
): Promise<AppDeploymentResult> {
167-
if (install) return await install(input.artifact, signal);
168-
await installAppleApp(host, device, input.artifact.installablePath, signal);
167+
let result: AppDeploymentResult = {};
168+
if (install) result = await install(input.artifact, signal);
169+
else await installAppleApp(host, device, input.artifact.installablePath, signal);
170+
const bundleId = result.bundleId ?? input.artifact.bundleId;
171+
const appName = result.appName ?? input.artifact.appName;
172+
const launchTarget = result.launchTarget ?? bundleId;
169173
return {
170-
...(input.artifact.bundleId ? { bundleId: input.artifact.bundleId } : {}),
171-
...(input.artifact.appName ? { appName: input.artifact.appName } : {}),
172-
...(input.artifact.bundleId ? { launchTarget: input.artifact.bundleId } : {}),
174+
...result,
175+
...(bundleId ? { bundleId } : {}),
176+
...(appName ? { appName } : {}),
177+
...(launchTarget ? { launchTarget } : {}),
173178
};
174179
}
175180

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

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -742,21 +742,3 @@ test('abandoned accepts stop once the request cannot hold another press', async
742742
expect(acceptAlert).toHaveBeenCalledTimes(2);
743743
});
744744
});
745-
746-
test('forwarded launch confirmation uses its provider URL resolver without reading local app containers', async () => {
747-
const local = vi.mocked(resolveIosSimulatorDeepLinkBundleId);
748-
local.mockClear();
749-
const signal = new AbortController().signal;
750-
const resolveOwner = vi.fn(async () => undefined);
751-
const port = createLaunchConfirmationPort(
752-
simulator,
753-
{ appBundleId: 'com.example.app', url: 'example://home' },
754-
{ awaitAlert: async () => ({}), readAlert: async () => ({}), acceptAlert: async () => ({}) },
755-
signal,
756-
undefined,
757-
resolveOwner,
758-
);
759-
await expect(port.resolveUrlOwner()).resolves.toBeUndefined();
760-
expect(resolveOwner).toHaveBeenCalledWith(simulator, 'example://home', signal);
761-
expect(local).not.toHaveBeenCalled();
762-
});

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

Lines changed: 6 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -221,24 +221,12 @@ export async function answerSimulatorLaunchConfirmation(
221221
interactor: Promise<Interactor>,
222222
signal: AbortSignal,
223223
deadlineAtMs: number | undefined,
224-
resolveUrlOwner?: (
225-
device: DeviceInfo,
226-
url: string,
227-
signal: AbortSignal,
228-
) => Promise<string | undefined>,
229224
): Promise<LaunchConfirmationAttempt> {
230225
const settled: Readonly<{ interactor: Interactor }> | LaunchConfirmationAttempt =
231226
await interactor.then((resolved) => ({ interactor: resolved }), unreadable('runner'));
232227
if ('outcome' in settled) return settled;
233228
return await answerLaunchConfirmation(
234-
createLaunchConfirmationPort(
235-
device,
236-
confirmation,
237-
settled.interactor,
238-
signal,
239-
deadlineAtMs,
240-
resolveUrlOwner,
241-
),
229+
createLaunchConfirmationPort(device, confirmation, settled.interactor, signal, deadlineAtMs),
242230
);
243231
}
244232

@@ -248,11 +236,6 @@ export function createLaunchConfirmationPort(
248236
interactor: Pick<Interactor, 'awaitAlert' | 'readAlert' | 'acceptAlert'>,
249237
signal: AbortSignal,
250238
deadlineAtMs: number | undefined,
251-
resolveUrlOwner?: (
252-
device: DeviceInfo,
253-
url: string,
254-
signal: AbortSignal,
255-
) => Promise<string | undefined>,
256239
): LaunchConfirmationPort {
257240
const awaitAlert = interactor.awaitAlert?.bind(interactor);
258241
const readAlert = interactor.readAlert?.bind(interactor);
@@ -270,12 +253,10 @@ export function createLaunchConfirmationPort(
270253
),
271254
readAlert: async () => await alertIfPresent(readAlert(target)),
272255
acceptAlert: async () => await acceptAlert(target),
273-
resolveUrlOwner: resolveUrlOwner
274-
? () => resolveUrlOwner(device, url, signal)
275-
: async () =>
276-
await resolveIosSimulatorDeepLinkBundleId(device, url, {
277-
timeoutMs: URL_OWNER_LOOKUP_TIMEOUT_MS,
278-
signal,
279-
}),
256+
resolveUrlOwner: async () =>
257+
await resolveIosSimulatorDeepLinkBundleId(device, url, {
258+
timeoutMs: URL_OWNER_LOOKUP_TIMEOUT_MS,
259+
signal,
260+
}),
280261
});
281262
}

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

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -73,11 +73,6 @@ type AppleLifecycleServices = Pick<
7373
device: DeviceInfo,
7474
input: OpenApplicationInput,
7575
): Promise<string | undefined>;
76-
resolveUrlOwner?: (
77-
device: DeviceInfo,
78-
url: string,
79-
signal: AbortSignal,
80-
) => Promise<string | undefined>;
8176
runnerFreeObservation: boolean;
8277
};
8378

@@ -215,7 +210,7 @@ async function openAppleApplication(
215210
localIosSimulator,
216211
{
217212
observation,
218-
answerConfirmation: confirmationAnswer(host, binding, input, launch),
213+
answerConfirmation: confirmationAnswer(binding, input, launch),
219214
redispatchLaunchUrl: confirmationRedispatch(binding, input, launch),
220215
},
221216
timing,
@@ -358,7 +353,6 @@ async function openLaunchUrl(
358353
* answered.
359354
*/
360355
function confirmationAnswer(
361-
host: AppleLifecycleServices,
362356
binding: BoundAppleInteractor,
363357
input: OpenApplicationInput,
364358
{ confirmation }: AppleLaunchPlan,
@@ -372,7 +366,6 @@ function confirmationAnswer(
372366
binding.resolveInteractor(input.execution, confirmation.appBundleId),
373367
binding.signal,
374368
input.execution.requestDeadlineAtMs,
375-
host.resolveUrlOwner,
376369
);
377370
};
378371
}

0 commit comments

Comments
 (0)