Skip to content

Commit 50ed204

Browse files
committed
refactor(apple): unify simulator capabilities and cancellation
Require common simulator file and app-metadata capabilities for local and remote providers. Use typed inventory and shared cancellation and readiness paths, preserving result normalization and lazy module loading.
1 parent 1a67e96 commit 50ed204

48 files changed

Lines changed: 895 additions & 627 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.m‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -114,10 +114,8 @@
114114
}
115115
}
116116

117-
// One window read. Both answers are required: an app with no window answers `frame` with
118-
// `(0,0 0x0)` without raising, so only `exists` says whether the window is there. The window
119-
// object is handed back because resolving this instance is what its `screen` will answer from.
120-
// The frame is reported even when refused, so a refusal names what it looked at.
117+
// Check existence before geometry: reading a missing window's frame records an XCTest failure,
118+
// even when the exception is caught. Keep the resolved instance for its screen lookup.
121119
static RunnerApplicationScreenFailure RunnerResolveUsableWindow(
122120
id application,
123121
id _Nullable *window,
@@ -130,6 +128,7 @@ static RunnerApplicationScreenFailure RunnerResolveUsableWindow(
130128
id candidate = [[application valueForKey:@"windows"] valueForKey:@"firstMatch"];
131129
NSNumber *present = [candidate valueForKey:@"exists"];
132130
resolved = [present isKindOfClass:NSNumber.class] && present.boolValue;
131+
if (!resolved) return;
133132
NSValue *frameValue = [candidate valueForKey:@"frame"];
134133
[frameValue getValue:&frame size:sizeof(frame)];
135134
readWindow = candidate;

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+XCTestEventBridgeTests.swift‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ extension RunnerTests {
202202
XCTAssertEqual(failure, .unresolvedWindow)
203203
XCTAssertNil(screen)
204204
XCTAssertEqual(displayID, 0)
205+
XCTAssertFalse(window.resolved, "a missing window's frame lookup records an XCTest failure")
205206
}
206207
/// The sole-screen rule's decision, at the seam the production probe feeds: the values the
207208
/// AXRuntime probe reads in, never a device list. The windowed/unknown rows below fail without

‎packages/capture-kit/src/ios-ax-tree.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ function readIosNodeIdentifier(node: IosTreeNode): string | undefined {
119119
* The node's screen-space rect, or undefined when the provider omitted a complete one. A component that
120120
* is not a finite number (an AX sentinel such as an infinite origin) makes the frame unusable.
121121
*/
122-
export function readIosNodeRect(node: IosTreeNode): RawSnapshotNode['rect'] {
122+
function readIosNodeRect(node: IosTreeNode): RawSnapshotNode['rect'] {
123123
const rect = node.rect ?? node.frame;
124124
if (
125125
!rect ||
@@ -137,7 +137,7 @@ function isFiniteNumber(value: unknown): value is number {
137137
return typeof value === 'number' && Number.isFinite(value);
138138
}
139139

140-
export function readIosNodeChildren(node: IosTreeNode): IosTreeNode[] {
140+
function readIosNodeChildren(node: IosTreeNode): IosTreeNode[] {
141141
return node.children ?? node.nodes ?? node.elements ?? [];
142142
}
143143

‎packages/host-kit/src/internal/request-cancel.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,3 +247,27 @@ export async function withRequestDeadline(
247247
clearRequestAbortRegistration(ownedRegistration);
248248
}
249249
}
250+
251+
/** Cancels the wait; the caller supplies any operation-specific stop and error handling. */
252+
export async function awaitWithSignal<T>(
253+
pending: Promise<T>,
254+
signal?: AbortSignal,
255+
onAbort: () => unknown = () => signal?.reason,
256+
): Promise<T> {
257+
if (!signal) return await pending;
258+
return await new Promise<T>((resolve, reject) => {
259+
const aborted = () => reject(onAbort());
260+
signal.addEventListener('abort', aborted, { once: true });
261+
if (signal.aborted) aborted();
262+
void pending.then(
263+
(value) => {
264+
signal.removeEventListener('abort', aborted);
265+
resolve(value);
266+
},
267+
(error: unknown) => {
268+
signal.removeEventListener('abort', aborted);
269+
reject(error);
270+
},
271+
);
272+
});
273+
}

‎packages/host-kit/src/request.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export {
2+
awaitWithSignal,
23
cancelAllRequests,
34
clearRequestAbortRegistration,
45
clearRequestCanceled,

‎packages/platform-apple/src/__tests__/fake-apple-tool.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { DeviceInfo } from '@agent-device/kernel/device';
22
import { AppError } from '@agent-device/kernel/errors';
33
import type { AppleToolProvider } from '../core/tool-provider.ts';
4-
import { withAppleToolProvider } from '../core/tool-provider.ts';
4+
import { withAppleToolProvider, createLocalAppleToolProvider } from '../core/tool-provider.ts';
55
import { execFailureDetails, type ExecResult } from '@agent-device/host-kit/command';
66
import { IOS_DEVICE } from './device-fixtures.ts';
77

@@ -38,7 +38,7 @@ export async function withFakeAppleTool<T>(
3838
return result;
3939
};
4040

41-
const provider: AppleToolProvider = {
41+
const provider = createLocalAppleToolProvider({
4242
...options.provider,
4343
whichCommand: options.provider?.whichCommand ?? (async () => true),
4444
runCommand: async (cmd, args, execOptions) =>
@@ -51,7 +51,7 @@ export async function withFakeAppleTool<T>(
5151
run: async (args, execOptions) =>
5252
await respond(['devicectl', ...args], 'xcrun', execOptions?.allowFailure),
5353
},
54-
};
54+
});
5555

5656
return await withAppleToolProvider(provider, async () => await run({ calls, device }));
5757
}

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

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@ import { beforeEach, test, vi } from 'vitest';
33

44
const { mockRunSimctl } = vi.hoisted(() => ({ mockRunSimctl: vi.fn() }));
55

6-
vi.mock('../simctl.ts', async (importOriginal) => ({
7-
...(await importOriginal<typeof import('../simctl.ts')>()),
8-
runSimctlForDevice: mockRunSimctl,
6+
vi.mock('@agent-device/host-kit/command', async (importOriginal) => ({
7+
...(await importOriginal<typeof import('@agent-device/host-kit/command')>()),
8+
runCmd: async (cmd: string, args: string[], options: unknown) => {
9+
assert.equal(cmd, 'xcrun');
10+
assert.equal(args[0], 'simctl');
11+
return { exitCode: 0, stderr: '', ...(await mockRunSimctl(args.slice(1), options)) };
12+
},
913
}));
1014

1115
import {
@@ -127,7 +131,7 @@ test('findIosSimulatorInstalledApp does not probe a stopped simulator', async ()
127131
});
128132

129133
function mockLaunchctlAndListapps(runningBundleIds: string[]): void {
130-
mockRunSimctl.mockImplementation(async (_device: DeviceInfo, args: string[]) => {
134+
mockRunSimctl.mockImplementation(async (args: string[]) => {
131135
if (args[0] === 'spawn') {
132136
const lines = runningBundleIds.map(
133137
(bundleId, index) => `${1000 + index}\t0\tUIKitApplication:${bundleId}[abcd][rb-legacy]`,
@@ -173,7 +177,7 @@ test('detectSoleRunningIosSimulatorApp returns undefined when nothing is running
173177
});
174178

175179
test('detectSoleRunningIosSimulatorApp treats a failed probe as inconclusive', async () => {
176-
mockRunSimctl.mockImplementation(async (_device: DeviceInfo, args: string[]) => {
180+
mockRunSimctl.mockImplementation(async (args: string[]) => {
177181
if (args[0] === 'spawn') return { exitCode: 1, stdout: '' };
178182
return {
179183
stdout: JSON.stringify({ 'com.apple.Preferences': { CFBundleDisplayName: 'Settings' } }),
@@ -184,7 +188,7 @@ test('detectSoleRunningIosSimulatorApp treats a failed probe as inconclusive', a
184188
});
185189

186190
test('detectSoleRunningIosSimulatorApp catches a rejecting launchctl probe (timeout/spawn failure)', async () => {
187-
mockRunSimctl.mockImplementation(async (_device: DeviceInfo, args: string[]) => {
191+
mockRunSimctl.mockImplementation(async (args: string[]) => {
188192
if (args[0] === 'spawn') throw new Error('xcrun timed out after 3000ms');
189193
return {
190194
stdout: JSON.stringify({ 'com.apple.Preferences': { CFBundleDisplayName: 'Settings' } }),
@@ -195,7 +199,7 @@ test('detectSoleRunningIosSimulatorApp catches a rejecting launchctl probe (time
195199
});
196200

197201
test('detectSoleRunningIosSimulatorApp catches a rejecting listapps probe (timeout/spawn failure)', async () => {
198-
mockRunSimctl.mockImplementation(async (_device: DeviceInfo, args: string[]) => {
202+
mockRunSimctl.mockImplementation(async (args: string[]) => {
199203
if (args[0] === 'spawn') {
200204
return {
201205
exitCode: 0,
@@ -214,9 +218,9 @@ test('detectSoleRunningIosSimulatorApp bounds the listapps probe with a timeout'
214218

215219
await detectSoleRunningIosSimulatorApp(bootedSimulator);
216220

217-
const listappsCall = mockRunSimctl.mock.calls.find(([, args]) => args[0] === 'listapps');
218-
assert.equal(typeof listappsCall?.[2]?.timeoutMs, 'number');
219-
assert.ok((listappsCall?.[2]?.timeoutMs ?? 0) > 0);
221+
const listappsCall = mockRunSimctl.mock.calls.find(([args]) => args[0] === 'listapps');
222+
assert.equal(typeof listappsCall?.[1]?.timeoutMs, 'number');
223+
assert.ok((listappsCall?.[1]?.timeoutMs ?? 0) > 0);
220224
});
221225

222226
test('detectSoleRunningIosSimulatorApp does not probe a stopped simulator', async () => {

‎packages/platform-apple/src/core/__tests__/display-inventory.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { beforeEach, describe, test, vi } from 'vitest';
22
import assert from 'node:assert/strict';
33

4-
vi.mock('../simctl.ts', async (importOriginal) => {
5-
const actual = await importOriginal<typeof import('../simctl.ts')>();
4+
vi.mock('../simctl-execution.ts', async (importOriginal) => {
5+
const actual = await importOriginal<typeof import('../simctl-execution.ts')>();
66
return {
77
...actual,
88
runSimctlForDevice: vi.fn(async () => ({ exitCode: 0, stdout: '', stderr: '' })),
@@ -49,7 +49,7 @@ import {
4949
import { AppError } from '@agent-device/kernel/errors';
5050
import { runXcrun } from '../tool-provider.ts';
5151
import { readHostTextFile } from '@agent-device/host-kit/host-file';
52-
import { runSimctlForDevice } from '../simctl.ts';
52+
import { runSimctlForDevice } from '../simctl-execution.ts';
5353
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
5454
import { ensureFoldHelperBinary } from '../../foldable/fold-helper-cache.ts';
5555
import { IOS_TEST_SIMULATOR } from './apple-core-stub-helpers.ts';

‎packages/platform-apple/src/core/__tests__/simctl.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1+
import { readSimctlContainerPath } from '../simctl-output.ts';
12
import { test } from 'vitest';
23
import assert from 'node:assert/strict';
34
import {
45
buildSimctlArgsForAddress,
56
buildSimctlArgsForDevice,
6-
readSimctlContainerPath,
77
readSimctlDevicesByRuntime,
88
readSimctlDeviceState,
99
scopeSimctlArgsForDevice,

‎packages/platform-apple/src/core/app-device-io.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { isMacOs, isTvOsDevice, type DeviceInfo } from '@agent-device/kernel/dev
22
import { requireExecSuccess } from '@agent-device/host-kit/command';
33
import { ensureBootedSimulator, requireSimulatorDevice } from './simulator.ts';
44
import { readMacOsClipboardText, writeMacOsClipboardText } from '../os/macos/apps.ts';
5-
import { runSimctlForDevice } from './simctl.ts';
5+
import { runSimctlForDevice } from './simctl-execution.ts';
66
import { runAppleRunnerCommand } from './runner-client.ts';
77
import type { AppleRunnerCommandOptions } from '@agent-device/apple-runner';
88

0 commit comments

Comments
 (0)