Skip to content

Commit a06b951

Browse files
committed
fix(ios): refuse every runner read over a not-running session app
The refusal now keys on the runner's own read trait, not on a host-stamped per-request mark: isReadOnlyCommand covers findText, readText, snapshot, gestureViewport, and alert get, so a mutation's leading read -- the viewport read a gesture starts with, the capture that resolves a selector click/fill -- refuses with APP_NOT_RUNNING exactly like a user-level read. A bare activate over a launch SpringBoard holds behind its "Open in ...?" confirmation is a launch without the URL, whatever command asked for the read. The daemon-side request-app-intent plumbing and the observationOnly wire field are removed: the runner's command trait table is the single source of the rule. The refusal stays retriable for a wait poll while the transport reads it as a definite answer; open, activate, and interactions that mutate without a leading read keep the foreground repair. This adopts the rule picked in the #2852 review (option 1) and says so in the CHANGELOG, the foreground-repairs docs section, and the physical-device help topic's lifecycle facts.
1 parent fd8277e commit a06b951

11 files changed

Lines changed: 174 additions & 5 deletions

File tree

‎.github/workflows/ios.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,9 @@ jobs:
157157
-only-testing:AgentDeviceRunnerUITests/RunnerTests/testRecordStartThrowsTheCaptureRefusalItReceived \
158158
-only-testing:AgentDeviceRunnerUITests/RunnerTests/testAlertDispatchResolvesItsOwnModalWithoutCoordinateTapRoutingProbe \
159159
-only-testing:AgentDeviceRunnerUITests/RunnerTests/testAlertResolutionCannotBypassRequestedDeadline \
160+
-only-testing:AgentDeviceRunnerUITests/RunnerTests/testObservationRefusesANotRunningSessionAppInsteadOfLaunchingIt \
161+
-only-testing:AgentDeviceRunnerUITests/RunnerTests/testInteractionLeadingReadRefusesToLaunchANotRunningSessionApp \
162+
-only-testing:AgentDeviceRunnerUITests/RunnerTests/testNonReadCommandStillLaunchesANotRunningSessionApp \
160163
-only-testing:AgentDeviceRunnerUITests/RunnerTests/testTypeWithoutResolvedInputReturnsTypedFailureBeforeDispatchingText \
161164
-only-testing:AgentDeviceRunnerUITests/RunnerTests/testBareTypeUsesTappedInputWhenSoftwareKeyboardIsHidden \
162165
-only-testing:AgentDeviceRunnerUITests/RunnerTests/testHardwareKeyboardResponderConfirmsItsOwnKeyboardFocus \

‎CHANGELOG.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,17 @@
3333
config that sets `screenshotFullscreen` for one of those surfaces now fails instead of succeeding
3434
with the same image it always produced; drop the flag there. macOS app sessions and every other
3535
platform keep accepting `--fullscreen` unchanged. (#2799)
36+
- Fixed (ios): no runner read launches a session app that is not running anymore. The XCTest runner
37+
repaired foreground loss by calling `activate()`, which launches an app that is not running. After
38+
`open <app> --relaunch --launch-url <url>` on a Simulator, iOS can hold the launch behind an
39+
"Open in …?" confirmation, and the first read of the waiting session launched the app without the
40+
URL. Reads — `snapshot`, `wait`, `is`, `get`, a reading `find`, and an interaction's leading reads
41+
(the viewport read a `gesture` starts with, the capture that resolves a selector `click`/`fill`) —
42+
now refuse with `COMMAND_FAILED`, `details.runnerErrorCode: "APP_NOT_RUNNING"`, `retriable: true`
43+
and a hint to answer the prompt with `alert accept` or relaunch with `open`. A `wait` polls
44+
through the refusal; the runner transport never resends it. Interactions that mutate without a
45+
leading read (`press`, a coordinate `fill`, `swipe`, `scroll`, hardware keys) keep the foreground
46+
repair and still bring a stopped app up.
3647
- Fixed (ios): a local Simulator snapshot taken through the host AX bridge once again publishes the
3748
geometric `hittable` fact, so `is hittable` and a `hittable:` selector resolve the same controls on
3849
the bridge and the XCTest runner. The snapshot capability table has declared `hittable =

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,11 @@ extension RunnerTests {
441441
let normalizedBundleId = command.appBundleId?
442442
.trimmingCharacters(in: .whitespacesAndNewlines)
443443
let requestedBundleId = (normalizedBundleId?.isEmpty == true) ? nil : normalizedBundleId
444+
if let bundleId = requestedBundleId,
445+
let notRunning = notRunningReadResponse(command: command, bundleId: bundleId)
446+
{
447+
return .response(notRunning)
448+
}
444449
if let bundleId = requestedBundleId {
445450
if currentBundleId != bundleId || currentApp == nil {
446451
_ = activateTarget(bundleId: bundleId, reason: "bundle_changed")

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,36 @@ extension RunnerTests {
316316
return foreign.count == 1 ? foreign.first : nil
317317
}
318318

319+
/// Refuses a runner read whose session app is not running, keyed on the runner's own read trait.
320+
/// No runner read launches the app — not a user-level read, and not a mutation's leading read:
321+
/// a gesture's `gestureViewport` and the capture that resolves a selector click are reads too.
322+
/// `activate()` on an app that is not running is a bare launch, which would start it without the
323+
/// URL of a launch SpringBoard still holds behind its "Open in …?" confirmation. The refusal is
324+
/// retriable so a `wait` polls through the launch an accepted prompt releases; only a command
325+
/// that itself mutates keeps the foreground repair.
326+
func notRunningReadResponse(command: Command, bundleId: String) -> Response? {
327+
#if os(iOS)
328+
guard isReadOnlyCommand(command),
329+
XCUIApplication(bundleIdentifier: bundleId).state == .notRunning
330+
else { return nil }
331+
NSLog(
332+
"AGENT_DEVICE_RUNNER_READ_TARGET_NOT_RUNNING bundle=%@ command=%@",
333+
bundleId,
334+
command.command.rawValue
335+
)
336+
return Response(
337+
ok: false,
338+
error: ErrorPayload(
339+
code: RunnerWireErrorCode.appNotRunning,
340+
message: "app '\(bundleId)' is not running",
341+
hint: "Reads do not launch the app. Relaunch it with open; if a system prompt such as a deep-link confirmation holds its launch, answer it with alert accept."
342+
)
343+
)
344+
#else
345+
return nil
346+
#endif
347+
}
348+
319349
func activateTarget(bundleId: String, reason: String) -> XCUIApplication {
320350
let target = XCUIApplication(bundleIdentifier: bundleId)
321351
let initialState = target.state

‎apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,10 @@ final class RunnerTests: XCTestCase {
3131
/// String codes the daemon keys behavior on. `RUNNER_BUSY` and `RUNNER_WEDGED` come from the busy
3232
/// gate; `MAIN_THREAD_TIMEOUT` is emitted by the transport when a command trips the execution
3333
/// watchdog, so the daemon can tell "the main thread is now occupied" from a generic failure.
34+
/// `APP_NOT_RUNNING` refuses a read whose session app is not running.
3435
enum RunnerWireErrorCode {
3536
static let mainThreadTimeout = "MAIN_THREAD_TIMEOUT"
37+
static let appNotRunning = "APP_NOT_RUNNING"
3638
}
3739

3840
static let springboardBundleId = "com.apple.springboard"

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,50 @@ extension RunnerTests {
134134
}
135135
}
136136
#endif
137+
138+
#if AGENT_DEVICE_RUNNER_UNIT_TESTS && os(iOS)
139+
extension RunnerTests {
140+
/// Installed on every Simulator runtime and cheap to leave terminated.
141+
private static let notRunningTargetBundleId = "com.apple.Preferences"
142+
143+
/// `execute(command:)` serves the command's main-thread work from the calling test's main
144+
/// thread and asserts it; the earlier off-main wrapper tripped that `dispatchPrecondition`,
145+
/// the process restarted mid-suite, and later tests never emitted their log lines.
146+
private func executeOnTerminatedTarget(_ json: String) throws -> (Response, XCUIApplication) {
147+
let target = XCUIApplication(bundleIdentifier: Self.notRunningTargetBundleId)
148+
target.terminate()
149+
invalidateCachedTarget(reason: "unit_test_setup")
150+
defer { invalidateCachedTarget(reason: "unit_test_cleanup") }
151+
return (try execute(command: try runnerCommandFixture(json)), target)
152+
}
153+
154+
func testObservationRefusesANotRunningSessionAppInsteadOfLaunchingIt() throws {
155+
let (response, target) = try executeOnTerminatedTarget(
156+
#"{"command":"snapshot","commandId":"observe","appBundleId":"\#(Self.notRunningTargetBundleId)"}"#
157+
)
158+
defer { target.terminate() }
159+
XCTAssertEqual(response.error?.code, RunnerWireErrorCode.appNotRunning)
160+
XCTAssertEqual(target.state, .notRunning)
161+
}
162+
163+
/// A gesture's first runner call is the `gestureViewport` read, and a selector click's is a
164+
/// snapshot; the refusal covers them exactly as it covers a user-level read.
165+
func testInteractionLeadingReadRefusesToLaunchANotRunningSessionApp() throws {
166+
let (response, target) = try executeOnTerminatedTarget(
167+
#"{"command":"gestureViewport","commandId":"interact","appBundleId":"\#(Self.notRunningTargetBundleId)"}"#
168+
)
169+
defer { target.terminate() }
170+
XCTAssertEqual(response.error?.code, RunnerWireErrorCode.appNotRunning)
171+
XCTAssertEqual(target.state, .notRunning, "a leading read must not launch the session app")
172+
}
173+
174+
func testNonReadCommandStillLaunchesANotRunningSessionApp() throws {
175+
let (response, target) = try executeOnTerminatedTarget(
176+
#"{"command":"activate","commandId":"repair","appBundleId":"\#(Self.notRunningTargetBundleId)"}"#
177+
)
178+
defer { target.terminate() }
179+
XCTAssertTrue(response.ok)
180+
XCTAssertNotEqual(target.state, .notRunning)
181+
}
182+
}
183+
#endif

‎packages/platform-apple/src/runner/__tests__/runner-recovery-wiring.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,3 +319,30 @@ test.each([undefined, 'get', 'accept', 'dismiss'] as const)(
319319
}
320320
},
321321
);
322+
323+
// The refusal is retriable for the caller's own poll, but to the transport it is a definite runner
324+
// answer: no resend, no lost-response status probe, and no invalidation of a healthy session.
325+
test('a read refused over a not-running app is one definite answer, not a transport retry', async () => {
326+
server = await startFakeRunnerServer({
327+
snapshot: [
328+
{ kind: 'runnerError', code: 'APP_NOT_RUNNING', message: "app 'com.example' is not running" },
329+
],
330+
});
331+
seedSession(server.port);
332+
333+
await assert.rejects(
334+
runAppleRunnerCommand(IOS_SIMULATOR, { command: 'snapshot' }),
335+
(error: unknown) => {
336+
assert.ok(error instanceof AppError);
337+
assert.equal(error.code, 'COMMAND_FAILED');
338+
assert.equal(error.details?.runnerErrorCode, 'APP_NOT_RUNNING');
339+
assert.equal(error.details?.retriable, true);
340+
return true;
341+
},
342+
);
343+
assert.deepEqual(
344+
server.requests.map((request) => request.command).filter((command) => command !== 'uptime'),
345+
['snapshot'],
346+
);
347+
assert.equal(invalidateRunnerSessionMock.mock.calls.length, 0);
348+
});

‎packages/platform-apple/src/runner/runner-contract.ts‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,22 @@ export const RUNNER_BUSY_RUNNER_CODE = 'RUNNER_BUSY';
2727
*/
2828
export const MAIN_THREAD_TIMEOUT_RUNNER_CODE = 'MAIN_THREAD_TIMEOUT';
2929

30+
/**
31+
* The runner's own code for a read whose session app is not running. No runner read launches the
32+
* app — a bare launch would drop the payload of a launch still pending, such as a deep link held
33+
* behind SpringBoard's confirmation — so the runner refuses any command carrying its read-only
34+
* trait, including a mutation's leading read (a gesture's viewport read, a selector's resolving
35+
* capture). The refusal describes one poll: the launch that confirmation releases may still be
36+
* starting when the next read arrives, so it is retriable for a `wait`, while the transport reads
37+
* it as a definite answer and never resends it.
38+
*/
39+
export const APP_NOT_RUNNING_RUNNER_CODE = 'APP_NOT_RUNNING';
40+
41+
const RETRIABLE_RUNNER_ERROR_CODES: ReadonlySet<string> = new Set([
42+
RUNNER_BUSY_RUNNER_CODE,
43+
APP_NOT_RUNNING_RUNNER_CODE,
44+
]);
45+
3046
export type RunnerCommand = {
3147
command:
3248
| 'tap'
@@ -175,12 +191,14 @@ export const RUNNER_SCREEN_CAPTURE_REFUSAL_RUNNER_CODES: ReadonlySet<string> = n
175191
/**
176192
* Runner codes that classify a failure for the host without renaming it on the wire. They stay
177193
* `COMMAND_FAILED` and survive as `details.runnerErrorCode`, which is what family policy reads:
178-
* `RUNNER_BUSY` for retriable contention, `ALERT_NOT_FOUND` for an alert that is not there yet, and
179-
* the scroll keyboard refusal for a surface the runner declined to swipe under the keys.
194+
* `RUNNER_BUSY` for retriable contention, `ALERT_NOT_FOUND` for an alert that is not there yet,
195+
* the scroll keyboard refusal for a surface the runner declined to swipe under the keys, and the
196+
* retriable `APP_NOT_RUNNING` for a read the runner refused rather than launch the session app.
180197
*/
181198
const DIAGNOSTIC_ONLY_RUNNER_ERROR_CODES: ReadonlySet<string> = new Set([
182199
RUNNER_BUSY_RUNNER_CODE,
183200
MAIN_THREAD_TIMEOUT_RUNNER_CODE,
201+
APP_NOT_RUNNING_RUNNER_CODE,
184202
ALERT_NOT_FOUND_RUNNER_CODE,
185203
SCROLL_KEYBOARD_OCCLUDES_SURFACE_RUNNER_CODE,
186204
...RUNNER_SCREEN_CAPTURE_REFUSAL_RUNNER_CODES,
@@ -207,7 +225,9 @@ export function classifyRunnerReportedError(
207225
code: diagnosticOnly ? 'COMMAND_FAILED' : toAppErrorCode(runnerErrorCode),
208226
details: Object.freeze({
209227
runnerErrorCode,
210-
...(runnerErrorCode === RUNNER_BUSY_RUNNER_CODE ? { retriable: true as const } : {}),
228+
...(runnerErrorCode !== undefined && RETRIABLE_RUNNER_ERROR_CODES.has(runnerErrorCode)
229+
? { retriable: true as const }
230+
: {}),
211231
}),
212232
});
213233
}

‎packages/platform-apple/src/runner/runner-error-classification.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@ import {
99
type IosDeveloperDiskImageState,
1010
type IosDeveloperModeState,
1111
} from './host.ts';
12-
import { MAIN_THREAD_TIMEOUT_RUNNER_CODE, RUNNER_BUSY_RUNNER_CODE } from './runner-contract.ts';
12+
import {
13+
APP_NOT_RUNNING_RUNNER_CODE,
14+
MAIN_THREAD_TIMEOUT_RUNNER_CODE,
15+
RUNNER_BUSY_RUNNER_CODE,
16+
} from './runner-contract.ts';
1317

1418
export const RUNNER_CACHE_RECOVERY_HINT =
1519
'If runner build products look stale or corrupted, run `pnpm clean:xcuitest` in a local checkout, or remove ~/.agent-device/apple-runner/derived, then retry.';
@@ -66,6 +70,8 @@ type RunnerErrorMatch = {
6670
};
6771

6872
const hasRetriableFlag: RunnerErrorDetailsMatch = (details) => details.retriable === true;
73+
const hasAppNotRunningRunnerCode: RunnerErrorDetailsMatch = (details) =>
74+
details.runnerErrorCode === APP_NOT_RUNNING_RUNNER_CODE;
6975
/**
7076
* The host's own `DevToolsSecurity -status` read, published as typed details by the probe that
7177
* takes it. The build-failure rule below keys on this field and never on the probe's message, so
@@ -199,14 +205,22 @@ const PROFILE_UNUSABLE: RunnerErrorRule['buildFailure'] = {
199205
* `flagged_retriable` precedes the denials (an explicitly retriable error
200206
* stays retriable whatever its message says), and `usbmux_device_unattached`
201207
* sits first (retrying cannot attach a cable, and its typed verdict carries
202-
* the recovery hint a generic connect failure would replace).
208+
* the recovery hint a generic connect failure would replace). `app_not_running`
209+
* precedes `flagged_retriable` too: its retriable flag is for the caller's own
210+
* poll, while to the transport it is a definite runner answer that no resend or
211+
* lost-response probe can change.
203212
*/
204213
export const RUNNER_ERROR_RULES: readonly RunnerErrorRule[] = [
205214
{
206215
reason: 'usbmux_device_unattached',
207216
match: { code: 'DEVICE_NOT_FOUND', details: hasUsbmuxDeviceUnattached },
208217
verdicts: { connectRetry: false },
209218
},
219+
{
220+
reason: 'app_not_running',
221+
match: { code: 'COMMAND_FAILED', details: hasAppNotRunningRunnerCode },
222+
verdicts: { retryable: false, connectRetry: false },
223+
},
210224
{
211225
reason: 'flagged_retriable',
212226
match: { code: 'COMMAND_FAILED', details: hasRetriableFlag },

‎src/commands/schema/cli-help.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -699,6 +699,7 @@ Android physical-device prerequisites:
699699
700700
Runner and daemon lifecycle (applies to simulators too):
701701
open without --relaunch is idempotent-foreground for an already-running app (it brings the process forward; it does not restart it). open --relaunch restarts the app; on iOS simulators this collapses to one simctl launch --terminate-running-process call instead of a separate terminate-then-launch.
702+
No runner read launches a session app that is not running: snapshot, wait, is, get, a reading find, and an interaction's leading reads (a gesture's viewport read, the capture that resolves a selector click/fill) answer the retriable APP_NOT_RUNNING instead of bare-launching over a launch SpringBoard still holds behind its deep-link confirmation. Only open, activate, and a command that mutates without a leading read bring a stopped app up.
702703
close keeps a healthy iOS simulator XCTest runner warm by default so the next open on that device skips the runner build, unless --shutdown was requested, the session was recording, the session held a device lease, or the device used a scoped (non-default) simulator set. A retained runner auto-stops after an idle window (default 5 minutes); set AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS to override, or 0 to disable idle stop and retain until daemon exit.
703704
Each AGENT_DEVICE_STATE_DIR runs its own daemon. It self-exits after an idle window (default 5 minutes, matching the runner idle-stop default) once it has no open sessions, no in-flight requests, and no active recording; set AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS to override, or 0 to disable idle reap.
704705
A stale iOS runner lease — its owner process dead, or its AGENT_DEVICE_STATE_DIR deleted — is reclaimed automatically instead of failing with "is already owned by another agent-device daemon". A live owner's runner is also reclaimed when the requesting daemon holds the host-global device claim for that device: claims are exclusive, so holding one proves the runner's owner released the device and merely kept the runner warm. The error remains only for owners outside claim arbitration (a pre-claims build, or daemons pointed at different claim stores).

0 commit comments

Comments
 (0)