Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
186 changes: 186 additions & 0 deletions packages/platform-apple/src/runner/__tests__/runner-exchange.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import assert from 'node:assert/strict';
import type { ExecResult } from '@agent-device/host-kit/command';
import { afterEach, test } from 'vitest';
import { executeRunnerExchange } from '../runner-exchange.ts';
import { RunnerCommandAccounting, type RunnerSession } from '../runner-session-types.ts';
import { IOS_SIMULATOR } from './device-fixtures.ts';
import { startFakeRunnerServer, type FakeRunnerServer } from './fake-runner-server.ts';

let server: FakeRunnerServer | undefined;

afterEach(async () => {
await server?.close();
server = undefined;
});

function sessionFor(port: number): RunnerSession {
return {
sessionId: `exchange:${port}`,
device: IOS_SIMULATOR,
deviceId: IOS_SIMULATOR.id,
port,
xctestrunPath: '/tmp/fake.xctestrun',
jsonPath: '/tmp/fake.json',
testPromise: new Promise<ExecResult>(() => {}),
child: { pid: process.pid, exitCode: null },
state: 'ready',
commandCharges: new RunnerCommandAccounting(),
};
}

test('the exchange preflights a mutation and settles only its answer', async () => {
server = await startFakeRunnerServer({
uptime: [{ kind: 'ok', data: { uptimeMs: 5 } }],
tap: [{ kind: 'ok', data: { tapped: true } }],
});
const session = sessionFor(server.port);
const invalidations: string[] = [];

const result = await executeRunnerExchange(
IOS_SIMULATOR,
session,
{ command: 'tap', x: 10, y: 10, appBundleId: 'com.example.app' },
undefined,
10_000,
async (reason) => {
invalidations.push(reason);
},
);

assert.deepEqual(result, { tapped: true });
assert.deepEqual(
server.requests.map(({ command }) => command),
['uptime', 'tap'],
);
assert.equal(session.commandCharges.hasOutstandingCharges, false);
assert.equal(session.lastHealthyMutation?.appBundleId, 'com.example.app');
assert.deepEqual(invalidations, []);
});

test('the readiness probe preserves its main-thread busy report when the command omits it', async () => {
server = await startFakeRunnerServer({
uptime: [{ kind: 'ok', data: { runnerMainThreadBusy: true } }],
tap: [{ kind: 'ok', data: { tapped: true } }],
});
const session = sessionFor(server.port);

await executeRunnerExchange(
IOS_SIMULATOR,
session,
{ command: 'tap', x: 10, y: 10, appBundleId: 'com.example.app' },
undefined,
10_000,
async () => {},
);

assert.equal(session.runnerMainThreadBusy, true);
});

test.each(['activate', 'terminate', 'targetReset'] as const)(
'a starting runner sends exempt %s without a readiness preflight',
async (command) => {
server = await startFakeRunnerServer([{ kind: 'ok', data: {} }]);
const session = sessionFor(server.port);
session.state = 'starting';

await executeRunnerExchange(
IOS_SIMULATOR,
session,
{ command, appBundleId: 'com.example.app' },
undefined,
10_000,
async () => {},
);

assert.deepEqual(
server.requests.map((request) => request.command),
[command],
);
},
);

test('the exchange awaits owner invalidation before returning a fatal answer', async () => {
server = await startFakeRunnerServer({
snapshot: [{ kind: 'ok', data: { runnerFatal: true, runnerFatalReason: 'ax_failed' } }],
});
const session = sessionFor(server.port);
session.lastHealthyMutation = { atMs: Date.now(), appBundleId: 'com.example.app' };
let signalInvalidationStarted!: () => void;
const invalidationStarted = new Promise<void>((resolve) => {
signalInvalidationStarted = resolve;
});
let releaseInvalidation!: () => void;
const invalidationGate = new Promise<void>((resolve) => {
releaseInvalidation = resolve;
});
let settled = false;

const exchange = executeRunnerExchange(
IOS_SIMULATOR,
session,
{ command: 'snapshot', appBundleId: 'com.example.app' },
undefined,
10_000,
async (reason) => {
assert.equal(reason, 'ax_failed');
signalInvalidationStarted();
await invalidationGate;
},
).finally(() => {
settled = true;
});

try {
await invalidationStarted;
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(settled, false);
} finally {
releaseInvalidation();
}
const result = await exchange;

assert.equal(result.runnerFatal, true);
assert.equal(session.lastHealthyMutation, undefined);
assert.equal(session.commandCharges.hasOutstandingCharges, false);
});

test('the exchange awaits owner invalidation before throwing a fatal runner error', async () => {
server = await startFakeRunnerServer({
snapshot: [{ kind: 'runnerError', code: 'RUNNER_WEDGED', message: 'runner wedged' }],
});
const session = sessionFor(server.port);
let signalInvalidationStarted!: () => void;
const invalidationStarted = new Promise<void>((resolve) => {
signalInvalidationStarted = resolve;
});
let releaseInvalidation!: () => void;
const invalidationGate = new Promise<void>((resolve) => {
releaseInvalidation = resolve;
});
let settled = false;

const exchange = executeRunnerExchange(
IOS_SIMULATOR,
session,
{ command: 'snapshot', appBundleId: 'com.example.app' },
undefined,
10_000,
async (reason) => {
assert.equal(reason, 'runner_main_thread_wedged');
signalInvalidationStarted();
await invalidationGate;
},
).finally(() => {
settled = true;
});
void exchange.catch(() => {});

try {
await invalidationStarted;
await new Promise<void>((resolve) => setImmediate(resolve));
assert.equal(settled, false);
} finally {
releaseInvalidation();
}
await assert.rejects(exchange);
});
34 changes: 24 additions & 10 deletions packages/platform-apple/src/runner/runner-exchange.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { AppError } from '@agent-device/kernel/errors';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { Deadline, emitDiagnostic, withDiagnosticTimer } from './host.ts';
import { waitForRunner, RUNNER_STARTUP_TIMEOUT_MS } from './runner-startup-transport.ts';
import {
waitForRunner,
RUNNER_STARTUP_TIMEOUT_MS,
type RunnerConnectionSession,
} from './runner-startup-transport.ts';
import { sendRunnerCommandOnce } from './runner-transport.ts';
import {
buildRunnerResponseError,
Expand Down Expand Up @@ -29,6 +33,12 @@ import {
} from './runner-failure-diagnostics.ts';
import { advanceRunnerSessionState, type RunnerSession } from './runner-session-types.ts';

type RunnerExchangeSession = RunnerConnectionSession &
Pick<
RunnerSession,
'port' | 'commandCharges' | 'lastHealthyMutation' | 'runnerMainThreadBusy' | 'launchDeadline'
>;

const RUNNER_READY_PREFLIGHT_TIMEOUT_MS = 1_000;
const RUNNER_PREFLIGHT_SKIP_FRESHNESS_MS = 5_000;

Expand Down Expand Up @@ -63,7 +73,7 @@ type RunnerReadinessPreflightDecision =
*/
export async function executeRunnerExchange(
device: DeviceInfo,
session: RunnerSession,
session: RunnerExchangeSession,
command: RunnerCommand,
logPath: string | undefined,
timeoutMs: number,
Expand Down Expand Up @@ -137,7 +147,7 @@ export async function executeRunnerExchange(
* runner's occupancy report, and applies what the payload says about the session.
*/
async function settleRunnerAnsweredExchange(
session: RunnerSession,
session: RunnerExchangeSession,
runnerCommand: RunnerCommand,
data: Record<string, unknown>,
invalidateFatalSession: (reason: string) => Promise<void>,
Expand Down Expand Up @@ -169,7 +179,7 @@ async function settleRunnerAnsweredExchange(
* runner answered it.
*/
function recordUnansweredRunnerExchange(
session: RunnerSession,
session: RunnerExchangeSession,
runnerCommand: RunnerCommand,
error: unknown,
): boolean {
Expand Down Expand Up @@ -199,7 +209,7 @@ function readRunnerMainThreadBusy(data: Record<string, unknown>): boolean | unde

function markSkippedPreflightTransportError(
error: unknown,
session: RunnerSession,
session: RunnerExchangeSession,
preflightDecision: RunnerReadinessPreflightDecision,
): unknown {
if (
Expand All @@ -218,7 +228,7 @@ function markSkippedPreflightTransportError(

async function sendRunnerCommandAfterPreflight(params: {
device: DeviceInfo;
session: RunnerSession;
session: RunnerExchangeSession;
runnerCommand: RunnerCommand;
logPath: string | undefined;
deadline: Deadline;
Expand Down Expand Up @@ -282,7 +292,7 @@ async function sendRunnerCommandAfterPreflight(params: {

async function runRunnerReadinessPreflight(params: {
device: DeviceInfo;
session: RunnerSession;
session: RunnerExchangeSession;
runnerCommand: RunnerCommand;
logAttempt: RunnerLogAttempt | undefined;
deadline: Deadline;
Expand Down Expand Up @@ -317,15 +327,19 @@ async function runRunnerReadinessPreflight(params: {
timeoutMs: readinessTimeoutMs,
},
);
await parseRunnerResponse(readinessResponse, session, logAttempt);
const readinessData = await parseRunnerResponse(readinessResponse, session, logAttempt);
const stampedMainThreadBusy = readRunnerMainThreadBusy(readinessData);
if (stampedMainThreadBusy !== undefined) {
session.runnerMainThreadBusy = stampedMainThreadBusy;
}
} catch (error) {
throw markRunnerReadinessPreflightError(error);
}
}

function emitRunnerReadinessPreflightSkipped(
runnerCommand: RunnerCommand,
session: RunnerSession,
session: RunnerExchangeSession,
decision: Extract<RunnerReadinessPreflightDecision, { action: 'skip' }>,
): void {
emitDiagnostic({
Expand Down Expand Up @@ -392,7 +406,7 @@ function resolveRunnerFatalReason(data: Record<string, unknown>): string | undef
}

function resolveRunnerReadinessPreflightDecision(
session: RunnerSession,
session: RunnerExchangeSession,
command: RunnerCommand,
): RunnerReadinessPreflightDecision {
const readOnlyCommand = isReadOnlyRunnerCommand(command);
Expand Down
22 changes: 17 additions & 5 deletions packages/platform-apple/src/runner/runner-startup-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,18 @@ import {
} from './runner-error-classification.ts';
import type { RunnerCommand } from './runner-contract.ts';
import type { RunnerSession } from './runner-session-types.ts';

export type RunnerConnectionSession = Pick<
RunnerSession,
| 'startupRetryWake'
| 'child'
| 'startupDeviceStates'
| 'state'
| 'testPromise'
| 'readLogTail'
| 'device'
| 'runnerLogPath'
>;
import {
runnerSimulatorSetFailureDetails,
simulatorSetDestinationNotFoundMessage,
Expand All @@ -53,7 +65,7 @@ export async function waitForRunner(
command: RunnerCommand,
logPath?: string,
timeoutMs: number = RUNNER_STARTUP_TIMEOUT_MS,
session?: RunnerSession,
session?: RunnerConnectionSession,
signal?: AbortSignal,
): Promise<Response> {
const deadline = Deadline.fromTimeoutMs(timeoutMs);
Expand Down Expand Up @@ -148,7 +160,7 @@ async function attemptRunnerConnection(params: {
command: RunnerCommand;
timeoutMs: number;
logPath?: string;
session?: RunnerSession;
session?: RunnerConnectionSession;
route: RunnerCommandRoute;
resolveRoute: RunnerRouteResolver;
markUsbmuxUnattached: () => void;
Expand All @@ -172,7 +184,7 @@ async function ensureRunnerAttemptCanStart(params: {
port: number;
timeoutMs: number;
logPath?: string;
session?: RunnerSession;
session?: RunnerConnectionSession;
attemptDeadline?: Deadline;
}): Promise<void> {
if (params.attemptDeadline?.isExpired()) {
Expand Down Expand Up @@ -246,7 +258,7 @@ async function tryReadySimulatorEndpoint(params: {
device: DeviceInfo;
port: number;
command: RunnerCommand;
session?: RunnerSession;
session?: RunnerConnectionSession;
signal?: AbortSignal;
attemptDeadline?: Deadline;
setLastError: (error: unknown) => void;
Expand Down Expand Up @@ -516,7 +528,7 @@ function buildRunnerConnectError(params: {
}

export async function buildRunnerEarlyExitError(params: {
session: RunnerSession;
session: RunnerConnectionSession;
port: number;
logPath?: string;
}): Promise<AppError> {
Expand Down
Loading