diff --git a/packages/apple-runner/src/__tests__/index-command-retry.test.ts b/packages/apple-runner/src/__tests__/index-command-retry.test.ts index 05b0a8ea76..5b7df765ae 100644 --- a/packages/apple-runner/src/__tests__/index-command-retry.test.ts +++ b/packages/apple-runner/src/__tests__/index-command-retry.test.ts @@ -50,7 +50,7 @@ vi.mock('../runner-xctestrun.ts', async () => { import { prepareIosRunner, runAppleRunnerCommand } from '../index.ts'; import { resetRunnerRecycleLedgerForTests } from '../runner-recycle-ledger.ts'; -import { RUNNER_REPLY_LOST_REASON } from '../runner-error-classification.ts'; +import { RUNNER_EXCHANGE_REASONS } from '../runner-error-classification.ts'; const requestCancellation = createTestRequestCancellation(); const { markRequestCanceled, clearRequestCanceled, isRequestCanceled } = requestCancellation; @@ -404,7 +404,7 @@ test('mutating commands keep invalidating when status recovery probe fails', asy () => runAppleRunnerCommand(IOS_SIMULATOR, { command: 'tap', x: 120, y: 240 }), (error: unknown) => { assert.ok(error instanceof AppError); - assert.equal(error.details?.reason, RUNNER_REPLY_LOST_REASON); + assert.equal(error.details?.reason, RUNNER_EXCHANGE_REASONS.replyLost.reason); assert.equal(error.details?.transportError, 'fetch failed'); return true; }, @@ -434,7 +434,7 @@ test('a mutation lost reply keeps the hint its transport error already carries', () => runAppleRunnerCommand(IOS_SIMULATOR, { command: 'tap', x: 120, y: 240 }), (error: unknown) => { assert.ok(error instanceof AppError); - assert.equal(error.details?.reason, RUNNER_REPLY_LOST_REASON); + assert.equal(error.details?.reason, RUNNER_EXCHANGE_REASONS.replyLost.reason); assert.equal(error.details?.hint, 'Unlock the device and retry.'); return true; }, @@ -920,7 +920,7 @@ test('sequence invalidates the session when the status probe fails', async () => }), (error: unknown) => { assert.ok(error instanceof AppError); - assert.equal(error.details?.reason, RUNNER_REPLY_LOST_REASON); + assert.equal(error.details?.reason, RUNNER_EXCHANGE_REASONS.replyLost.reason); assert.equal(error.details?.transportError, 'fetch failed'); return true; }, diff --git a/packages/apple-runner/src/__tests__/index-dispatch-disclosure.test.ts b/packages/apple-runner/src/__tests__/index-dispatch-disclosure.test.ts index c4cc29bae8..bec4a12a39 100644 --- a/packages/apple-runner/src/__tests__/index-dispatch-disclosure.test.ts +++ b/packages/apple-runner/src/__tests__/index-dispatch-disclosure.test.ts @@ -16,7 +16,7 @@ import type { RunnerCommand } from '../runner-contract.ts'; import { isRetryableRunnerError, isStructuredRunnerFailure, - RUNNER_REPLY_LOST_REASON, + RUNNER_EXCHANGE_REASONS, } from '../runner-error-classification.ts'; import { runApplePressSeries } from '../runner-sequence.ts'; import { executeRunnerCommandWithSession, type RunnerSession } from '../runner-session.ts'; @@ -249,7 +249,10 @@ for (const row of ROWS) { await assert.rejects(drive(), (error: unknown) => { assert.ok(error instanceof AppError); assert.equal(error.details?.dispatched, row.dispatched); - assert.equal(error.details?.reason === RUNNER_REPLY_LOST_REASON, REPLY_LOST_ROWS.has(row.id)); + assert.equal( + error.details?.reason === RUNNER_EXCHANGE_REASONS.replyLost.reason, + REPLY_LOST_ROWS.has(row.id), + ); return true; }); }); @@ -267,7 +270,7 @@ test.each([ async (_, status) => { await assert.rejects(lostResponse([...status], SNAPSHOT), (error: unknown) => { assert.ok(error instanceof AppError); - assert.notEqual(error.details?.reason, RUNNER_REPLY_LOST_REASON); + assert.notEqual(error.details?.reason, RUNNER_EXCHANGE_REASONS.replyLost.reason); assert.equal(isRetryableRunnerError(error), true); return true; }); diff --git a/packages/apple-runner/src/__tests__/index-recovery-wiring.test.ts b/packages/apple-runner/src/__tests__/index-recovery-wiring.test.ts index db11df3d2f..3748be30dd 100644 --- a/packages/apple-runner/src/__tests__/index-recovery-wiring.test.ts +++ b/packages/apple-runner/src/__tests__/index-recovery-wiring.test.ts @@ -9,7 +9,7 @@ import type { RunnerSession } from '../runner-session.ts'; import { appleRunnerTestHost } from '../test-host.ts'; import { withAppleRunnerProvider } from '../runner-provider.ts'; import { classifyRunnerReportedError, type RunnerCommand } from '../runner-contract.ts'; -import { RUNNER_REPLY_LOST_REASON } from '../runner-error-classification.ts'; +import { RUNNER_EXCHANGE_REASONS } from '../runner-error-classification.ts'; import { createRunnerPhaseBudget, requireRunnerPhaseRemainingMs } from '../runner-phase-budget.ts'; import { captureDiagnostics, @@ -185,7 +185,7 @@ test.each(Object.values(LOST_RESPONSE_MUTATION_ROWS))( await assert.rejects(runAppleRunnerCommand(IOS_SIMULATOR, { ...request }), (error: unknown) => { assert.ok(error instanceof AppError); assert.equal(error.details?.dispatched, 'unknown'); - assert.equal(error.details?.reason, RUNNER_REPLY_LOST_REASON); + assert.equal(error.details?.reason, RUNNER_EXCHANGE_REASONS.replyLost.reason); return true; }); assert.equal( @@ -245,7 +245,7 @@ test.each(Object.values(LOST_RESPONSE_MUTATION_ROWS))( await assert.rejects(runAppleRunnerCommand(IOS_SIMULATOR, { ...request }), (error: unknown) => { assert.ok(error instanceof AppError); assert.equal(error.details?.dispatched, 'unknown'); - assert.equal(error.details?.reason, RUNNER_REPLY_LOST_REASON); + assert.equal(error.details?.reason, RUNNER_EXCHANGE_REASONS.replyLost.reason); return true; }); assert.equal(invalidateRunnerSessionMock.mock.calls.length, 1, 'the dead runner is dropped'); diff --git a/packages/apple-runner/src/__tests__/runner-command-recovery.test.ts b/packages/apple-runner/src/__tests__/runner-command-recovery.test.ts index 7cd0bc85e8..3f53a6609e 100644 --- a/packages/apple-runner/src/__tests__/runner-command-recovery.test.ts +++ b/packages/apple-runner/src/__tests__/runner-command-recovery.test.ts @@ -7,7 +7,7 @@ import { IOS_SIMULATOR } from './device-fixtures.ts'; import type { ExecResult } from '@agent-device/host-kit/command'; import { handleRunnerTransportErrorAfterCommandSend } from '../runner-command-recovery.ts'; import type { RunnerCommand } from '../runner-contract.ts'; -import { RUNNER_REPLY_LOST_REASON } from '../runner-error-classification.ts'; +import { RUNNER_EXCHANGE_REASONS } from '../runner-error-classification.ts'; import type { RunnerSession } from '../runner-session.ts'; import { startFakeRunnerServer, @@ -131,7 +131,7 @@ test('notAccepted from a restarted runner fails the lost command as unknown, nam await assert.rejects(result, (error: unknown) => { assert.ok(error instanceof AppError); - assert.equal(error.details?.reason, RUNNER_REPLY_LOST_REASON); + assert.equal(error.details?.reason, RUNNER_EXCHANGE_REASONS.replyLost.reason); assert.equal(error.details?.dispatched, 'unknown'); return true; }); @@ -149,7 +149,7 @@ test('a failing status probe retains the invalidation and names the lost reply', assert.notEqual(error.message, transportError.message); assert.equal(error.details?.transportError, transportError.message); assert.equal(error.cause, transportError); - assert.equal(error.details?.reason, RUNNER_REPLY_LOST_REASON); + assert.equal(error.details?.reason, RUNNER_EXCHANGE_REASONS.replyLost.reason); assert.equal(error.details?.transportReason, 'socket_reset'); assert.equal(error.details?.recovery, 'status_probe_failed'); assert.equal(error.details?.dispatched, 'unknown'); @@ -167,7 +167,7 @@ test('a command without an id cannot be probed: invalidate and name the lost rep await assert.rejects(result, (error: unknown) => { assert.ok(error instanceof AppError); assert.equal(error.cause, transportError); - assert.equal(error.details?.reason, RUNNER_REPLY_LOST_REASON); + assert.equal(error.details?.reason, RUNNER_EXCHANGE_REASONS.replyLost.reason); assert.equal(error.details?.recovery, 'status_recovery_unavailable'); return true; }); diff --git a/packages/apple-runner/src/__tests__/runner-error-classification.test.ts b/packages/apple-runner/src/__tests__/runner-error-classification.test.ts index 92ef044f2b..d9d4ddf313 100644 --- a/packages/apple-runner/src/__tests__/runner-error-classification.test.ts +++ b/packages/apple-runner/src/__tests__/runner-error-classification.test.ts @@ -8,7 +8,7 @@ import { } from '../runner-contract.ts'; import { RUNNER_ERROR_RULES, - RUNNER_REPLY_LOST_REASON, + RUNNER_EXCHANGE_REASONS, isRetryableRunnerError, isRunnerBusyError, resolveRunnerFatalErrorReason, @@ -51,7 +51,7 @@ test('transport-shaped failures are retryable', () => { test('a lost reply keys on its typed reason, never on the transport text it carries', () => { for (const message of ['fetch failed', 'connect ECONNREFUSED 127.0.0.1:8100', 'socket hang up']) { - const lostReply = commandFailed(message, { reason: RUNNER_REPLY_LOST_REASON }); + const lostReply = commandFailed(message, { reason: RUNNER_EXCHANGE_REASONS.replyLost.reason }); assert.equal(isRetryableRunnerError(lostReply), false, message); assert.equal(shouldRetryRunnerConnectError(lostReply), false, message); assert.equal(shouldRestartRunnerBeforeCommandSend(lostReply, TAP), false, message); diff --git a/packages/apple-runner/src/__tests__/runner-lifecycle-dispatch-disclosure.test.ts b/packages/apple-runner/src/__tests__/runner-lifecycle-dispatch-disclosure.test.ts index b8e2e4517d..d84405de06 100644 --- a/packages/apple-runner/src/__tests__/runner-lifecycle-dispatch-disclosure.test.ts +++ b/packages/apple-runner/src/__tests__/runner-lifecycle-dispatch-disclosure.test.ts @@ -40,10 +40,7 @@ vi.mock('../runner-session.ts', async () => { }); import { runAppleRunnerCommand } from '../index.ts'; -import { - isRetryableRunnerError, - RUNNER_REPLY_LOST_REASON, -} from '../runner-error-classification.ts'; +import { isRetryableRunnerError, RUNNER_EXCHANGE_REASONS } from '../runner-error-classification.ts'; import type { RunnerCommand } from '../runner-contract.ts'; import { resetRunnerRecycleLedgerForTests } from '../runner-recycle-ledger.ts'; import { waitForRunner } from '../runner-startup-transport.ts'; @@ -177,7 +174,7 @@ const DRIVERS: Record Promise> = { return await tap(); } catch (error) { assert.ok(error instanceof AppError); - assert.equal(error.details?.reason, RUNNER_REPLY_LOST_REASON); + assert.equal(error.details?.reason, RUNNER_EXCHANGE_REASONS.replyLost.reason); assert.equal(error.details?.recovery, 'status_probe_failed'); assert.equal(error.details?.runnerRestarted, undefined, 'the runner is not restarted'); throw error; @@ -253,7 +250,7 @@ test('a mutation whose connect-loop POST timed out after writing is not restarte assert.ok(error instanceof AppError); assert.equal(error.details?.runnerRestarted, undefined); assert.equal(error.details?.dispatched, 'unknown'); - assert.equal(error.details?.reason, RUNNER_REPLY_LOST_REASON); + assert.equal(error.details?.reason, RUNNER_EXCHANGE_REASONS.replyLost.reason); assert.equal(error.details?.recovery, 'status_probe_failed'); return true; }); @@ -271,7 +268,7 @@ test('a mutation whose reply and status probe both fail on transport text is not .mockRejectedValue(new AppError('COMMAND_FAILED', 'connect ECONNREFUSED 127.0.0.1:8100')); await assert.rejects(tap(), (error: unknown) => { assert.ok(error instanceof AppError); - assert.equal(error.details?.reason, RUNNER_REPLY_LOST_REASON); + assert.equal(error.details?.reason, RUNNER_EXCHANGE_REASONS.replyLost.reason); assert.equal(error.details?.transportError, 'fetch failed'); assert.equal(isRetryableRunnerError(error), false); return true; diff --git a/packages/apple-runner/src/__tests__/runner-lifecycle-prepare-artifact.test.ts b/packages/apple-runner/src/__tests__/runner-lifecycle-prepare-artifact.test.ts index 3aa90842cb..7ff89e809d 100644 --- a/packages/apple-runner/src/__tests__/runner-lifecycle-prepare-artifact.test.ts +++ b/packages/apple-runner/src/__tests__/runner-lifecycle-prepare-artifact.test.ts @@ -246,6 +246,8 @@ test('prepareIosRunner invalidates rebuilt sessions when bad-cache recovery heal assert.ok(error instanceof AppError); assert.equal(error.message, 'artifact restored but runner did not connect'); assert.equal(error.details?.restoredFailureReason, 'Runner endpoint probe failed'); + assert.equal(error.details?.reason, 'prepare_rebuilt_runner_unhealthy'); + assert.equal(error.details?.rebuiltFailureMessage, 'Runner health timed out'); assert.equal(error.details?.xctestrunPath, '/tmp/rebuilt.xctestrun'); assert.equal(error.details?.artifact, 'rebuilt'); assert.equal(error.details?.cache, 'miss'); diff --git a/packages/apple-runner/src/__tests__/runner-xctestrun-startup-failure-reasons.test.ts b/packages/apple-runner/src/__tests__/runner-xctestrun-startup-failure-reasons.test.ts index df565fc56e..ec030ac995 100644 --- a/packages/apple-runner/src/__tests__/runner-xctestrun-startup-failure-reasons.test.ts +++ b/packages/apple-runner/src/__tests__/runner-xctestrun-startup-failure-reasons.test.ts @@ -14,7 +14,6 @@ import { RUNNER_ERROR_RULES, classifyRunnerStartupFailure, RUNNER_STARTUP_FAILURE_REASONS, - RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON, type RunnerStartupFailureReason, } from '../runner-error-classification.ts'; import { assertDevToolsSecurityForIosRunner } from '../runner-dev-tools-security.ts'; @@ -151,7 +150,7 @@ test('the device speaking for a failure keeps the error that caused it', () => { const caused = new AppError( 'COMMAND_FAILED', 'xcodebuild build-for-testing failed', - { reason: RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON }, + { reason: RUNNER_STARTUP_FAILURE_REASONS.buildFailedUnclassified.reason }, new Error('xcodebuild was killed by the host'), ); @@ -218,11 +217,15 @@ function assertToolOutputReachable( assert.match(String(nestedDetails?.stdout), /AgentDeviceRunner/); } +const STARTUP_FAILURE_REASONS = Object.values(RUNNER_STARTUP_FAILURE_REASONS).map( + (row) => row.reason, +); + test('every startup failure reason has a recorded fixture', () => { const reasonsWithFixtures = new Set(RUNNER_STARTUP_FAILURE_FIXTURES.map((f) => f.reason)); - assert.equal(reasonsWithFixtures.size, RUNNER_STARTUP_FAILURE_REASONS.length); - for (const reason of RUNNER_STARTUP_FAILURE_REASONS) { + assert.equal(reasonsWithFixtures.size, STARTUP_FAILURE_REASONS.length); + for (const reason of STARTUP_FAILURE_REASONS) { assert.ok(reasonsWithFixtures.has(reason), `no fixture records the ${reason} reason`); } }); @@ -232,9 +235,9 @@ test('every reason the classifier can name is produced by a rule row', () => { RUNNER_ERROR_RULES.flatMap((rule) => (rule.buildFailure ? [rule.buildFailure.reason] : [])), ); - for (const reason of RUNNER_STARTUP_FAILURE_REASONS) { + for (const reason of STARTUP_FAILURE_REASONS) { // The catch-all is the classifier's own answer when no row matched, so it names no row. - if (reason === RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON) continue; + if (reason === RUNNER_STARTUP_FAILURE_REASONS.buildFailedUnclassified.reason) continue; // The device-readiness members are named by the device's own states in // `runner-device-readiness.ts`, not by a rule row: no amount of tool text establishes them, // which is exactly why they are declared as a subset (#2683). @@ -258,7 +261,10 @@ test('a scoped-set simulator xcodebuild cannot find names its set and the Xcode' test('a default-set simulator xcodebuild cannot find names no simulator set', async () => { const envelope = await driveBuildFailure(buildFixtureById('default-set-destination-not-found')); - assert.equal(envelope.details?.reason, RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON); + assert.equal( + envelope.details?.reason, + RUNNER_STARTUP_FAILURE_REASONS.buildFailedUnclassified.reason, + ); assert.equal(envelope.details?.simulatorSetPath, undefined); assert.equal(envelope.message, 'xcodebuild build-for-testing failed'); assert.doesNotMatch(String(envelope.hint), /DVTSimulatorSetLocation/); @@ -277,7 +283,10 @@ test('an argv that names a provisioning profile is not evidence of a signing fai const envelope = await driveBuildFailure(argvFixture); - assert.equal(envelope.details?.reason, RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON); + assert.equal( + envelope.details?.reason, + RUNNER_STARTUP_FAILURE_REASONS.buildFailedUnclassified.reason, + ); assert.match(String(envelope.hint), CACHE_RECOVERY_HINT); assert.doesNotMatch(String(envelope.hint), /AGENT_DEVICE_IOS_PROVISIONING_PROFILE/); }); @@ -301,7 +310,7 @@ test('the failure the build catch publishes does not classify itself', async () const reclassified = classifyRunnerStartupFailure(published); - assert.equal(reclassified.reason, RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON); + assert.equal(reclassified.reason, RUNNER_STARTUP_FAILURE_REASONS.buildFailedUnclassified.reason); assert.match(reclassified.hint, CACHE_RECOVERY_HINT); }); @@ -318,7 +327,10 @@ test('an identical message without the typed host fact is not read as a DevTools const envelope = await driveBuildRejection(withoutFact); - assert.equal(envelope.details?.reason, RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON); + assert.equal( + envelope.details?.reason, + RUNNER_STARTUP_FAILURE_REASONS.buildFailedUnclassified.reason, + ); assert.match(String(envelope.hint), CACHE_RECOVERY_HINT); assert.doesNotMatch(String(envelope.hint), /DevToolsSecurity/); }); @@ -332,7 +344,10 @@ test('an app identifier named without the availability fact is not read as a tak const envelope = await driveBuildFailure(nearMiss); - assert.equal(envelope.details?.reason, RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON); + assert.equal( + envelope.details?.reason, + RUNNER_STARTUP_FAILURE_REASONS.buildFailedUnclassified.reason, + ); assert.match(String(envelope.hint), CACHE_RECOVERY_HINT); assert.doesNotMatch(String(envelope.hint), /AGENT_DEVICE_IOS_BUNDLE_ID/); }); @@ -344,7 +359,10 @@ test('a conflicting-settings failure is not answered with missing-profile advice const envelope = await driveBuildFailure(conflict); - assert.equal(envelope.details?.reason, RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON); + assert.equal( + envelope.details?.reason, + RUNNER_STARTUP_FAILURE_REASONS.buildFailedUnclassified.reason, + ); assert.match(String(envelope.hint), CACHE_RECOVERY_HINT); assert.doesNotMatch(String(envelope.hint), /AGENT_DEVICE_IOS_PROVISIONING_PROFILE/); }); diff --git a/packages/apple-runner/src/runner-cache-metadata.ts b/packages/apple-runner/src/runner-cache-metadata.ts index b292c5ca1e..cc730ce1fb 100644 --- a/packages/apple-runner/src/runner-cache-metadata.ts +++ b/packages/apple-runner/src/runner-cache-metadata.ts @@ -3,7 +3,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { isMacOs, type DeviceInfo } from '@agent-device/kernel/device'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { hostEnvironment, isEnvTruthy, findProjectRoot, readVersion } from './host.ts'; import { resolveRunnerBuildDestinationFamily, @@ -19,6 +19,11 @@ import { import type { RunnerPhaseBudget } from './runner-phase-budget.ts'; import { computeRunnerSourceFingerprint } from './runner-source.ts'; +const RUNNER_BUILD_SETTINGS_REASONS = { + // The runner build used settings other than those its cache identity records. + buildSettingsMismatch: { reason: 'runner_build_settings_mismatch' }, +} as const satisfies ReasonTable<'apple runner'>; + const DEFAULT_IOS_RUNNER_APP_BUNDLE_ID = 'com.callstack.agentdevice.runner'; const RUNNER_DERIVED_ROOT = path.join(os.homedir(), '.agent-device', 'apple-runner'); export const RUNNER_CACHE_METADATA_FILE = '.agent-device-runner-cache.json'; @@ -504,7 +509,7 @@ export function requireRunnerBuildSettingsMatchBuildLog( 'COMMAND_FAILED', 'The Apple runner build did not use the settings its cache identity records', { - reason: 'runner_build_settings_mismatch', + reason: RUNNER_BUILD_SETTINGS_REASONS.buildSettingsMismatch.reason, buildLogPath: logPath, differences, hint: 'Align the build invocation with the runner cache identity resolvers, or rebuild without the cache.', diff --git a/packages/apple-runner/src/runner-cache.ts b/packages/apple-runner/src/runner-cache.ts index ca3f302d54..381a16ca70 100644 --- a/packages/apple-runner/src/runner-cache.ts +++ b/packages/apple-runner/src/runner-cache.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { resolveRunnerDerivedOverride } from './apple-runner-platform.ts'; import { emitDiagnostic, @@ -24,6 +24,11 @@ import type { RunnerCacheArtifactMismatch, RunnerCacheRefusal, } from './runner-artifact-manifest.ts'; + +const RUNNER_CACHE_REASONS = { + // The runner build products cannot be certified for cache reuse; `details.refusalReason` says why. + cacheUncertifiable: { reason: 'runner_cache_uncertifiable' }, +} as const satisfies ReasonTable<'apple runner'>; export { resolveExpectedRunnerCacheMetadata, resolveRunnerArchBuildSettings, @@ -203,7 +208,7 @@ export function requireCertifiedRunnerCacheArtifacts( 'COMMAND_FAILED', 'The Apple runner products cannot be certified for cache reuse', { - reason: 'runner_cache_uncertifiable', + reason: RUNNER_CACHE_REASONS.cacheUncertifiable.reason, refusalReason: refusal.reason, refusingPath: refusal.path ?? derived, ...(refusal.reason === 'root_unusable' ? {} : { resolvesTo: refusal.target }), diff --git a/packages/apple-runner/src/runner-command-recovery.ts b/packages/apple-runner/src/runner-command-recovery.ts index a5070fb59f..91967d75df 100644 --- a/packages/apple-runner/src/runner-command-recovery.ts +++ b/packages/apple-runner/src/runner-command-recovery.ts @@ -12,7 +12,7 @@ import { } from './runner-contract.ts'; import { isReadOnlyRunnerCommand } from './runner-command-traits.ts'; import { - RUNNER_REPLY_LOST_REASON, + RUNNER_EXCHANGE_REASONS, shouldRetainRunnerSession, shouldRecoverRunnerStatus, } from './runner-error-classification.ts'; @@ -111,7 +111,7 @@ async function applyRunnerTransportRecovery( } /** - * A lost reply fails a mutation as {@link RUNNER_REPLY_LOST_REASON}: it is not resent. A read keeps + * A lost reply fails a mutation as `runner_reply_lost`: it is not resent. A read keeps * the transport error, because `runAppleRunnerCommand` resends a read on exactly that error. */ function resolveRunnerRecoveryFailure( @@ -146,7 +146,7 @@ function buildLostReplyError( ...(lostReply.lifecycleState === undefined ? {} : { lifecycleState: lostReply.lifecycleState }), - reason: RUNNER_REPLY_LOST_REASON, + reason: RUNNER_EXCHANGE_REASONS.replyLost.reason, ...(transportReason === undefined ? {} : { transportReason }), recovery: lostReply.recovery, ...readReadinessPreflightRecoveryDetails(transportError), diff --git a/packages/apple-runner/src/runner-command-types.ts b/packages/apple-runner/src/runner-command-types.ts new file mode 100644 index 0000000000..fe2b3578d4 --- /dev/null +++ b/packages/apple-runner/src/runner-command-types.ts @@ -0,0 +1,171 @@ +// The wire shapes of the commands the host sends the XCTest runner. Types only, so a module that +// reads them loads nothing; runner-contract.ts re-exports them beside the behavior that builds them. +import type { DeviceRotation } from '@agent-device/contracts/device'; +import type { SnapshotPreferredBackend } from '@agent-device/kernel/snapshot'; +import type { ClickButton } from '@agent-device/contracts/click-button'; +import type { + CoordinateTapTextInputEvidence, + ElementSelectorKey, +} from '@agent-device/contracts/interactor-types'; +import type { GesturePlan } from '@agent-device/contracts/gesture-plan-types'; +import type { ScrollDirection } from '@agent-device/contracts/scroll-gesture'; +import type { ScrollReleaseBehavior } from '@agent-device/contracts/scroll-command'; + +export type RunnerCommand = { + coordinateTapTextInputEvidence?: CoordinateTapTextInputEvidence; + command: + | 'tap' + | 'mouseClick' + | 'longPress' + | 'drag' + | 'remotePress' + | 'type' + | 'swipe' + // Fused frame-resolve + drag scroll (non-tvOS). Intentionally mutating in runner command + // traits so it routes through single-send, command-id tracking, and lost-response status + // recovery like other gestures. + | 'scroll' + // macOS-only frame-resolve + desktop wheel scroll. Kept distinct from `scroll` so mobile + // touch drag semantics remain stable. + | 'desktopScroll' + | 'findText' + | 'querySelector' + | 'readText' + | 'snapshot' + | 'accessibilityAudit' + | 'screenshot' + | 'backInApp' + | 'home' + | 'rotate' + | 'gesture' + | 'gestureViewport' + | 'appSwitcher' + | 'actionButton' + | 'volumeUp' + | 'volumeDown' + | 'keyboardDismiss' + | 'keyboardReturn' + // Reads the software keyboard and the focused field's return key. A read: it reports what is on + // screen, and presses nothing. + | 'keyboardStatus' + | 'alert' + | 'sequence' + | 'recordStart' + | 'recordStop' + | 'status' + | 'uptime' + // The session app's XCUIApplication.state by name. A lifecycle read: it skips the activation + // preflight, so it reports the state the app is in rather than the one a repair leaves. + | 'appState' + // Reads the Simulator AX bridge tree in the runner process, off its journal and command queue. + | 'snapshotBridge' + // Sets the device's general pasteboard from the runner's own process: a simulator's + // `simctl pbcopy` only promises its data from a process that exits before anything reads it. + | 'pasteboardWrite' + | 'activate' + | 'terminate' + | 'targetReset' + | 'shutdown'; + commandId?: string; + statusCommandId?: string; + appBundleId?: string; + text?: string; + selectorKey?: ElementSelectorKey; + selectorValue?: string; + /** `querySelector` only: answer the lean per-element hittability read instead of a node. */ + hittabilityProbe?: boolean; + allowNonHittableCoordinateFallback?: boolean; + delayMs?: number; + textEntryMode?: 'append' | 'replace'; + action?: 'get' | 'accept' | 'dismiss'; + includesKeyboard?: boolean; + x?: number; + y?: number; + button?: ClickButton; + remoteButton?: 'select' | 'menu' | 'home' | 'up' | 'down' | 'left' | 'right'; + x2?: number; + y2?: number; + durationMs?: number; + /** Remaining request budget for runner work that performs bounded XCTest queries. */ + timeoutMs?: number; + direction?: ScrollDirection; + amount?: number; + pixels?: number; + scrollReleaseBehavior?: ScrollReleaseBehavior; + orientation?: DeviceRotation; + /** Canonical pointer samples planned by the portable gesture runtime. */ + gesturePlan?: GesturePlan; + outPath?: string; + fps?: number; + interactiveOnly?: boolean; + /** Pin the snapshot capture backend (same-backend evidence probes). */ + preferredBackend?: SnapshotPreferredBackend; + /** + * Read accessibility custom actions for merged leaves. Opt-in: each element + * costs its own AX round trip, and the runner pins the private-AX backend + * because no other backend can carry them. + */ + customActions?: boolean; + observeOnly?: boolean; + depth?: number; + scope?: string; + raw?: boolean; + fullscreen?: boolean; + inlineScreenshot?: boolean; + synthesized?: boolean; + /** + * The lit panel's display and native box in points, sent only for a multi-panel device on a + * command that resolves a screen (ADR 0025). + */ + litPanel?: { displayId: number; widthPt: number; heightPt: number }; + sequenceOrientation?: RunnerSequenceOrientation; + steps?: RunnerSequenceStep[]; + snapshotBridge?: RunnerSnapshotBridgeRequest; +}; + +/** + * One request to the Simulator AX bridge reader that the runner serves. `target` names the foreground + * process of `appBundleId`. `describe` reads that process's tree under the guest bridge's own bounds, + * and refuses a process other than `expectedPid` and `expectedProcessStartTime` as a stale target, so + * it cannot be sent without them. + */ +export type RunnerSnapshotBridgeRequest = + | { verb: 'target'; requestId: string; maxDurationMs?: number } + | { + verb: 'describe'; + requestId: string; + generation: string; + expectedPid: number; + expectedProcessStartTime: string; + maxDepth?: number; + maxNodes?: number; + maxDurationMs?: number; + maxResponseBytes?: number; + nativeLevelsHint?: number; + /** + * System surface host executables whose running process on this Simulator refuses the read with + * `system-surface-host-present`. The runner names its own Simulator. + */ + surfaceHostExecutables?: readonly string[]; + }; + +/** + * One allowlisted coordinate gesture step inside a fused `sequence` runner command. + * The kind set is intentionally narrow (tap/doubleTap/longPress) and validated on both the + * daemon and runner sides — see `parseRunnerSequenceResult` in runner-contract.ts (the single + * interpretation point). + */ +export type RunnerSequenceStep = { + kind: 'tap' | 'doubleTap' | 'longPress'; + x: number; + y: number; + durationMs?: number; + pauseMs?: number; + /** + * For `tap` steps on iOS non-tv: use the synthesized HID tap (synthesizedTapAt) fast path + * instead of the drag-based XCUICoordinate tapAt, matching the individual `tap` command. + */ + synthesized?: boolean; +}; + +export type RunnerSequenceOrientation = 1 | 2 | 3 | 4; diff --git a/packages/apple-runner/src/runner-contract.ts b/packages/apple-runner/src/runner-contract.ts index 5da9cfbe22..8802c59bf0 100644 --- a/packages/apple-runner/src/runner-contract.ts +++ b/packages/apple-runner/src/runner-contract.ts @@ -5,18 +5,14 @@ import { toAppErrorCode, type AppErrorCode, type DispatchDisclosure, + type ReasonTable, } from '@agent-device/kernel/errors'; import crypto from 'node:crypto'; -import type { DeviceRotation } from '@agent-device/contracts/device'; -import type { SnapshotPreferredBackend } from '@agent-device/kernel/snapshot'; -import type { ClickButton } from '@agent-device/contracts/click-button'; import type { - CoordinateTapTextInputEvidence, - ElementSelectorKey, -} from '@agent-device/contracts/interactor-types'; -import type { GesturePlan } from '@agent-device/contracts/gesture-plan-types'; -import type { ScrollDirection } from '@agent-device/contracts/scroll-gesture'; -import type { ScrollReleaseBehavior } from '@agent-device/contracts/scroll-command'; + RunnerCommand, + RunnerSequenceOrientation, + RunnerSequenceStep, +} from './runner-command-types.ts'; import { getRequestSignal, isRequestCanceled } from './host.ts'; /** @@ -37,161 +33,12 @@ export const RUNNER_READY_PREFLIGHT_TIMEOUT_MS = 1_000; */ export const RUNNER_WEDGED_RUNNER_CODE: RunnerTableErrorCode = 'RUNNER_WEDGED'; -export type RunnerCommand = { - coordinateTapTextInputEvidence?: CoordinateTapTextInputEvidence; - command: - | 'tap' - | 'mouseClick' - | 'longPress' - | 'drag' - | 'remotePress' - | 'type' - | 'swipe' - // Fused frame-resolve + drag scroll (non-tvOS). Intentionally mutating in runner command - // traits so it routes through single-send, command-id tracking, and lost-response status - // recovery like other gestures. - | 'scroll' - // macOS-only frame-resolve + desktop wheel scroll. Kept distinct from `scroll` so mobile - // touch drag semantics remain stable. - | 'desktopScroll' - | 'findText' - | 'querySelector' - | 'readText' - | 'snapshot' - | 'accessibilityAudit' - | 'screenshot' - | 'backInApp' - | 'home' - | 'rotate' - | 'gesture' - | 'gestureViewport' - | 'appSwitcher' - | 'actionButton' - | 'volumeUp' - | 'volumeDown' - | 'keyboardDismiss' - | 'keyboardReturn' - // Reads the software keyboard and the focused field's return key. A read: it reports what is on - // screen, and presses nothing. - | 'keyboardStatus' - | 'alert' - | 'sequence' - | 'recordStart' - | 'recordStop' - | 'status' - | 'uptime' - // The session app's XCUIApplication.state by name. A lifecycle read: it skips the activation - // preflight, so it reports the state the app is in rather than the one a repair leaves. - | 'appState' - // Reads the Simulator AX bridge tree in the runner process, off its journal and command queue. - | 'snapshotBridge' - // Sets the device's general pasteboard from the runner's own process: a simulator's - // `simctl pbcopy` only promises its data from a process that exits before anything reads it. - | 'pasteboardWrite' - | 'activate' - | 'terminate' - | 'targetReset' - | 'shutdown'; - commandId?: string; - statusCommandId?: string; - appBundleId?: string; - text?: string; - selectorKey?: ElementSelectorKey; - selectorValue?: string; - /** `querySelector` only: answer the lean per-element hittability read instead of a node. */ - hittabilityProbe?: boolean; - allowNonHittableCoordinateFallback?: boolean; - delayMs?: number; - textEntryMode?: 'append' | 'replace'; - action?: 'get' | 'accept' | 'dismiss'; - includesKeyboard?: boolean; - x?: number; - y?: number; - button?: ClickButton; - remoteButton?: 'select' | 'menu' | 'home' | 'up' | 'down' | 'left' | 'right'; - x2?: number; - y2?: number; - durationMs?: number; - /** Remaining request budget for runner work that performs bounded XCTest queries. */ - timeoutMs?: number; - direction?: ScrollDirection; - amount?: number; - pixels?: number; - scrollReleaseBehavior?: ScrollReleaseBehavior; - orientation?: DeviceRotation; - /** Canonical pointer samples planned by the portable gesture runtime. */ - gesturePlan?: GesturePlan; - outPath?: string; - fps?: number; - interactiveOnly?: boolean; - /** Pin the snapshot capture backend (same-backend evidence probes). */ - preferredBackend?: SnapshotPreferredBackend; - /** - * Read accessibility custom actions for merged leaves. Opt-in: each element - * costs its own AX round trip, and the runner pins the private-AX backend - * because no other backend can carry them. - */ - customActions?: boolean; - observeOnly?: boolean; - depth?: number; - scope?: string; - raw?: boolean; - fullscreen?: boolean; - inlineScreenshot?: boolean; - synthesized?: boolean; - /** - * The lit panel's display and native box in points, sent only for a multi-panel device on a - * command that resolves a screen (ADR 0025). - */ - litPanel?: { displayId: number; widthPt: number; heightPt: number }; - sequenceOrientation?: RunnerSequenceOrientation; - steps?: RunnerSequenceStep[]; - snapshotBridge?: RunnerSnapshotBridgeRequest; -}; - -/** - * One request to the Simulator AX bridge reader that the runner serves. `target` names the foreground - * process of `appBundleId`. `describe` reads that process's tree under the guest bridge's own bounds, - * and refuses a process other than `expectedPid` and `expectedProcessStartTime` as a stale target, so - * it cannot be sent without them. - */ -export type RunnerSnapshotBridgeRequest = - | { verb: 'target'; requestId: string; maxDurationMs?: number } - | { - verb: 'describe'; - requestId: string; - generation: string; - expectedPid: number; - expectedProcessStartTime: string; - maxDepth?: number; - maxNodes?: number; - maxDurationMs?: number; - maxResponseBytes?: number; - nativeLevelsHint?: number; - /** - * System surface host executables whose running process on this Simulator refuses the read with - * `system-surface-host-present`. The runner names its own Simulator. - */ - surfaceHostExecutables?: readonly string[]; - }; - -/** - * One allowlisted coordinate gesture step inside a fused `sequence` runner command. - * The kind set is intentionally narrow (tap/doubleTap/longPress) and validated on both the - * daemon and runner sides — see `parseRunnerSequenceResult` below (the single interpretation point). - */ -export type RunnerSequenceStep = { - kind: 'tap' | 'doubleTap' | 'longPress'; - x: number; - y: number; - durationMs?: number; - pauseMs?: number; - /** - * For `tap` steps on iOS non-tv: use the synthesized HID tap (synthesizedTapAt) fast path - * instead of the drag-based XCUICoordinate tapAt, matching the individual `tap` command. - */ - synthesized?: boolean; -}; +export type { + RunnerCommand, + RunnerSequenceOrientation, + RunnerSequenceStep, + RunnerSnapshotBridgeRequest, +} from './runner-command-types.ts'; export function resolveRunnerRequestSignal(options: { requestId?: string; @@ -310,6 +157,46 @@ export type RunnerErrorCodeRow = Readonly<{ }>; }>; +/** + * The `details.reason` values the host publishes for Apple runner failures: the reasons the rows of + * {@link RUNNER_ERROR_CODES} map runner codes to (the runner itself writes no reason), and the + * refusals this module raises before or around a runner exchange. + */ +export const RUNNER_ERROR_REASONS = { + // The runner was still busy with an earlier command and refused this one; retry it. + runnerBusy: { reason: 'runner_busy' }, + // The command's work on the app's main thread did not finish in time, so it may have run. + mainThreadTimeout: { reason: 'runner_main_thread_timeout' }, + // A coordinate `fill` point identified no text input, so nothing was tapped or typed. + noTextInputAtPoint: { reason: 'no_text_input_at_point', commands: ['fill'] }, + // The runner could not tell whether a coordinate `fill` point holds a text input; nothing was tapped. + textInputProbeUnavailable: { reason: 'text_input_probe_unavailable', commands: ['fill'] }, + // The runner refused the gesture before its events reached XCTest, so nothing was sent. + synthesizedGestureNotDispatched: { reason: 'synthesized_gesture_not_dispatched' }, + // The gesture failed after its events reached XCTest, so it may have run. + synthesizedGestureOutcomeUnknown: { reason: 'synthesized_gesture_outcome_unknown' }, + // The back swipe ran and left the app's screen unchanged. + backSwipeNoChange: { reason: 'back_swipe_no_change', commands: ['back'] }, + // The back swipe ran, but the screen was already changing or could not be sampled afterwards. + backSwipeUnverified: { reason: 'back_swipe_unverified', commands: ['back'] }, + // The back swipe was refused before it reached the device. + backSwipeNotDispatched: { reason: 'back_swipe_not_dispatched', commands: ['back'] }, + // A Return on the focused input could not be confirmed; a tap on the field may have landed. + keyboardReturnUnavailable: { reason: 'keyboard_return_unavailable' }, + // The target has no such hardware control, such as an Action Button, so nothing was pressed. + hardwareControlUnavailable: { reason: 'hardware_control_unavailable' }, + // On macOS, the app's accessibility tree exposes no in-app back control. + inAppBackControlUnavailable: { reason: 'in_app_back_control_unavailable', commands: ['back'] }, + // Apple's audit failed while a system alert covered the app; answer the alert, then retry. + nativeAuditBlockedByAlert: { reason: 'native_audit_blocked_by_alert', commands: ['audit'] }, + // The runner build does not require a listener token; rebuild it with this agent-device version. + tokenUnsupported: { reason: 'runner_token_unsupported' }, + // The daemon refused a runner action sequence before sending it, so nothing reached the device. + sequenceInvalid: { reason: 'runner_sequence_invalid' }, + // Another request took over the Apple runner session before this command was sent. + sessionOwnershipChanged: { reason: 'runner_session_ownership_changed' }, +} as const satisfies ReasonTable<'apple runner'>; + export const RUNNER_ERROR_CODES = { INVALID_ARGS: { dispatched: 'no' }, ELEMENT_NOT_FOUND: { dispatched: 'no' }, @@ -318,7 +205,11 @@ export const RUNNER_ERROR_CODES = { OBSERVATION_UNAVAILABLE: { dispatched: 'no' }, // Transient by construction (#1105) — past the wedge threshold the runner escalates to // RUNNER_WEDGED — so every host path publishes this refusal as retriable. - RUNNER_BUSY: { dispatched: 'no', reason: 'runner_busy', diagnosticOnly: { retriable: true } }, + RUNNER_BUSY: { + dispatched: 'no', + reason: RUNNER_ERROR_REASONS.runnerBusy.reason, + diagnosticOnly: { retriable: true }, + }, RUNNER_WEDGED: { dispatched: 'no' }, // A repeat of a `commandId` the runner already finished, when that command keeps no response body // to replay. Nothing ran for the repeat, but only the runner knows whether an earlier send of that @@ -334,7 +225,7 @@ export const RUNNER_ERROR_CODES = { // of a later command, this is the only typed signal available before any refusal happens. It is not // retriable: the wait already elapsed and an immediate retry would only meet RUNNER_BUSY. dispatched: 'unknown', - reason: 'runner_main_thread_timeout', + reason: RUNNER_ERROR_REASONS.mainThreadTimeout.reason, diagnosticOnly: {}, }, SCROLL_KEYBOARD_OCCLUDES_SURFACE: { dispatched: 'no', diagnosticOnly: {} }, @@ -349,38 +240,44 @@ export const RUNNER_ERROR_CODES = { // A coordinate `fill` whose point identified no text input (#1721). The synthesized first-responder // replacement this route would otherwise take has no element, so its clear and its typed text reach // whichever field already holds focus. The refusal answers before the focus tap. - NO_TEXT_INPUT_AT_POINT: { dispatched: 'no', reason: 'no_text_input_at_point' }, + NO_TEXT_INPUT_AT_POINT: { + dispatched: 'no', + reason: RUNNER_ERROR_REASONS.noTextInputAtPoint.reason, + }, // A coordinate `fill` whose pre-tap input lookup could not answer on the degraded channel. Like // NO_TEXT_INPUT_AT_POINT it answers before the focus tap, and it is not a claim that the point has // no input — only that the runner could not tell. - TEXT_INPUT_PROBE_UNAVAILABLE: { dispatched: 'no', reason: 'text_input_probe_unavailable' }, + TEXT_INPUT_PROBE_UNAVAILABLE: { + dispatched: 'no', + reason: RUNNER_ERROR_REASONS.textInputProbeUnavailable.reason, + }, // Refused before the gesture's events reached XCTest, so the command sent nothing. SYNTHESIZED_GESTURE_NOT_DISPATCHED: { dispatched: 'no', - reason: 'synthesized_gesture_not_dispatched', + reason: RUNNER_ERROR_REASONS.synthesizedGestureNotDispatched.reason, diagnosticOnly: {}, }, // Failed after the gesture's events reached XCTest, so it may have run. SYNTHESIZED_GESTURE_OUTCOME_UNKNOWN: { dispatched: 'unknown', - reason: 'synthesized_gesture_outcome_unknown', + reason: RUNNER_ERROR_REASONS.synthesizedGestureOutcomeUnknown.reason, diagnosticOnly: {}, }, // The swipe ran and left the app's screen unchanged. BACK_SWIPE_NO_CHANGE: { dispatched: 'unknown', - reason: 'back_swipe_no_change', + reason: RUNNER_ERROR_REASONS.backSwipeNoChange.reason, diagnosticOnly: {}, }, // The swipe ran, but the screen kept changing on its own beforehand or could not be sampled after. BACK_SWIPE_UNVERIFIED: { dispatched: 'unknown', - reason: 'back_swipe_unverified', + reason: RUNNER_ERROR_REASONS.backSwipeUnverified.reason, diagnosticOnly: {}, }, BACK_SWIPE_NOT_DISPATCHED: { dispatched: 'no', - reason: 'back_swipe_not_dispatched', + reason: RUNNER_ERROR_REASONS.backSwipeNotDispatched.reason, diagnosticOnly: {}, }, // The Apple runner left the visible keyboard alone: it exposes no dismiss key, and a background tap @@ -395,7 +292,7 @@ export const RUNNER_ERROR_CODES = { // landed. KEYBOARD_RETURN_UNAVAILABLE: { dispatched: 'unknown', - reason: 'keyboard_return_unavailable', + reason: RUNNER_ERROR_REASONS.keyboardReturnUnavailable.reason, diagnosticOnly: { wireCode: 'UNSUPPORTED_OPERATION' }, }, // A press of a hardware or Siri Remote control this target cannot perform. Today that is the Action @@ -408,7 +305,7 @@ export const RUNNER_ERROR_CODES = { // the control. HARDWARE_CONTROL_UNAVAILABLE: { dispatched: 'no', - reason: 'hardware_control_unavailable', + reason: RUNNER_ERROR_REASONS.hardwareControlUnavailable.reason, diagnosticOnly: { wireCode: 'UNSUPPORTED_OPERATION' }, }, // macOS `back` where the app's tree exposes no in-app back control. That refusal answered with no @@ -417,7 +314,7 @@ export const RUNNER_ERROR_CODES = { // the wrong home for it and this row must not move the command to a code its callers never saw. IN_APP_BACK_CONTROL_UNAVAILABLE: { dispatched: 'no', - reason: 'in_app_back_control_unavailable', + reason: RUNNER_ERROR_REASONS.inAppBackControlUnavailable.reason, diagnosticOnly: {}, }, // `audit` asked a runner that cannot run Apple's audit for it: an OS older than iOS 17, or a @@ -432,7 +329,7 @@ export const RUNNER_ERROR_CODES = { // app, so the reply proves no effect reached it. NATIVE_AUDIT_BLOCKED_BY_ALERT: { dispatched: 'no', - reason: 'native_audit_blocked_by_alert', + reason: RUNNER_ERROR_REASONS.nativeAuditBlockedByAlert.reason, diagnosticOnly: {}, }, // The four runner codes meaning "this capture did not happen" (#2728), covering the display, the @@ -697,7 +594,6 @@ export function assertRunnerRequestActive(requestId: string | undefined): void { const RUNNER_TOKEN_HEADER = 'X-Agent-Device-Runner-Token'; const RUNNER_TOKEN_ENFORCED_HEADER = 'X-Agent-Device-Runner-Auth'; const RUNNER_TOKEN_BYTES = 24; -export const RUNNER_TOKEN_UNSUPPORTED_REASON = 'runner_token_unsupported'; /** How to reach one runner generation: its listener port and the token it requires. */ export type RunnerEndpoint = Readonly<{ @@ -734,7 +630,7 @@ export function runnerRequestHeaders(endpoint: RunnerEndpoint): Record): AppError { return discloseDispatch( - new AppError('INVALID_ARGS', message, { ...details, reason: 'runner_sequence_invalid' }), + new AppError('INVALID_ARGS', message, { + ...details, + reason: RUNNER_ERROR_REASONS.sequenceInvalid.reason, + }), 'no', ); } diff --git a/packages/apple-runner/src/runner-device-readiness.ts b/packages/apple-runner/src/runner-device-readiness.ts index a6ddc6fba6..cb5a2bb99c 100644 --- a/packages/apple-runner/src/runner-device-readiness.ts +++ b/packages/apple-runner/src/runner-device-readiness.ts @@ -3,6 +3,7 @@ import { isIosFamily, type DeviceInfo } from '@agent-device/kernel/device'; import { resolveIosPhysicalDeviceControl } from './host.ts'; import type { IosDeviceReadiness } from './runner-physical-device.ts'; import { + RUNNER_STARTUP_FAILURE_REASONS, type IosRunnerDeviceStates, type RunnerDeviceReadinessFailureReason, } from './runner-error-classification.ts'; @@ -71,7 +72,7 @@ function namePreBuildDeviceObstacle( | undefined { if (readiness.developerMode !== 'disabled') return undefined; return { - reason: 'device_developer_mode_disabled', + reason: RUNNER_STARTUP_FAILURE_REASONS.deviceDeveloperModeDisabled.reason, message: DEVICE_MODE_OFF_MESSAGE, hint: readiness.remedies.developerModeOff, }; diff --git a/packages/apple-runner/src/runner-error-classification.ts b/packages/apple-runner/src/runner-error-classification.ts index ee0402975f..52010c2d90 100644 --- a/packages/apple-runner/src/runner-error-classification.ts +++ b/packages/apple-runner/src/runner-error-classification.ts @@ -4,6 +4,7 @@ import { type AppErrorCode, type AppErrorDetails, type DispatchDisclosure, + type ReasonTable, } from '@agent-device/kernel/errors'; import { isCommandTimeoutError } from './host.ts'; import type { @@ -15,7 +16,7 @@ import { RUNNER_WEDGED_RUNNER_CODE, type RunnerTableErrorCode, type RunnerCommand, - RUNNER_TOKEN_UNSUPPORTED_REASON, + RUNNER_ERROR_REASONS, } from './runner-contract.ts'; import { isReadOnlyRunnerCommand } from './runner-command-traits.ts'; @@ -48,12 +49,14 @@ export function runnerConnectFailureDetails(reason: RunnerConnectFailureReason): return { runnerConnectFailureReason: reason }; } -/** - * `details.reason` of a mutation whose reply stayed lost: status recovery found no result and no - * runner answer, so nothing proves the command did not run. The command is not resent; the caller - * observes the screen before acting again. A read never carries it, because it is resent. - */ -export const RUNNER_REPLY_LOST_REASON = 'runner_reply_lost'; +export const RUNNER_EXCHANGE_REASONS = { + /** Not resent, and a read never carries it, because a read is resent. */ + // A mutation's reply was lost and status recovery found no result, so it may have run; + // observe the screen before acting again. + replyLost: { reason: 'runner_reply_lost' }, + // The HTTP forwarder in front of the runner answered 502, 503 or 504. + forwardingUnavailable: { reason: 'runner_forwarding_unavailable' }, +} as const satisfies ReasonTable<'apple runner'>; type RunnerErrorMatch = { /** Required `AppError.code`; absent = any AppError. */ @@ -69,9 +72,9 @@ type RunnerErrorMatch = { }; const hasRunnerReplyLostReason: RunnerErrorDetailsMatch = (details) => - details.reason === RUNNER_REPLY_LOST_REASON; + details.reason === RUNNER_EXCHANGE_REASONS.replyLost.reason; const hasRunnerTokenUnsupportedReason: RunnerErrorDetailsMatch = (details) => - details.reason === RUNNER_TOKEN_UNSUPPORTED_REASON; + details.reason === RUNNER_ERROR_REASONS.tokenUnsupported.reason; /** * The runner refused the command before running it while abandoned main-thread work drains (#1105). * The runner code owns the verdict — never `details.reason`, which a host path can publish for its @@ -102,8 +105,8 @@ const hasRunnerConnectFailureReason = * Xcode's own wording cannot, on its own, mark a failure terminal. */ const hasLaunchLogCauseFailure: RunnerErrorDetailsMatch = (details) => - details.reason === SIMULATOR_SERVICE_HUB_UNAVAILABLE_REASON || - details.reason === SIMULATOR_SET_DESTINATION_NOT_FOUND_REASON; + details.reason === RUNNER_STARTUP_FAILURE_REASONS.simulatorServiceHubUnavailable.reason || + details.reason === RUNNER_STARTUP_FAILURE_REASONS.simulatorSetDestinationNotFound.reason; /** * The preflight marks whatever it was waiting on when it stopped, and one of the things it waits on * is a caller that stopped waiting. A canceled request is not a wedged runner: the restart this @@ -125,24 +128,6 @@ type RunnerErrorVerdicts = { postSendRecovery?: boolean; // Status recovery can reach runner after lost response. }; -/** - * The two device-readiness members (#2683): what the iPhone itself reports through - * `devicectl device info details`, not what another tool's output implies about it. They are listed - * apart because they are the members {@link classifyRunnerStartupFailure} does NOT produce — no - * xcodebuild or host-tool text establishes them, and the code that reads the device publishes them - * with the hint beside it. The two reach the caller at different moments, which is the whole - * asymmetry of #2683: a disabled Developer Mode toggle refuses the run up front, while an unavailable - * developer disk image is published onto a build that named no cause of its own, because iOS 17+ - * mounts that image on demand during build and launch. A connect-stage failure always claims a cause - * of its own (`IOS_RUNNER_CONNECT_TIMEOUT` unless a provisioning row matches first), so there the - * image state travels only as `details.developerDiskImage`, and - * `device_developer_disk_image_unavailable` is published only from the startup build catch. - */ -export const RUNNER_DEVICE_READINESS_FAILURE_REASONS = [ - 'device_developer_mode_disabled', - 'device_developer_disk_image_unavailable', -] as const; - /** * Why the Apple runner could not reach the point of serving a command (#2680). Published in * `details.reason` on the `COMMAND_FAILED` every one of these paths throws, so a caller branches @@ -160,41 +145,62 @@ export const RUNNER_DEVICE_READINESS_FAILURE_REASONS = [ * Nothing outside this package publishes or consumes this enum, and one declaration is the only way * a row and its reason cannot disagree. */ -export const RUNNER_STARTUP_FAILURE_REASONS = [ - 'bundle_identifier_already_registered', - 'signing_no_development_team', - 'signing_provisioning_profile_missing', - 'signing_unspecified', - 'devtools_security_developer_mode_disabled', - 'simulator_service_hub_unavailable', - 'simulator_set_destination_not_found', - ...RUNNER_DEVICE_READINESS_FAILURE_REASONS, - 'build_failed_unclassified', -] as const; +export const RUNNER_STARTUP_FAILURE_REASONS = { + // The runner's bundle identifier is taken; set AGENT_DEVICE_IOS_BUNDLE_ID to a unique value. + bundleIdentifierAlreadyRegistered: { reason: 'bundle_identifier_already_registered' }, + // The runner build needs a development team for signing. + signingNoDevelopmentTeam: { reason: 'signing_no_development_team' }, + // No installed provisioning profile covers the runner, or the one found is unusable. + signingProvisioningProfileMissing: { reason: 'signing_provisioning_profile_missing' }, + // The runner build failed on code signing for a cause the output does not name. + signingUnspecified: { reason: 'signing_unspecified' }, + // DevToolsSecurity is disabled on the host, so the UI test runner cannot be attached. + devToolsSecurityDeveloperModeDisabled: { reason: 'devtools_security_developer_mode_disabled' }, + /** + * macOS gates `DTServiceHub` behind a version-restriction entitlement, so an Xcode older than the + * macOS it runs on cannot bless the simulator service at all: every launch fails the same way until + * the host selects an Xcode that supports its macOS. The launch output reports that refusal as a + * Code=1 localDeviceConnectionWithError failure; a bless warning alone can also precede a + * successful boot. + */ + // macOS refused to load this Xcode's simulator service; select an Xcode that supports this macOS. + simulatorServiceHubUnavailable: { reason: 'simulator_service_hub_unavailable' }, + /** The set is named on the command, so every retry fails the same way. */ + // xcodebuild found no simulator with this id in the requested simulator set. + simulatorSetDestinationNotFound: { reason: 'simulator_set_destination_not_found' }, + /** + * The two device-readiness members (#2683): what the iPhone itself reports through + * `devicectl device info details`, not what another tool's output implies about it. They are listed + * apart because they are the members {@link classifyRunnerStartupFailure} does NOT produce — no + * xcodebuild or host-tool text establishes them, and the code that reads the device publishes them + * with the hint beside it. The two reach the caller at different moments, which is the whole + * asymmetry of #2683: a disabled Developer Mode toggle refuses the run up front, while an unavailable + * developer disk image is published onto a build that named no cause of its own, because iOS 17+ + * mounts that image on demand during build and launch. A connect-stage failure always claims a cause + * of its own (`IOS_RUNNER_CONNECT_TIMEOUT` unless a provisioning row matches first), so there the + * image state travels only as `details.developerDiskImage`, and + * `device_developer_disk_image_unavailable` is published only from the startup build catch. + */ + // Developer Mode is off on the physical device, so it refuses the runner. + deviceDeveloperModeDisabled: { reason: 'device_developer_mode_disabled' }, + // The physical device reports no developer disk image, and the runner build named no other cause. + deviceDeveloperDiskImageUnavailable: { reason: 'device_developer_disk_image_unavailable' }, + /** An unclassified build is not evidence of a signing problem, so the hint names none. */ + // The runner did not start and no rule proves a cause; the hint gives the cache-recovery steps. + buildFailedUnclassified: { reason: 'build_failed_unclassified' }, +} as const satisfies ReasonTable<'apple runner'>; + +export type RunnerStartupFailureReason = + (typeof RUNNER_STARTUP_FAILURE_REASONS)[keyof typeof RUNNER_STARTUP_FAILURE_REASONS]['reason']; -export type RunnerStartupFailureReason = (typeof RUNNER_STARTUP_FAILURE_REASONS)[number]; +export const RUNNER_DEVICE_READINESS_FAILURE_REASONS = [ + RUNNER_STARTUP_FAILURE_REASONS.deviceDeveloperModeDisabled.reason, + RUNNER_STARTUP_FAILURE_REASONS.deviceDeveloperDiskImageUnavailable.reason, +] as const; -/** The device-readiness subset, typed from the one list above. */ export type RunnerDeviceReadinessFailureReason = (typeof RUNNER_DEVICE_READINESS_FAILURE_REASONS)[number]; -/** - * The reason for a simulator runner launch whose service hub the host macOS refused to load. macOS - * gates `DTServiceHub` behind a version-restriction entitlement, so an Xcode older than the macOS it - * runs on cannot bless the simulator service at all: every launch fails the same way until the host - * selects an Xcode that supports its macOS. The launch output reports that refusal as a Code=1 - * localDeviceConnectionWithError failure; a bless warning alone can also precede a successful boot. - */ -const SIMULATOR_SERVICE_HUB_UNAVAILABLE_REASON: RunnerStartupFailureReason = - 'simulator_service_hub_unavailable'; - -/** - * The reason for a scoped-set launch whose simulator this Xcode cannot resolve. The set is named on the - * command, so a launch that finds no matching destination fails identically on every retry. - */ -const SIMULATOR_SET_DESTINATION_NOT_FOUND_REASON: RunnerStartupFailureReason = - 'simulator_set_destination_not_found'; - /** * The bless sentence stays on one line, but its underlying Code=1 refusal can be on the next * (#3449). Code=2 interruptions can instead let the runner start (#3963). @@ -204,14 +210,6 @@ const SIMULATOR_SERVICE_HUB_BLESS_MATCH = [ 'failed to bless service hub', ] as const; -/** - * The reason a startup failure carries when no rule proves a cause. Its hint is deliberately the - * cache-recovery advice rather than anything about signing: an unclassified build is not evidence of - * a signing problem. - */ -export const RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON: RunnerStartupFailureReason = - 'build_failed_unclassified'; - type RunnerErrorRule = { /** Stable rule name for tests and diagnostics. */ reason: string; @@ -247,7 +245,7 @@ type RunnerErrorRule = { * different complaint cannot drift into three different fixes for one lever. */ const PROFILE_UNUSABLE: RunnerErrorRule['buildFailure'] = { - reason: 'signing_provisioning_profile_missing', + reason: RUNNER_STARTUP_FAILURE_REASONS.signingProvisioningProfileMissing.reason, hint: 'Install/select a valid iOS provisioning profile, or set AGENT_DEVICE_IOS_PROVISIONING_PROFILE.', }; @@ -264,7 +262,7 @@ const PROFILE_UNUSABLE: RunnerErrorRule['buildFailure'] = { export const RUNNER_ERROR_RULES: readonly RunnerErrorRule[] = [ { // A mutation that may have run: no axis may resend or restart it, whatever text it carries. - reason: RUNNER_REPLY_LOST_REASON, + reason: RUNNER_EXCHANGE_REASONS.replyLost.reason, match: { code: 'COMMAND_FAILED', details: hasRunnerReplyLostReason }, verdicts: { retryable: false, @@ -277,13 +275,13 @@ export const RUNNER_ERROR_RULES: readonly RunnerErrorRule[] = [ { // The runner answered without requiring the listener token, so it predates the token and // listens to anyone: stop it, and never resend, restart into, or replay on it. - reason: RUNNER_TOKEN_UNSUPPORTED_REASON, + reason: RUNNER_ERROR_REASONS.tokenUnsupported.reason, match: { code: 'COMMAND_FAILED', details: hasRunnerTokenUnsupportedReason }, verdicts: { retryable: false, drainResend: false, connectRetry: false, - sessionFatalReason: RUNNER_TOKEN_UNSUPPORTED_REASON, + sessionFatalReason: RUNNER_ERROR_REASONS.tokenUnsupported.reason, restartBeforeSend: false, restartAfterReadinessPreflight: false, artifactSuspect: false, @@ -353,10 +351,10 @@ export const RUNNER_ERROR_RULES: readonly RunnerErrorRule[] = [ verdicts: { retryable: false, connectRetry: false }, }, { - reason: 'runner_forwarding_unavailable', + reason: RUNNER_EXCHANGE_REASONS.forwardingUnavailable.reason, match: { code: 'COMMAND_FAILED', - details: (details) => details.reason === 'runner_forwarding_unavailable', + details: (details) => details.reason === RUNNER_EXCHANGE_REASONS.forwardingUnavailable.reason, }, verdicts: { retryable: true, @@ -465,7 +463,7 @@ export const RUNNER_ERROR_RULES: readonly RunnerErrorRule[] = [ }, verdicts: {}, buildFailure: { - reason: 'simulator_set_destination_not_found', + reason: RUNNER_STARTUP_FAILURE_REASONS.simulatorSetDestinationNotFound.reason, hint: 'Check that the simulator still exists in the --ios-simulator-device-set this error names (`xcrun simctl --set list devices`). If it does, the Xcode this error names no longer honors -DVTSimulatorSetLocation, so use a simulator in the default set.', messageSuffix: (details) => typeof details.simulatorSetPath === 'string' && typeof details.simulatorUdid === 'string' @@ -486,7 +484,7 @@ export const RUNNER_ERROR_RULES: readonly RunnerErrorRule[] = [ }, verdicts: {}, buildFailure: { - reason: SIMULATOR_SERVICE_HUB_UNAVAILABLE_REASON, + reason: RUNNER_STARTUP_FAILURE_REASONS.simulatorServiceHubUnavailable.reason, hint: 'This Xcode cannot start its simulator service on this macOS: macOS refuses to load its DTServiceHub. Select an Xcode that supports this macOS on the daemon host (`xcode-select -s /Applications/Xcode.app`, or DEVELOPER_DIR=/Applications/Xcode.app for the daemon process), then retry. Updating Xcode is the fix; restarting the runner or clearing derived data cannot change it.', messageSuffix: () => 'this Xcode cannot start its simulator service on this macOS', }, @@ -496,7 +494,7 @@ export const RUNNER_ERROR_RULES: readonly RunnerErrorRule[] = [ match: { toolTextIncludesAll: ['failed registering bundle identifier'] }, verdicts: {}, buildFailure: { - reason: 'bundle_identifier_already_registered', + reason: RUNNER_STARTUP_FAILURE_REASONS.bundleIdentifierAlreadyRegistered.reason, hint: 'Set AGENT_DEVICE_IOS_BUNDLE_ID to a unique reverse-DNS value (for example, com.yourname.agentdevice.runner), then retry.', }, }, @@ -508,7 +506,7 @@ export const RUNNER_ERROR_RULES: readonly RunnerErrorRule[] = [ match: { toolTextLineIncludesAll: ['app identifier', 'not available'] }, verdicts: {}, buildFailure: { - reason: 'bundle_identifier_already_registered', + reason: RUNNER_STARTUP_FAILURE_REASONS.bundleIdentifierAlreadyRegistered.reason, hint: 'Set AGENT_DEVICE_IOS_BUNDLE_ID to a unique reverse-DNS value (for example, com.yourname.agentdevice.runner), then retry.', }, }, @@ -517,7 +515,7 @@ export const RUNNER_ERROR_RULES: readonly RunnerErrorRule[] = [ match: { toolTextIncludesAll: ['requires a development team'] }, verdicts: {}, buildFailure: { - reason: 'signing_no_development_team', + reason: RUNNER_STARTUP_FAILURE_REASONS.signingNoDevelopmentTeam.reason, hint: 'Configure signing in Xcode or set AGENT_DEVICE_IOS_TEAM_ID for physical-device runs.', }, }, @@ -531,7 +529,7 @@ export const RUNNER_ERROR_RULES: readonly RunnerErrorRule[] = [ match: { toolTextIncludesAll: ['conflicting provisioning settings'] }, verdicts: {}, buildFailure: { - reason: RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON, + reason: RUNNER_STARTUP_FAILURE_REASONS.buildFailedUnclassified.reason, hint: RUNNER_CACHE_RECOVERY_HINT, }, }, @@ -583,7 +581,7 @@ export const RUNNER_ERROR_RULES: readonly RunnerErrorRule[] = [ match: { toolTextIncludesAll: ['code signing'] }, verdicts: {}, buildFailure: { - reason: 'signing_unspecified', + reason: RUNNER_STARTUP_FAILURE_REASONS.signingUnspecified.reason, hint: 'Enable Automatic Signing in Xcode or provide AGENT_DEVICE_IOS_TEAM_ID and optional AGENT_DEVICE_IOS_SIGNING_IDENTITY.', }, }, @@ -592,7 +590,7 @@ export const RUNNER_ERROR_RULES: readonly RunnerErrorRule[] = [ match: { code: 'COMMAND_FAILED', details: hasDevToolsSecurityStatus }, verdicts: {}, buildFailure: { - reason: 'devtools_security_developer_mode_disabled', + reason: RUNNER_STARTUP_FAILURE_REASONS.devToolsSecurityDeveloperModeDisabled.reason, hint: 'Run `sudo DevToolsSecurity -enable`, then retry the iOS runner. UI test runners start suspended until Xcode/testmanagerd can attach.', }, }, @@ -868,7 +866,7 @@ export function classifyRunnerStartupFailure(error: unknown): RunnerStartupClass } } return { - reason: RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON, + reason: RUNNER_STARTUP_FAILURE_REASONS.buildFailedUnclassified.reason, hint: RUNNER_CACHE_RECOVERY_HINT, matched: false, }; @@ -876,7 +874,7 @@ export function classifyRunnerStartupFailure(error: unknown): RunnerStartupClass /** * The verdict, the advice beside it, and whether a row reached either (#2690 review). `matched` is - * half the answer rather than an implementation detail: {@link RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON} + * half the answer rather than an implementation detail: `build_failed_unclassified` * is also what a row that deliberately claims no cause publishes, so reading the reason alone cannot * tell "nothing spoke" from "a row spoke and declined to name a cause". */ @@ -943,7 +941,7 @@ export function enrichRunnerStartupFailureWithDeviceStates( ...(error.details ?? {}), ...(speaks ? { - reason: 'device_developer_disk_image_unavailable', + reason: RUNNER_STARTUP_FAILURE_REASONS.deviceDeveloperDiskImageUnavailable.reason, hint: states.developerDiskImageHint, } : {}), @@ -960,7 +958,10 @@ export function enrichRunnerStartupFailureWithDeviceStates( */ function claimedStartupFailureReason(error: AppError): RunnerStartupFailureReason | undefined { const reason = error.details?.reason; - if (typeof reason !== 'string' || reason === RUNNER_STARTUP_FAILURE_UNCLASSIFIED_REASON) { + if ( + typeof reason !== 'string' || + reason === RUNNER_STARTUP_FAILURE_REASONS.buildFailedUnclassified.reason + ) { return undefined; } return reason as RunnerStartupFailureReason; diff --git a/packages/apple-runner/src/runner-launched-session.ts b/packages/apple-runner/src/runner-launched-session.ts index fbd1094444..0aa4322538 100644 --- a/packages/apple-runner/src/runner-launched-session.ts +++ b/packages/apple-runner/src/runner-launched-session.ts @@ -1,4 +1,4 @@ -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { randomUUID } from 'node:crypto'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { Deadline, emitDiagnostic } from './host.ts'; @@ -14,6 +14,15 @@ import { } from './runner-session-types.ts'; import { resolveRunnerLaunchReadinessMs, type RunnerStartBudget } from './runner-start-budget.ts'; +const RUNNER_LAUNCH_REASONS = { + // The runner launcher exited before the runner accepted a connection. + processExited: { reason: 'runner_process_exited' }, + // The runner launcher could not stop its runner process. + terminationFailed: { reason: 'runner_termination_failed' }, + // Reading the runner's output failed while it was starting, so the runner was stopped. + outputFailed: { reason: 'runner_output_failed' }, +} as const satisfies ReasonTable<'apple runner'>; + export async function launchRunnerSession( device: DeviceInfo, launcher: RunnerLauncher, @@ -65,7 +74,7 @@ export async function launchRunnerSession( 'COMMAND_FAILED', 'Runner did not accept connection (launcher exited early)', { - reason: 'runner_process_exited', + reason: RUNNER_LAUNCH_REASONS.processExited.reason, port, logPath: logPath ?? requestedLogPath, output: observation.readLogTail(16_384), @@ -82,7 +91,7 @@ export async function launchRunnerSession( 'COMMAND_FAILED', 'Runner launcher could not terminate its generation', { - reason: 'runner_termination_failed', + reason: RUNNER_LAUNCH_REASONS.terminationFailed.reason, deviceId: device.id, }, error, @@ -143,7 +152,7 @@ export async function refuseFailedRunnerPublication(session: RunnerSession): Pro throw new AppError( 'COMMAND_FAILED', 'Runner output failed during startup', - { reason: 'runner_output_failed', deviceId: session.deviceId }, + { reason: RUNNER_LAUNCH_REASONS.outputFailed.reason, deviceId: session.deviceId }, session.launch.failure, ); } diff --git a/packages/apple-runner/src/runner-lifecycle.ts b/packages/apple-runner/src/runner-lifecycle.ts index 78b35982bb..97dad7a943 100644 --- a/packages/apple-runner/src/runner-lifecycle.ts +++ b/packages/apple-runner/src/runner-lifecycle.ts @@ -6,6 +6,7 @@ import { discloseUnclassifiedDispatch, isRequestCanceledError, type DispatchDisclosure, + type ReasonTable, } from '@agent-device/kernel/errors'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { ReadinessPhase } from '@agent-device/contracts/wait'; @@ -60,6 +61,14 @@ import { tryBeginRunnerRecycle, } from './runner-recycle-ledger.ts'; +const RUNNER_PREPARE_REASONS = { + // `prepare ios-runner` ran out of its deadline before the named `details.phase` began. + deadlineExpired: { reason: 'prepare_deadline_expired' }, + // The cached runner failed its health check, and the rebuilt runner failed it too; + // `details.rebuiltFailureMessage` says how. + rebuiltRunnerUnhealthy: { reason: 'prepare_rebuilt_runner_unhealthy' }, +} as const satisfies ReasonTable<'prepare'>; + export type PrepareIosRunnerOptions = AppleRunnerPrepareOptions; export type PrepareIosRunnerResult = AppleRunnerPrepareResult; @@ -628,7 +637,7 @@ function readPreparePhaseTimeoutMs( if (remainingMs <= 0) { throw new AppError('COMMAND_FAILED', 'prepare ios-runner timed out', { phase, - reason: 'prepare_deadline_expired', + reason: RUNNER_PREPARE_REASONS.deadlineExpired.reason, }); } return remainingMs; @@ -668,7 +677,11 @@ function wrapPrepareHealthFailure( xctestrunPath: session.xctestrunArtifact?.xctestrunPath, artifact: session.xctestrunArtifact?.artifact, cache: session.xctestrunArtifact?.cache, - reason: appErr.message, + reason: RUNNER_PREPARE_REASONS.rebuiltRunnerUnhealthy.reason, + rebuiltFailureMessage: appErr.message, + ...(typeof appErr.details?.reason === 'string' + ? { rebuiltFailureReason: appErr.details.reason } + : {}), }, appErr, ); diff --git a/packages/apple-runner/src/runner-macos-products.ts b/packages/apple-runner/src/runner-macos-products.ts index 9250b575ba..368c0bb5ec 100644 --- a/packages/apple-runner/src/runner-macos-products.ts +++ b/packages/apple-runner/src/runner-macos-products.ts @@ -1,12 +1,19 @@ import fs from 'node:fs'; import path from 'node:path'; import { isMacOs, type DeviceInfo } from '@agent-device/kernel/device'; -import { AppError, asAppError } from '@agent-device/kernel/errors'; +import { AppError, asAppError, type ReasonTable } from '@agent-device/kernel/errors'; import { runAppleToolCommand } from './host.ts'; -const RUNNER_PRODUCT_REPAIR_FAILURE_REASONS = new Set([ - 'RUNNER_PRODUCT_MISSING', - 'RUNNER_PRODUCT_REPAIR_FAILED', +const RUNNER_MACOS_PRODUCT_REASONS = { + // The macOS runner's xctestrun file names no product to launch. + productMissing: { reason: 'RUNNER_PRODUCT_MISSING' }, + // The signature of a macOS runner product could not be repaired. + productRepairFailed: { reason: 'RUNNER_PRODUCT_REPAIR_FAILED' }, +} as const satisfies ReasonTable<'apple runner'>; + +const RUNNER_PRODUCT_REPAIR_FAILURE_REASONS = new Set([ + RUNNER_MACOS_PRODUCT_REASONS.productMissing.reason, + RUNNER_MACOS_PRODUCT_REASONS.productRepairFailed.reason, ]); const AD_HOC_RESIGN_ARGS = [ @@ -27,7 +34,7 @@ export async function repairMacOsRunnerProductsIfNeeded( } if (productPaths.length === 0) { throw new AppError('COMMAND_FAILED', 'Missing macOS runner product', { - reason: 'RUNNER_PRODUCT_MISSING', + reason: RUNNER_MACOS_PRODUCT_REASONS.productMissing.reason, xctestrunPath, }); } @@ -37,7 +44,7 @@ export async function repairMacOsRunnerProductsIfNeeded( for (const productPath of sortedProductPaths) { if (!fs.existsSync(productPath)) { throw new AppError('COMMAND_FAILED', 'Missing macOS runner product', { - reason: 'RUNNER_PRODUCT_MISSING', + reason: RUNNER_MACOS_PRODUCT_REASONS.productMissing.reason, productPath, xctestrunPath, }); @@ -86,7 +93,7 @@ function repairFailure( details?: unknown, ): AppError { return new AppError('COMMAND_FAILED', 'Failed to repair macOS runner product signature', { - reason: 'RUNNER_PRODUCT_REPAIR_FAILED', + reason: RUNNER_MACOS_PRODUCT_REASONS.productRepairFailed.reason, productPath, xctestrunPath, error, diff --git a/packages/apple-runner/src/runner-phase-budget.ts b/packages/apple-runner/src/runner-phase-budget.ts index 73854c3153..eeb0bbae06 100644 --- a/packages/apple-runner/src/runner-phase-budget.ts +++ b/packages/apple-runner/src/runner-phase-budget.ts @@ -1,6 +1,11 @@ -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import { Deadline } from './host.ts'; +const RUNNER_PHASE_BUDGET_REASONS = { + // The Apple runner's budget ran out before the step in `details.phase` began; retry. + phaseBudgetExhausted: { reason: 'runner_phase_budget_exhausted' }, +} as const satisfies ReasonTable<'apple runner'>; + /** * Everything one runner phase may spend: the single clock every step of the phase reads, * and the owning request's cancellation. Created once, where the phase begins, and handed @@ -48,7 +53,7 @@ export function requireRunnerPhaseRemainingMs( function runnerPhaseBudgetExhaustedError(phase: string): AppError { return new AppError('COMMAND_FAILED', 'The Apple runner budget ran out before this step began', { phase, - reason: 'runner_phase_budget_exhausted', + reason: RUNNER_PHASE_BUDGET_REASONS.phaseBudgetExhausted.reason, retriable: true, }); } diff --git a/packages/apple-runner/src/runner-sequence.ts b/packages/apple-runner/src/runner-sequence.ts index f9cf022723..785f4008ef 100644 --- a/packages/apple-runner/src/runner-sequence.ts +++ b/packages/apple-runner/src/runner-sequence.ts @@ -5,7 +5,11 @@ import { runnerSynthesizesTap, type DeviceInfo, } from '@agent-device/kernel/device'; -import { AppError, discloseDispatchAfterSteps } from '@agent-device/kernel/errors'; +import { + AppError, + discloseDispatchAfterSteps, + type ReasonTable, +} from '@agent-device/kernel/errors'; import { MAX_RUNNER_SEQUENCE_STEPS, buildRunnerSequenceCommand, @@ -15,6 +19,11 @@ import { type RunnerSequenceStep, } from './runner-contract.ts'; +const RUNNER_SEQUENCE_REASONS = { + // The runner did not report the orientation of a press series; inspect the screen before continuing. + orientationUnavailable: { reason: 'runner_sequence_orientation_unavailable' }, +} as const satisfies ReasonTable<'apple runner'>; + /** * Wall-clock budget for one sequence request. The runner executes a complete chunk inside one * main-thread block guarded by a 30s watchdog, so chunking leaves headroom below that boundary. @@ -92,7 +101,7 @@ function requirePressSeriesOrientation( if (orientation !== undefined) return orientation; throw discloseDispatchAfterSteps( new AppError('COMMAND_FAILED', 'The runner did not return the press series orientation', { - reason: 'runner_sequence_orientation_unavailable', + reason: RUNNER_SEQUENCE_REASONS.orientationUnavailable.reason, completedSteps, hint: 'Run snapshot -i to inspect the current UI before continuing with the remaining actions.', }), diff --git a/packages/apple-runner/src/runner-session.ts b/packages/apple-runner/src/runner-session.ts index 854bbd882f..54db700b59 100644 --- a/packages/apple-runner/src/runner-session.ts +++ b/packages/apple-runner/src/runner-session.ts @@ -37,6 +37,7 @@ import { type RunnerCommand, mintRunnerToken, runnerListenerEnv, + RUNNER_ERROR_REASONS, type RunnerEndpoint, } from './runner-contract.ts'; import { enrichRunnerStartupFailureWithDeviceStates } from './runner-error-classification.ts'; @@ -435,7 +436,7 @@ function runnerSessionOwnershipChanged(): AppError { return new AppError( 'COMMAND_FAILED', 'Apple runner session ownership changed before command dispatch', - { reason: 'runner_session_ownership_changed' }, + { reason: RUNNER_ERROR_REASONS.sessionOwnershipChanged.reason }, ); } diff --git a/packages/apple-runner/src/runner-start-budget.ts b/packages/apple-runner/src/runner-start-budget.ts index 73b9bff730..adcb3d2613 100644 --- a/packages/apple-runner/src/runner-start-budget.ts +++ b/packages/apple-runner/src/runner-start-budget.ts @@ -3,6 +3,7 @@ import { AppError, createRequestCanceledError, isRequestCanceledError, + type ReasonTable, } from '@agent-device/kernel/errors'; import { emitDiagnostic } from './host.ts'; import { isCallerDeadlineAbortReason, resolveRunnerStartupSignal } from './runner-contract.ts'; @@ -20,6 +21,11 @@ import { stopRunnerPrepProcessesWithoutLiveOwner } from './runner-disposal.ts'; import { normalizeRunnerStartupTimeoutMs, type RunnerSession } from './runner-session-types.ts'; import type { AppleRunnerLifecycleOptions } from './runner-provider.ts'; +const RUNNER_START_BUDGET_REASONS = { + // Starting the Apple runner took longer than its start budget; the next request starts over. + startBudgetExhausted: { reason: 'runner_start_budget_exhausted' }, +} as const satisfies ReasonTable<'apple runner'>; + type RunnerSessionOptions = AppleRunnerLifecycleOptions; /** @@ -81,7 +87,7 @@ function runnerStartBudgetExhaustedError(timeoutMs: number, explicit: boolean): 'COMMAND_FAILED', `Apple runner start exceeded its ${explicit ? 'startup timeout' : 'default start budget'} of ${timeoutMs}ms`, { - reason: 'runner_start_budget_exhausted', + reason: RUNNER_START_BUDGET_REASONS.startBudgetExhausted.reason, timeoutMs, retriable: true, hint: explicit diff --git a/packages/apple-runner/src/runner-toolchain-identity.ts b/packages/apple-runner/src/runner-toolchain-identity.ts index aae7a07797..561c0d9d56 100644 --- a/packages/apple-runner/src/runner-toolchain-identity.ts +++ b/packages/apple-runner/src/runner-toolchain-identity.ts @@ -1,8 +1,17 @@ import fs from 'node:fs'; import path from 'node:path'; -import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; +import { + AppError, + createRequestCanceledError, + type ReasonTable, +} from '@agent-device/kernel/errors'; import { commandDeveloperDir } from './host.ts'; +const RUNNER_TOOLCHAIN_REASONS = { + // The Xcode toolchain version files the runner cache is keyed on could not be read. + toolchainUnreadable: { reason: 'apple_toolchain_unreadable' }, +} as const satisfies ReasonTable<'apple runner'>; + /** * Apple toolchain identity, read from the files that `xcodebuild -version`, `xcrun * --show-sdk-version`, and `xcrun --show-sdk-build-version` print from. Nothing here execs: a @@ -94,7 +103,7 @@ export function requireRunnerToolchainFingerprint( 'COMMAND_FAILED', `Could not read the Xcode toolchain versions the Apple runner cache is keyed on (${error.message})`, { - reason: 'apple_toolchain_unreadable', + reason: RUNNER_TOOLCHAIN_REASONS.toolchainUnreadable.reason, ...(chosenDir === undefined ? {} : { developerDir: chosenDir }), file: error.file, detail: error.detail, diff --git a/packages/apple-runner/src/runner-transport.ts b/packages/apple-runner/src/runner-transport.ts index 2657af38ed..4fa663a2b7 100644 --- a/packages/apple-runner/src/runner-transport.ts +++ b/packages/apple-runner/src/runner-transport.ts @@ -9,7 +9,10 @@ import { createRunnerCommandRouteResolver, type RunnerCommandRoute, } from './runner-command-route.ts'; -import { isUsbmuxDeviceUnattachedError } from './runner-error-classification.ts'; +import { + isUsbmuxDeviceUnattachedError, + RUNNER_EXCHANGE_REASONS, +} from './runner-error-classification.ts'; import { type RunnerCommand, requireTokenEnforcingRunner, @@ -115,7 +118,7 @@ export async function postRunnerCommandOverRoute( if (endpoint.http && [502, 503, 504].includes(response.status)) { await response.body?.cancel(); throw new AppError('COMMAND_FAILED', 'Runner HTTP forwarding is unavailable', { - reason: 'runner_forwarding_unavailable', + reason: RUNNER_EXCHANGE_REASONS.forwardingUnavailable.reason, status: response.status, }); } diff --git a/test/repo-guards/runner-refusal-reason-docs.test.ts b/test/repo-guards/runner-refusal-reason-docs.test.ts index 157d5dc014..d4caa1bedb 100644 --- a/test/repo-guards/runner-refusal-reason-docs.test.ts +++ b/test/repo-guards/runner-refusal-reason-docs.test.ts @@ -1,5 +1,7 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; +import { memberPath } from '../../scripts/layering/layering-ast.ts'; +import { collectReasonTables } from '../../scripts/reasons/collect.ts'; import { exportedConstObject, parseTs, @@ -11,11 +13,13 @@ import { * `error.details.reason` is a published vocabulary: a client that branches on it treats an * undocumented member as an unknown value. Every exported typed published-reason table must have * each reason documented at the surfaces that enumerate it, in the same change that adds it. - * Tables are read as typed syntax (oxc), so an unreadable member fails here instead of being dropped. + * Reason tables are read by the collector the reasons page uses; the runner code rows, which are not a + * reason table, and the claim-conflict union are read as typed syntax (oxc), so an unreadable member + * fails here instead of being dropped. */ type Surface = Readonly<{ name: string; relativePath: string }>; -type Kind = 'rows' | 'object' | 'union'; +type Kind = 'table' | 'runnerCodes' | 'union'; const commandsDoc: Surface = { name: 'commands.md', relativePath: 'website/docs/docs/commands.md' }; const cliHelpWorkflows: Surface = { name: 'cli-help-workflows.ts', @@ -30,15 +34,15 @@ const reasonTable = ( ) => ({ name, relativePath, kind, surfaces }); const REASON_TABLES = [ - reasonTable('RUNNER_ERROR_CODES', 'packages/apple-runner/src/runner-contract.ts', 'rows'), - reasonTable('PRE_DISPATCH_REFUSAL_REASONS', 'packages/kernel/src/errors.ts', 'rows'), - reasonTable('SCROLL_REASONS', 'packages/contracts/src/scroll-reasons.ts', 'rows'), + reasonTable('RUNNER_ERROR_CODES', 'packages/apple-runner/src/runner-contract.ts', 'runnerCodes'), + reasonTable('PRE_DISPATCH_REFUSAL_REASONS', 'packages/kernel/src/errors.ts', 'table'), + reasonTable('SCROLL_REASONS', 'packages/contracts/src/scroll-reasons.ts', 'table'), reasonTable( 'ANDROID_SCREEN_RECORDING_REASONS', 'packages/contracts/src/screen-recording-runtime-host.ts', - 'rows', + 'table', ), - reasonTable('WAIT_REASONS', 'packages/contracts/src/wait.ts', 'rows', [ + reasonTable('WAIT_REASONS', 'packages/contracts/src/wait.ts', 'table', [ commandsDoc, cliHelpWorkflows, ]), @@ -77,55 +81,59 @@ test('a documented reason does not stand in for a longer undocumented one', () = test('the extractors read every member and reject unsupported ones instead of dropping them', () => { const read = (source: string, name: string, kind: Kind) => - readReasons(source, 'fixture.ts', name, kind); + readReasons(source, 'packages/a/src/table.ts', name, kind); const expectRead = (source: string, name: string, kind: Kind, expected: string[]) => assert.deepEqual(read(source, name, kind), expected); const expectReject = (source: string, name: string, kind: Kind, pattern: RegExp) => assert.throws(() => read(source, name, kind), pattern); + const codes = (reason: string) => + `export const R = { + // Busy. + busy: { reason: 'runner_busy' } } as const satisfies ReasonTable<'r'>; + export const RUNNER_ERROR_CODES = { RUNNER_BUSY: { dispatched: 'no', reason: ${reason} }, RUNNER_WEDGED: { dispatched: 'no' } } as const satisfies Record;`; - expectRead( - `export const RUNNER_ERROR_CODES = { - RUNNER_BUSY: { dispatched: 'no', reason: 'runner_busy' }, - RUNNER_WEDGED: { dispatched: 'no' }, - } as const satisfies Record;`, - 'RUNNER_ERROR_CODES', - 'rows', - ['runner_busy'], - ); + expectRead(codes('R.busy.reason'), 'RUNNER_ERROR_CODES', 'runnerCodes', ['runner_busy']); expectReject( - `export const RUNNER_ERROR_CODES = { RUNNER_BUSY: { dispatched: 'no', reason: R.busy } } as const satisfies Record;`, + codes('R.gone.reason'), 'RUNNER_ERROR_CODES', - 'rows', - /unsupported reason in RUNNER_ERROR_CODES row RUNNER_BUSY/, - ); - expectRead( - `export const WAIT_REASONS = { captureStalled: 'wait_capture_stalled', deadlineExceeded: "wait_deadline_exceeded" } as const;`, - 'WAIT_REASONS', - 'object', - ['wait_capture_stalled', 'wait_deadline_exceeded'], + 'runnerCodes', + /RUNNER_ERROR_CODES row RUNNER_BUSY must write its reason as a literal or read it from a reason table row/, ); - for (const member of ['computeReason()']) { + expectRead(codes("'runner_busy'"), 'RUNNER_ERROR_CODES', 'runnerCodes', ['runner_busy']); + for (const row of [ + 'RUNNER_BUSY: BUSY_ROW', + 'RUNNER_BUSY: { ...BUSY_ROW }', + '...COMMON', + "[CODE]: { reason: 'x' }", + ]) { expectReject( - `export const WAIT_REASONS = { a: ${member} } as const;`, - 'WAIT_REASONS', - 'object', - /unsupported member in WAIT_REASONS/, + `export const RUNNER_ERROR_CODES = { ${row} } as const;`, + 'RUNNER_ERROR_CODES', + 'runnerCodes', + /must be an object literal of named members/, ); } + expectRead( + `export const WAIT_REASONS = { + // Stalled. + captureStalled: { reason: 'wait_capture_stalled' }, + } as const satisfies ReasonTable<'wait'>;`, + 'WAIT_REASONS', + 'table', + ['wait_capture_stalled'], + ); expectRead( `export type DeviceClaimConflictReason = 'DEVICE_CLAIM_LIVE_OWNER' | 'DEVICE_CLAIM_OWNER_UNCERTAIN';`, 'DeviceClaimConflictReason', 'union', ['DEVICE_CLAIM_LIVE_OWNER', 'DEVICE_CLAIM_OWNER_UNCERTAIN'], ); - for (const member of ['string']) { - expectReject( - `export type DeviceClaimConflictReason = ${member};`, - 'DeviceClaimConflictReason', - 'union', - /unsupported member in DeviceClaimConflictReason/, - ); - } + expectReject( + `export type DeviceClaimConflictReason = string;`, + 'DeviceClaimConflictReason', + 'union', + /unsupported member in DeviceClaimConflictReason/, + ); }); /** Whether `docs` names `reason` as a whole token, so a longer reason that extends it does not count. */ @@ -134,15 +142,61 @@ function documentsReason(docs: string, reason: string): boolean { return new RegExp(`(? candidate.name === name); + assert.ok(table, `${filename} must declare the ${name} reason table`); + return table.rows.map(({ reason }) => reason); + } + return readRunnerCodeReasons(parseTs(filename, source), tables, name); +} + +/** + * The reasons the rows of the runner code table publish. A row writes its reason as + * a literal or `TABLE.member.reason`, which must name a row of a reason table in the same file. + */ +function readRunnerCodeReasons( + parsed: ReturnType, + tables: ReturnType, name: string, - kind: 'rows' | 'object' | 'union', ): string[] { - if (kind === 'union') return readUnionReasons(parseTs(filename, source), filename, name); - return readTableReasons(exportedConstObject(parseTs(filename, source), name), name, kind); + return exportedConstObject(parsed, name).properties.flatMap((property: any) => { + const row = readRunnerCodeRow(name, property); + const reason = row.properties.find((member: any) => member.key.name === 'reason'); + if (reason === undefined) return []; + if (reason.value.type === 'Literal' && typeof reason.value.value === 'string') { + return [reason.value.value]; + } + const [table, member, field] = memberPath(reason.value) ?? []; + const found = tables + .find((candidate) => candidate.name === table) + ?.rows.find((candidate) => candidate.member === member); + assert.ok( + field === 'reason' && found !== undefined, + `${name} row ${property.key.name} must write its reason as a literal or read it from a reason table row as TABLE.member.reason.`, + ); + return [found.reason]; + }); +} + +/** A RUNNER_ERROR_CODES row written as a plain object of named members, or a failed assertion. */ +function readRunnerCodeRow(name: string, property: any): any { + const row = property.type === 'Property' ? unwrapAssertion(property.value) : undefined; + const label = property.key?.name ?? property.type; + assert.ok( + property.key?.type === 'Identifier' && + !property.computed && + row?.type === 'ObjectExpression' && + row.properties.every( + (member: any) => + member.type === 'Property' && member.key.type === 'Identifier' && !member.computed, + ), + `${name} row ${label} must be an object literal of named members, so its reason can be read.`, + ); + return row; } /** The string members of an exported `type Name = 'a' | 'b'` union. */ @@ -173,45 +227,3 @@ function readUnionReasons( return member.literal.value; }); } - -/** The reasons of an exported const table: each row's `reason`, or each member's literal. */ -function readTableReasons( - table: ReturnType, - name: string, - kind: 'rows' | 'object', -): string[] { - const members: string[] = []; - for (const property of table.properties) { - assert.ok( - property.type === 'Property' && property.key.type === 'Identifier', - `unsupported member in ${name}: ${property.type}`, - ); - if (kind === 'object') { - assert.ok( - property.value.type === 'Literal' && typeof property.value.value === 'string', - `unsupported member in ${name}: ${property.value.type}`, - ); - members.push(property.value.value); - continue; - } - const row = unwrapAssertion(property.value); - assert.ok( - row?.type === 'ObjectExpression', - `unsupported row in ${name} for ${property.key.name}: ${row?.type ?? 'none'}`, - ); - for (const member of row.properties) { - if ( - member.type !== 'Property' || - member.key.type !== 'Identifier' || - member.key.name !== 'reason' - ) - continue; - assert.ok( - member.value.type === 'Literal' && typeof member.value.value === 'string', - `unsupported reason in ${name} row ${property.key.name}: ${member.value.type}`, - ); - members.push(member.value.value); - } - } - return members; -} diff --git a/test/repo-guards/runner-startup-reason-docs.test.ts b/test/repo-guards/runner-startup-reason-docs.test.ts index e85d292628..d807e28653 100644 --- a/test/repo-guards/runner-startup-reason-docs.test.ts +++ b/test/repo-guards/runner-startup-reason-docs.test.ts @@ -3,13 +3,13 @@ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { test } from 'vitest'; -import { parseSync } from 'oxc-parser'; +import { collectReasonTables } from '../../scripts/reasons/collect.ts'; /** * `error.details.reason` is a published vocabulary: a client that branches on it treats an * undocumented member as an unknown value. Nothing but this file connects the union to the two * surfaces that enumerate it, so a new reason added to the classifier has to be documented in the - * same change. The reason union is the source of truth; the docs are read as text because they carry + * same change. The reason table is the source of truth; the docs are read as text because they carry * the prose a reader follows, not a machine-readable list. */ @@ -39,70 +39,15 @@ test('the runner startup reason union is documented in full at both prose surfac } }); -test('startup reason extraction includes alternate quotes, digits, hyphens and readiness spreads', () => { - assert.deepEqual( - startupFailureReasons(` - export const RUNNER_DEVICE_READINESS_FAILURE_REASONS = ["ready-3"] as const; - export const RUNNER_STARTUP_FAILURE_REASONS = [ - "phase-2", ...RUNNER_DEVICE_READINESS_FAILURE_REASONS, - ] as const; - `), - ['phase-2', 'ready-3'], - ); -}); - -test('startup reason extraction rejects every unsupported member instead of dropping it', () => { - for (const member of ['...UNKNOWN_REASONS', 'computeReason()', '42', ',']) { - assert.throws( - () => - startupFailureReasons( - `export const RUNNER_STARTUP_FAILURE_REASONS = [${member}] as const;`, - ), - /unsupported member in RUNNER_STARTUP_FAILURE_REASONS/, - ); - } - assert.throws( - () => - startupFailureReasons(` - export const RUNNER_DEVICE_READINESS_FAILURE_REASONS = [...UNKNOWN_REASONS] as const; - export const RUNNER_STARTUP_FAILURE_REASONS = [...RUNNER_DEVICE_READINESS_FAILURE_REASONS] as const; - `), - /unsupported member in RUNNER_DEVICE_READINESS_FAILURE_REASONS/, - ); -}); - +/** The rows of the RUNNER_STARTUP_FAILURE_REASONS reason table, read as the reasons page reads them. */ function startupFailureReasons(source: string): string[] { - const parsed = parseSync(classificationPath, source); - assert.deepEqual(parsed.errors, [], 'startup reason source must parse'); - const declarations = parsed.program.body.flatMap((statement) => - statement.type === 'ExportNamedDeclaration' && - statement.declaration?.type === 'VariableDeclaration' - ? statement.declaration.declarations - : [], + const file = path.relative(repoRoot, classificationPath); + const table = collectReasonTables(new Map([[file, source]])).find( + ({ name }) => name === 'RUNNER_STARTUP_FAILURE_REASONS', ); - const startup = 'RUNNER_STARTUP_FAILURE_REASONS'; - const readiness = 'RUNNER_DEVICE_READINESS_FAILURE_REASONS'; - function members(name: string): string[] { - const declaration = declarations.find(({ id }) => id.type === 'Identifier' && id.name === name); - assert.ok(declaration, `missing exported declaration ${name}`); - const initializer = - declaration.init?.type === 'TSAsExpression' ? declaration.init.expression : declaration.init; - assert.ok(initializer?.type === 'ArrayExpression', `${name} must be an array literal`); - return initializer.elements.flatMap((member) => { - if (member?.type === 'Literal' && typeof member.value === 'string') return [member.value]; - if ( - name === startup && - member?.type === 'SpreadElement' && - member.argument.type === 'Identifier' && - member.argument.name === readiness - ) - return members(readiness); - assert.fail(`unsupported member in ${name}: ${member?.type ?? 'array hole'}`); - }); - } - const reasons = members(startup); - assert.ok(reasons.length > 0, 'the startup reason union must not be empty'); - return reasons; + assert.ok(table, `${file} must declare the RUNNER_STARTUP_FAILURE_REASONS reason table`); + assert.ok(table.rows.length > 0, 'the startup reason table must not be empty'); + return table.rows.map(({ reason }) => reason); } /** The sentence that enumerates the startup reasons, found on the same line at both surfaces. */ diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 108594e953..29bf60b2d2 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -15,8 +15,18 @@ Treat a reason that this page does not list as unknown, not as an error in the r | Reason | Meaning | | --- | --- | +| `native_audit_blocked_by_alert` | Apple's audit failed while a system alert covered the app; answer the alert, then retry. | | `native-audit-invalid-result` | The runner answered the native audit with a missing or malformed result. | +### `back` + +| Reason | Meaning | +| --- | --- | +| `back_swipe_no_change` | The back swipe ran and left the app's screen unchanged. | +| `back_swipe_unverified` | The back swipe ran, but the screen was already changing or could not be sampled afterwards. | +| `back_swipe_not_dispatched` | The back swipe was refused before it reached the device. | +| `in_app_back_control_unavailable` | On macOS, the app's accessibility tree exposes no in-app back control. | + ### `clipboard` | Reason | Meaning | @@ -42,6 +52,8 @@ Treat a reason that this page does not list as unknown, not as an error in the r | Reason | Meaning | | --- | --- | +| `no_text_input_at_point` | A coordinate `fill` point identified no text input, so nothing was tapped or typed. | +| `text_input_probe_unavailable` | The runner could not tell whether a coordinate `fill` point holds a text input; nothing was tapped. | | `android_shell_text_unsupported` | The adb-shell fallback carries ASCII text only; a helper or provider channel is needed. | | `android_ime_helper_no_ack` | The test IME helper gave no evidence it attempted the dispatch, so nothing is proven typed. | | `android_ime_helper_dispatch_rejected` | The test IME helper answered that it rejected the dispatch, so nothing was typed. | @@ -112,6 +124,13 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `plugin_setup_failed` | The plugin's `setup(host)` threw, or registering what it returned failed. | | `reserved_provider` | A plugin claims a provider id reserved for daemon routing, `cloud` or `proxy`. | +### `prepare` + +| Reason | Meaning | +| --- | --- | +| `prepare_deadline_expired` | `prepare ios-runner` ran out of its deadline before the named `details.phase` began. | +| `prepare_rebuilt_runner_unhealthy` | The cached runner failed its health check, and the rebuilt runner failed it too; `details.rebuiltFailureMessage` says how. | + ### `proxy` | Reason | Meaning | @@ -323,6 +342,45 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | +| `runner_build_settings_mismatch` | The runner build used settings other than those its cache identity records. | +| `runner_cache_uncertifiable` | The runner build products cannot be certified for cache reuse; `details.refusalReason` says why. | +| `runner_busy` | The runner was still busy with an earlier command and refused this one; retry it. | +| `runner_main_thread_timeout` | The command's work on the app's main thread did not finish in time, so it may have run. | +| `no_text_input_at_point` | A coordinate `fill` point identified no text input, so nothing was tapped or typed. | +| `text_input_probe_unavailable` | The runner could not tell whether a coordinate `fill` point holds a text input; nothing was tapped. | +| `synthesized_gesture_not_dispatched` | The runner refused the gesture before its events reached XCTest, so nothing was sent. | +| `synthesized_gesture_outcome_unknown` | The gesture failed after its events reached XCTest, so it may have run. | +| `back_swipe_no_change` | The back swipe ran and left the app's screen unchanged. | +| `back_swipe_unverified` | The back swipe ran, but the screen was already changing or could not be sampled afterwards. | +| `back_swipe_not_dispatched` | The back swipe was refused before it reached the device. | +| `keyboard_return_unavailable` | A Return on the focused input could not be confirmed; a tap on the field may have landed. | +| `hardware_control_unavailable` | The target has no such hardware control, such as an Action Button, so nothing was pressed. | +| `in_app_back_control_unavailable` | On macOS, the app's accessibility tree exposes no in-app back control. | +| `native_audit_blocked_by_alert` | Apple's audit failed while a system alert covered the app; answer the alert, then retry. | +| `runner_token_unsupported` | The runner build does not require a listener token; rebuild it with this agent-device version. | +| `runner_sequence_invalid` | The daemon refused a runner action sequence before sending it, so nothing reached the device. | +| `runner_session_ownership_changed` | Another request took over the Apple runner session before this command was sent. | +| `runner_reply_lost` | A mutation's reply was lost and status recovery found no result, so it may have run; observe the screen before acting again. | +| `runner_forwarding_unavailable` | The HTTP forwarder in front of the runner answered 502, 503 or 504. | +| `bundle_identifier_already_registered` | The runner's bundle identifier is taken; set AGENT_DEVICE_IOS_BUNDLE_ID to a unique value. | +| `signing_no_development_team` | The runner build needs a development team for signing. | +| `signing_provisioning_profile_missing` | No installed provisioning profile covers the runner, or the one found is unusable. | +| `signing_unspecified` | The runner build failed on code signing for a cause the output does not name. | +| `devtools_security_developer_mode_disabled` | DevToolsSecurity is disabled on the host, so the UI test runner cannot be attached. | +| `simulator_service_hub_unavailable` | macOS refused to load this Xcode's simulator service; select an Xcode that supports this macOS. | +| `simulator_set_destination_not_found` | xcodebuild found no simulator with this id in the requested simulator set. | +| `device_developer_mode_disabled` | Developer Mode is off on the physical device, so it refuses the runner. | +| `device_developer_disk_image_unavailable` | The physical device reports no developer disk image, and the runner build named no other cause. | +| `build_failed_unclassified` | The runner did not start and no rule proves a cause; the hint gives the cache-recovery steps. | +| `runner_process_exited` | The runner launcher exited before the runner accepted a connection. | +| `runner_termination_failed` | The runner launcher could not stop its runner process. | +| `runner_output_failed` | Reading the runner's output failed while it was starting, so the runner was stopped. | +| `RUNNER_PRODUCT_MISSING` | The macOS runner's xctestrun file names no product to launch. | +| `RUNNER_PRODUCT_REPAIR_FAILED` | The signature of a macOS runner product could not be repaired. | +| `runner_phase_budget_exhausted` | The Apple runner's budget ran out before the step in `details.phase` began; retry. | +| `runner_sequence_orientation_unavailable` | The runner did not report the orientation of a press series; inspect the screen before continuing. | +| `runner_start_budget_exhausted` | Starting the Apple runner took longer than its start budget; the next request starts over. | +| `apple_toolchain_unreadable` | The Xcode toolchain version files the runner cache is keyed on could not be read. | | `apple_runner_host_unbound` | The Apple runner was asked for its host before the daemon bound one. | ### Artifact extraction