Skip to content

Commit 4780b46

Browse files
committed
fix(ios): route the display probe through the owning devicectl helper
`queryAppleDisplayInventory` copied the devicectl JSON protocol — temp path, `--json-output`, `runXcrun` with allowFailure, payload read, cleanup — and had already dropped the hint mapping the owning helper applies. Export `runIosDevicectlJsonRequest` as that single protocol implementation with a timeout and signal, and let the throwing command and the probe both build on it. Classify the probe by what actually happened: an exec kill stays a timeout via `isCommandTimeoutError`, `unreadable-json` now means devicectl answered with a payload that did not parse, and only those two reasons claim the toolchain lacks the subcommand. The old mapping labelled an AppError — i.e. the timeout — as an unreadable payload, which is inverted. Drop the panel labels nothing read. `outer`/`inner` and the derived pose had no consumer outside the module and its tests, while `primary` plus panel power is what every decision already used; the geometry conflict still reports `apple_display_primary_geometry_conflict`. Also stub `resolveCaptureDisplay` in the screenshot suite so it stops paying for a real CoreDevice probe, assert the caller signal actually reaches `runXcrun` instead of asserting it was never aborted, and drop the dynamic import of a module the facade already imports statically.
1 parent 83308f7 commit 4780b46

7 files changed

Lines changed: 300 additions & 200 deletions

File tree

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@ vi.mock('@agent-device/host-kit/host-file', async (importOriginal) => {
1919

2020
import { buildAppleSimulatorRecordVideoArgs } from '../simctl-facade.ts';
2121
import { readHostTextFile } from '@agent-device/host-kit/host-file';
22+
import { runXcrun } from '../core/tool-provider.ts';
2223
import { IOS_SIMULATOR } from './device-fixtures.ts';
2324

2425
const mockReadHostTextFile = vi.mocked(readHostTextFile);
26+
const mockRunXcrun = vi.mocked(runXcrun);
2527

2628
/** Measured `devicectl device info displays` shape for a closed iPhone Duo. */
2729
const IPHONE_DUO_CLOSED = JSON.stringify({
@@ -71,6 +73,7 @@ describe('buildAppleSimulatorRecordVideoArgs', () => {
7173
beforeEach(() => {
7274
mockReadHostTextFile.mockReset();
7375
mockReadHostTextFile.mockResolvedValue('');
76+
mockRunXcrun.mockClear();
7477
});
7578

7679
test('names the lit panel instead of recording the dark default', async () => {
@@ -102,6 +105,8 @@ describe('buildAppleSimulatorRecordVideoArgs', () => {
102105
await buildAppleSimulatorRecordVideoArgs(IOS_SIMULATOR, '/tmp/rec.mp4', {
103106
signal: controller.signal,
104107
});
105-
expect(controller.signal.aborted).toBe(false);
108+
const probeCall = mockRunXcrun.mock.calls.find(([args]) => args[0] === 'devicectl');
109+
expect(probeCall).toBeDefined();
110+
expect(probeCall![1]?.signal).toBe(controller.signal);
106111
});
107112
});

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

Lines changed: 93 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,38 @@
1-
import { test } from 'vitest';
1+
import { test, vi } from 'vitest';
22
import assert from 'node:assert/strict';
3+
4+
import { AppError } from '@agent-device/kernel/errors';
5+
import { isCommandTimeoutError } from '@agent-device/host-kit/command';
6+
7+
vi.mock('../tool-provider.ts', async (importOriginal) => {
8+
const actual = await importOriginal<typeof import('../tool-provider.ts')>();
9+
return {
10+
...actual,
11+
runXcrun: vi.fn(async () => ({ exitCode: 0, stdout: '', stderr: '' })),
12+
};
13+
});
14+
vi.mock('@agent-device/host-kit/host-file', async (importOriginal) => {
15+
const actual = await importOriginal<typeof import('@agent-device/host-kit/host-file')>();
16+
return {
17+
...actual,
18+
hostTemporaryDirectory: () => '/tmp',
19+
readHostTextFile: vi.fn(async () => ''),
20+
unlinkHostFile: vi.fn(async () => {}),
21+
};
22+
});
23+
24+
import { readHostTextFile, unlinkHostFile } from '@agent-device/host-kit/host-file';
325
import {
426
parseIosDeviceAppsPayload,
527
parseIosDeviceProcessesPayload,
628
resolveIosDevicectlHint,
29+
runIosDevicectlJsonRequest,
730
} from '../devicectl.ts';
31+
import { runXcrun } from '../tool-provider.ts';
32+
33+
const mockRunXcrun = vi.mocked(runXcrun);
34+
const mockReadHostTextFile = vi.mocked(readHostTextFile);
35+
const mockUnlinkHostFile = vi.mocked(unlinkHostFile);
836

937
test('parseIosDeviceAppsPayload maps devicectl app entries', () => {
1038
const apps = parseIosDeviceAppsPayload({
@@ -105,3 +133,67 @@ test('resolveIosDevicectlHint explains how to pair an unpaired device', () => {
105133
test('resolveIosDevicectlHint still returns null for an unrecognised failure', () => {
106134
assert.equal(resolveIosDevicectlHint('', 'some unrelated devicectl explosion'), null);
107135
});
136+
137+
test('runIosDevicectlJsonRequest reports a non-zero exit as a typed failure instead of throwing', async () => {
138+
mockRunXcrun.mockResolvedValue({ exitCode: 2, stdout: '', stderr: 'no such option --displays' });
139+
mockReadHostTextFile.mockResolvedValue('');
140+
mockUnlinkHostFile.mockClear();
141+
142+
const outcome = await runIosDevicectlJsonRequest({
143+
jsonPrefix: 'agent-device-test',
144+
args: ['devicectl', 'device', 'info', 'displays', '--device', 'UDID-1'],
145+
});
146+
147+
assert.equal(outcome.ok, false);
148+
assert.equal(outcome.reason, 'command-failed');
149+
assert.equal(outcome.result?.stderr, 'no such option --displays');
150+
assert.equal(mockUnlinkHostFile.mock.calls.length, 1);
151+
});
152+
153+
test('runIosDevicectlJsonRequest separates a malformed payload from a failed command', async () => {
154+
mockRunXcrun.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' });
155+
mockReadHostTextFile.mockResolvedValue('{"result": ');
156+
157+
const outcome = await runIosDevicectlJsonRequest({
158+
jsonPrefix: 'agent-device-test',
159+
args: ['devicectl', 'device', 'info', 'displays', '--device', 'UDID-1'],
160+
});
161+
162+
assert.equal(outcome.ok, false);
163+
assert.equal(outcome.reason, 'unreadable-json');
164+
assert.match(String(outcome.cause), /JSON|Unexpected/);
165+
});
166+
167+
test('runIosDevicectlJsonRequest lets an exec timeout stay a timeout', async () => {
168+
mockRunXcrun.mockRejectedValue(
169+
new AppError('COMMAND_FAILED', 'xcrun timed out after 5000ms', {
170+
cmd: 'xcrun',
171+
args: ['devicectl'],
172+
timeoutMs: 5_000,
173+
}),
174+
);
175+
176+
await assert.rejects(
177+
runIosDevicectlJsonRequest({
178+
jsonPrefix: 'agent-device-test',
179+
args: ['devicectl', 'device', 'info', 'displays', '--device', 'UDID-1'],
180+
timeoutMs: 5_000,
181+
}),
182+
(error: unknown) => isCommandTimeoutError(error),
183+
);
184+
mockRunXcrun.mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' });
185+
});
186+
187+
test('runIosDevicectlJsonRequest still tolerates a recognized failure payload', async () => {
188+
mockRunXcrun.mockResolvedValue({ exitCode: 1, stdout: '', stderr: '' });
189+
mockReadHostTextFile.mockResolvedValue('{"error":{"code":7}}');
190+
191+
const outcome = await runIosDevicectlJsonRequest({
192+
jsonPrefix: 'agent-device-test',
193+
args: ['devicectl', 'device', 'process', 'terminate', '--device', 'UDID-1'],
194+
tolerateFailurePayload: (payload) =>
195+
(payload as { error?: { code?: number } }).error?.code === 7,
196+
});
197+
198+
assert.equal(outcome.ok, true);
199+
});

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

Lines changed: 58 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ vi.mock('../tool-provider.ts', async (importOriginal) => {
1515
runXcrun: vi.fn(async () => ({ exitCode: 0, stdout: '', stderr: '' })),
1616
};
1717
});
18+
vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => {
19+
const actual = await importOriginal<typeof import('@agent-device/host-kit/diagnostics')>();
20+
return { ...actual, emitDiagnostic: vi.fn() };
21+
});
1822
vi.mock('@agent-device/host-kit/host-file', async (importOriginal) => {
1923
const actual = await importOriginal<typeof import('@agent-device/host-kit/host-file')>();
2024
return {
@@ -27,9 +31,7 @@ vi.mock('@agent-device/host-kit/host-file', async (importOriginal) => {
2731

2832
import {
2933
appleSimulatorDisplayArgvFragment,
30-
assignDisplayRoles,
3134
buildInventory,
32-
deriveDisplayPose,
3335
parseCoreDeviceDisplays,
3436
readPanelPower,
3537
resolveAppleCaptureDisplay,
@@ -39,14 +41,17 @@ import {
3941
captureSimulatorScreenshotWithFallback,
4042
captureSimulatorScreenshotWithRetry,
4143
} from '../screenshot.ts';
44+
import { AppError } from '@agent-device/kernel/errors';
4245
import { runXcrun } from '../tool-provider.ts';
4346
import { readHostTextFile } from '@agent-device/host-kit/host-file';
4447
import { runSimctlForDevice } from '../simctl.ts';
48+
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
4549
import { IOS_TEST_SIMULATOR } from './apple-core-stub-helpers.ts';
4650

4751
const mockRunSimctlForDevice = vi.mocked(runSimctlForDevice);
4852
const mockRunXcrun = vi.mocked(runXcrun);
4953
const mockReadHostTextFile = vi.mocked(readHostTextFile);
54+
const mockEmitDiagnostic = vi.mocked(emitDiagnostic);
5055

5156
/** Verbatim `devicectl device info displays` shape for a closed iPhone Duo. */
5257
const IPHONE_DUO_CLOSED = {
@@ -210,17 +215,16 @@ describe('parseCoreDeviceDisplays', () => {
210215
});
211216

212217
describe('buildInventory', () => {
213-
test('names the Duo panels outer/inner and reports the closed pose', () => {
218+
test('names the lit primary panel of a closed Duo without falling through to simctl', () => {
214219
const inventory = buildInventory(parseCoreDeviceDisplays(IPHONE_DUO_CLOSED));
215220
assert.equal(inventory.unresolved, false);
216221
assert.equal(inventory.multiScreen, true);
217222
assert.equal(inventory.ambiguous, false);
218-
assert.equal(inventory.pose, 'closed');
219223
assert.deepEqual(
220-
inventory.displays.map((display) => [display.name, display.role]),
224+
inventory.displays.map((display) => [display.name, display.primary, display.power]),
221225
[
222-
['LCD', 'outer'],
223-
['LCD-1', 'inner'],
226+
['LCD', true, 'lit'],
227+
['LCD-1', false, 'dark'],
224228
],
225229
);
226230
assert.equal(inventory.activeDisplay?.name, 'LCD');
@@ -230,16 +234,14 @@ describe('buildInventory', () => {
230234
const inventory = buildInventory(parseCoreDeviceDisplays(duoPanelsWithoutActiveKey()));
231235
assert.equal(inventory.multiScreen, true);
232236
assert.equal(inventory.ambiguous, false);
233-
assert.equal(inventory.pose, 'closed');
234237
assert.equal(inventory.activeDisplay?.name, 'LCD');
235238
});
236239

237-
test('reports the fully-open pose when the inner panel is lit', () => {
240+
test('captures the inner panel when it is the lit one', () => {
238241
const inventory = buildInventory([
239242
{ ...outerPanel, power: 'dark' },
240243
{ ...innerPanel, power: 'lit' },
241244
]);
242-
assert.equal(inventory.pose, 'fully-open');
243245
assert.equal(inventory.ambiguous, false);
244246
assert.equal(inventory.activeDisplay?.name, 'LCD-1');
245247
});
@@ -259,53 +261,40 @@ describe('buildInventory', () => {
259261
const inventory = buildInventory(panels);
260262
assert.equal(inventory.multiScreen, true);
261263
assert.equal(inventory.ambiguous, true);
262-
assert.equal(inventory.pose, 'unknown');
263264
assert.equal(inventory.activeDisplay?.name, 'LCD');
264265
}
265266
});
266267

267-
test('refuses to invent roles or a pose when no panel reports primary', () => {
268+
test('names a capture even when no panel reports primary', () => {
268269
const inventory = buildInventory([
269270
{ ...outerPanel, primary: false },
270271
{ ...innerPanel, power: 'lit', primary: false },
271272
]);
272273
assert.equal(inventory.multiScreen, true);
273274
assert.equal(inventory.ambiguous, true);
274-
assert.equal(inventory.pose, 'unknown');
275-
assert.deepEqual(
276-
inventory.displays.map((display) => display.role),
277-
[undefined, undefined],
278-
);
279275
// A capture is still named: never the implicit black-producing default.
280276
assert.ok(inventory.activeDisplay);
281277
});
282278

283-
test('leaves a third panel unroled rather than labelling every extra panel inner', () => {
279+
test('keeps choosing the lit panel when a third panel is present', () => {
284280
const inventory = buildInventory([
285-
outerPanel,
286-
innerPanel,
281+
{ ...outerPanel, power: 'dark' },
282+
{ ...innerPanel, power: 'lit' },
287283
displayWith({ name: 'LCD-2', displayId: 5, power: 'dark', primary: false }),
288284
]);
289-
assert.deepEqual(
290-
inventory.displays.map((display) => [display.name, display.role]),
291-
[
292-
['LCD', 'outer'],
293-
['LCD-1', 'inner'],
294-
['LCD-2', undefined],
295-
],
296-
);
285+
assert.equal(inventory.multiScreen, true);
286+
assert.equal(inventory.activeDisplay?.name, 'LCD-1');
287+
assert.equal(inventory.displays.length, 3);
297288
});
298289

299-
test('keeps a single-panel device single-screen with no pose', () => {
290+
test('keeps a single-panel device single-screen', () => {
300291
const inventory = buildInventory(parseCoreDeviceDisplays(IPHONE_17_NO_ACTIVE_KEY));
301292
assert.equal(inventory.multiScreen, false);
302293
assert.equal(inventory.ambiguous, false);
303-
assert.equal(inventory.pose, undefined);
304294
assert.equal(inventory.activeDisplay, undefined);
305-
assert.equal(inventory.displays[0]!.role, undefined);
306295
});
307296

308-
test('treats an attached external display as neither a foldable panel nor a pose signal', () => {
297+
test('treats an attached external display as neither a foldable panel nor a capture target', () => {
309298
const inventory = buildInventory([
310299
outerPanel,
311300
displayWith({
@@ -319,38 +308,17 @@ describe('buildInventory', () => {
319308
}),
320309
]);
321310
assert.equal(inventory.multiScreen, false);
322-
assert.equal(inventory.pose, undefined);
323311
// The external display is carried through for reporting but never selected.
324312
assert.equal(inventory.activeDisplay, undefined);
325313
});
326314
});
327315

328-
describe('deriveDisplayPose', () => {
329-
test('refuses to name a pose when panel power is ambiguous', () => {
330-
assert.equal(deriveDisplayPose([outerPanel, { ...innerPanel, power: 'lit' }]), 'unknown');
331-
assert.equal(deriveDisplayPose([{ ...outerPanel, power: 'dark' }, innerPanel]), 'unknown');
332-
});
333-
});
334-
335-
describe('assignDisplayRoles', () => {
336-
test('leaves a single-panel device unroled', () => {
337-
const [only] = assignDisplayRoles([outerPanel]);
338-
assert.equal(only!.role, undefined);
339-
});
340-
341-
test('returns panels unroled when none is primary', () => {
342-
const roles = assignDisplayRoles([{ ...outerPanel, primary: false }, innerPanel]).map(
343-
(display) => display.role,
344-
);
345-
assert.deepEqual(roles, [undefined, undefined]);
346-
});
347-
});
348-
349316
describe('resolveAppleCaptureDisplay', () => {
350317
beforeEach(() => {
351318
mockRunXcrun.mockClear();
352319
mockReadHostTextFile.mockReset();
353320
mockReadHostTextFile.mockResolvedValue('');
321+
mockEmitDiagnostic.mockClear();
354322
});
355323

356324
test('returns the lit panel for a multi-panel device', async () => {
@@ -389,6 +357,42 @@ describe('resolveAppleCaptureDisplay', () => {
389357
assert.equal(await resolveAppleCaptureDisplay(IOS_TEST_SIMULATOR), undefined);
390358
});
391359

360+
function unresolvedReason(): string | undefined {
361+
const call = mockEmitDiagnostic.mock.calls.find(
362+
([diagnostic]) => diagnostic.phase === 'apple_display_inventory_unresolved',
363+
);
364+
return call?.[0].data?.reason as string | undefined;
365+
}
366+
367+
test('reports an exec timeout as a timeout, not as an unreadable payload', async () => {
368+
mockRunXcrun.mockRejectedValueOnce(
369+
new AppError('COMMAND_FAILED', 'xcrun timed out after 5000ms', {
370+
cmd: 'xcrun',
371+
args: ['devicectl'],
372+
timeoutMs: 5_000,
373+
}),
374+
);
375+
assert.equal(await resolveAppleCaptureDisplay(IOS_TEST_SIMULATOR), undefined);
376+
assert.equal(unresolvedReason(), 'probe-timed-out');
377+
});
378+
379+
test('blames the payload only when devicectl answered', async () => {
380+
mockRunXcrun.mockResolvedValueOnce({ exitCode: 0, stdout: '', stderr: '' });
381+
mockReadHostTextFile.mockResolvedValueOnce('{"result": ');
382+
assert.equal(await resolveAppleCaptureDisplay(IOS_TEST_SIMULATOR), undefined);
383+
assert.equal(unresolvedReason(), 'unreadable-json');
384+
});
385+
386+
test('blames the toolchain when devicectl refused the subcommand', async () => {
387+
mockRunXcrun.mockResolvedValueOnce({
388+
exitCode: 1,
389+
stdout: '',
390+
stderr: "ERROR: Unknown command 'displays'",
391+
});
392+
assert.equal(await resolveAppleCaptureDisplay(IOS_TEST_SIMULATOR), undefined);
393+
assert.equal(unresolvedReason(), 'command-failed');
394+
});
395+
392396
test('bounds the probe below the capture it precedes', async () => {
393397
mockReadHostTextFile.mockResolvedValue(JSON.stringify(IPHONE_17_NO_ACTIVE_KEY));
394398
await resolveAppleCaptureDisplay(IOS_TEST_SIMULATOR);

0 commit comments

Comments
 (0)