Skip to content

Commit ff565d6

Browse files
committed
refactor(ios-runner): own main-thread capture state in RunnerMainOwnedState
Target identity, accessibility health and the post-snapshot delay flag move into one @mainactor type, so Swift 5 mode rejects a read or write of them from the command queue instead of leaving the boundary to review (#2882). Every main hop's work closure is @mainactor and runs through one MainActor.assumeIsolated helper; timeoutError and onAbandoned are @sendable, so the #2836 routing-probe shape no longer compiles. Functions that only run on main carry @mainactor; the transport, command queue, capture plan, watchdog and the locked completion/abandonment owner stay nonisolated. Escaping closures carry @mainactor or @sendable: transport completions and in-flight waiters, DispatchSource handlers, the phase-timer clock and the unit-test hooks. The recorder's capture is @mainactor and is called only inside the frame tick's main hop; ScreenRecorder.start takes a non-escaping bootstrap and a @sendable frame. Unit tests that touch the state run on the main actor, or step onto it with MainActor.assumeIsolated where they also dispatch work off main.
1 parent fa1082d commit ff565d6

49 files changed

Lines changed: 456 additions & 277 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import XCTest
2+
3+
/// Runner state only the main thread reads or writes. Off-main code reads target identity from a
4+
/// `SnapshotCaptureTarget` taken on main and writes through `applyMainOwnedSnapshotState`.
5+
@MainActor
6+
final class RunnerMainOwnedState {
7+
var app: XCUIApplication?
8+
var bundleId: String?
9+
var processIdentifier: Int?
10+
var accessibilityHealth: RunnerAccessibilityHealth = .unknown
11+
var needsPostSnapshotInteractionDelay = false
12+
13+
nonisolated init() {}
14+
}

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ extension RunnerTests {
2121
return max(0.001, timeoutMs / 1000)
2222
}
2323

24+
@MainActor
2425
func resolveAlert(app activeApp: XCUIApplication, deadline: Date) -> RunnerAlert? {
2526
#if AGENT_DEVICE_RUNNER_UNIT_TESTS
2627
if let override = alertResolutionOverrideForTesting {
@@ -50,6 +51,7 @@ extension RunnerTests {
5051
return nil
5152
}
5253

54+
@MainActor
5355
func handleAlert(_ alert: RunnerAlert, action: String, deadline: Date) -> Response {
5456
if action == "accept" || action == "dismiss" {
5557
guard let button = chooseAlertButton(alert.buttons, action: action) else {
@@ -266,6 +268,7 @@ extension RunnerTests {
266268
// for a fresh hittable read instead of spending it on a dropped tap. The hittable read
267269
// is itself a synchronous query a starved host can complete past the deadline, so a read
268270
// that lands late forfeits rather than buys back the one activation.
271+
@MainActor
269272
private func waitUntilAlertButtonHittable(_ button: XCUIElement, deadline: Date) -> Bool {
270273
while Date() < deadline {
271274
if probeAlertButtonHittable(button, deadline: deadline) {
@@ -276,6 +279,7 @@ extension RunnerTests {
276279
return false
277280
}
278281

282+
@MainActor
279283
private func probeAlertButtonHittable(_ button: XCUIElement, deadline: Date) -> Bool {
280284
#if AGENT_DEVICE_RUNNER_UNIT_TESTS
281285
if let override = alertButtonHittabilityProbeOverrideForTesting {

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

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ extension RunnerTests {
133133
return try runMainThreadWork(
134134
"command_execution",
135135
timeout: max(0.001, deadline.timeIntervalSinceNow),
136-
timeoutError: mainThreadExecutionTimeoutError
136+
timeoutError: Self.mainThreadExecutionTimeoutError
137137
) {
138138
try self.executeOnMainSafely(
139139
command: command,
@@ -145,14 +145,15 @@ extension RunnerTests {
145145
return try runMainThreadWork(
146146
"command_execution",
147147
timeout: mainThreadExecutionTimeout,
148-
timeoutError: mainThreadExecutionTimeoutError
148+
timeoutError: Self.mainThreadExecutionTimeoutError
149149
) {
150150
try self.executeOnMainSafely(command: command, routeToSpringboard: routeToSpringboard)
151151
}
152152
}
153153

154154
// MARK: - Command Handling
155155

156+
@MainActor
156157
private func executeOnMainSafely(
157158
command: Command,
158159
alertDeadline: Date? = nil,
@@ -248,7 +249,7 @@ extension RunnerTests {
248249
let failureCountBefore = try runMainThreadWork(
249250
"recorded_failure_count",
250251
timeout: mainThreadExecutionTimeout,
251-
timeoutError: mainThreadExecutionTimeoutError
252+
timeoutError: Self.mainThreadExecutionTimeoutError
252253
) {
253254
self.currentXCTestFailureCount()
254255
}
@@ -265,7 +266,7 @@ extension RunnerTests {
265266
let recordedFailureResponse = try runMainThreadWork(
266267
"recorded_failure_count",
267268
timeout: mainThreadExecutionTimeout,
268-
timeoutError: mainThreadExecutionTimeoutError
269+
timeoutError: Self.mainThreadExecutionTimeoutError
269270
) {
270271
self.didRecordXCTestFailure(since: failureCountBefore)
271272
? self.xctestRecordedFailureResponse(command: command, response: response)
@@ -275,7 +276,7 @@ extension RunnerTests {
275276
try runMainThreadWork(
276277
"target_invalidation",
277278
timeout: mainThreadExecutionTimeout,
278-
timeoutError: mainThreadExecutionTimeoutError
279+
timeoutError: Self.mainThreadExecutionTimeoutError
279280
) {
280281
self.invalidateCachedTarget(reason: "xctest_recorded_failure")
281282
}
@@ -290,7 +291,7 @@ extension RunnerTests {
290291
try runMainThreadWork(
291292
"target_invalidation",
292293
timeout: mainThreadExecutionTimeout,
293-
timeoutError: mainThreadExecutionTimeoutError
294+
timeoutError: Self.mainThreadExecutionTimeoutError
294295
) {
295296
self.invalidateCachedTarget(reason: "response_unavailable")
296297
self.sleepFor(self.retryCooldown)
@@ -301,6 +302,7 @@ extension RunnerTests {
301302
}
302303
}
303304

305+
@MainActor
304306
private func executeOnMain(
305307
command: Command,
306308
alertDeadline: Date?,
@@ -404,7 +406,7 @@ extension RunnerTests {
404406
return Response(ok: false, error: ErrorPayload(message: "terminate requires appBundleId"))
405407
}
406408
XCUIApplication(bundleIdentifier: bundleId).terminate()
407-
if currentBundleId == bundleId {
409+
if mainOwned.bundleId == bundleId {
408410
invalidateCachedTarget(reason: "target_terminated")
409411
}
410412
return Response(ok: true, data: DataPayload(message: "app terminated"))
@@ -418,11 +420,12 @@ extension RunnerTests {
418420
)
419421
}
420422

423+
@MainActor
421424
func prepareActiveCommandContext(
422425
command: Command,
423426
routeToSpringboard: Bool = false
424427
) -> ActiveCommandPreparation {
425-
var activeApp = currentApp ?? app
428+
var activeApp = mainOwned.app ?? app
426429
var systemSurface: SystemSurfaceHost? = nil
427430
if routeToSpringboard {
428431
activeApp = springboard
@@ -447,7 +450,7 @@ extension RunnerTests {
447450
return .response(notRunning)
448451
}
449452
if let bundleId = requestedBundleId {
450-
if currentBundleId != bundleId || currentApp == nil {
453+
if mainOwned.bundleId != bundleId || mainOwned.app == nil {
451454
_ = activateTarget(bundleId: bundleId, reason: "bundle_changed")
452455
} else {
453456
refreshCachedTargetIfProcessChanged(bundleId: bundleId)
@@ -457,7 +460,7 @@ extension RunnerTests {
457460
invalidateCachedTarget(reason: "missing_app_bundle")
458461
}
459462

460-
activeApp = currentApp ?? app
463+
activeApp = mainOwned.app ?? app
461464
if let bundleId = requestedBundleId, targetNeedsActivation(activeApp) {
462465
activeApp = activateTarget(bundleId: bundleId, reason: "stale_target")
463466
} else if requestedBundleId == nil, targetNeedsActivation(activeApp) {
@@ -546,6 +549,7 @@ extension RunnerTests {
546549
)
547550
}
548551

552+
@MainActor
549553
func shouldSkipAppActivationPreflight(_ command: Command) -> Bool {
550554
#if os(iOS)
551555
if command.command == .alert {
@@ -605,25 +609,27 @@ extension RunnerTests {
605609
&& command.y != nil
606610
}
607611

612+
@MainActor
608613
private func hasCachedTargetForActivationSkip(command: Command) -> Bool {
609-
guard let currentApp, currentApp.state == .runningForeground else { return false }
614+
guard let boundApp = mainOwned.app, boundApp.state == .runningForeground else { return false }
610615
guard let bundleId = command.appBundleId?.trimmingCharacters(in: .whitespacesAndNewlines),
611616
!bundleId.isEmpty
612617
else {
613618
return true
614619
}
615-
return currentBundleId == bundleId
620+
return mainOwned.bundleId == bundleId
616621
}
617622

623+
@MainActor
618624
func resolveAppWithoutActivation(command: Command) -> XCUIApplication {
619625
guard let bundleId = command.appBundleId?
620626
.trimmingCharacters(in: .whitespacesAndNewlines),
621627
!bundleId.isEmpty
622628
else {
623-
return currentApp ?? app
629+
return mainOwned.app ?? app
624630
}
625-
if currentBundleId == bundleId, let currentApp {
626-
return currentApp
631+
if mainOwned.bundleId == bundleId, let boundApp = mainOwned.app {
632+
return boundApp
627633
}
628634
return XCUIApplication(bundleIdentifier: bundleId)
629635
}

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import XCTest
22
import AgentDeviceSnapshotPresentation
33

44
extension RunnerTests {
5+
@MainActor
56
func executeOnMainPrepared(
67
command: Command,
78
activeApp: XCUIApplication,
@@ -143,7 +144,7 @@ extension RunnerTests {
143144
}
144145
if let x = command.x, let y = command.y {
145146
let xCTestChannelPenalized = isSnapshotXCTestChannelPenalized(
146-
bundleId: currentBundleId
147+
bundleId: mainOwned.bundleId
147148
)
148149
let xCTestTextInputProbeSkipped = !shouldProbeCoordinateTapTextInput(
149150
xCTestChannelPenalized: xCTestChannelPenalized
@@ -156,7 +157,7 @@ extension RunnerTests {
156157
textInput = nil
157158
NSLog(
158159
"AGENT_DEVICE_RUNNER_COORDINATE_TAP_TEXT_INPUT_PROBE_SKIPPED bundle=%@",
159-
currentBundleId ?? ""
160+
mainOwned.bundleId ?? ""
160161
)
161162
}
162163
var fallback: GestureFallback?

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ extension RunnerTests {
5757
///
5858
/// NOTE: a new SYNTHESIS gesture must pass `idleTimeout: false` — the default `true` would wrap
5959
/// it in the scroll idle-timeout/quiescence-skip path and change its runtime behavior.
60+
@MainActor
6061
func performGesture(
6162
_ app: XCUIApplication,
6263
idleTimeout: Bool = true,

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

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,7 @@ extension RunnerTests {
180180

181181
// MARK: - Target Activation
182182

183+
@MainActor
183184
func ensureRunnerHostAppActive(reason: String) {
184185
NSLog(
185186
"AGENT_DEVICE_RUNNER_HOST_ACTIVATE state=%d reason=%@",
@@ -191,9 +192,9 @@ extension RunnerTests {
191192
} else if app.state != .runningForeground {
192193
app.activate()
193194
}
194-
currentApp = app
195-
currentBundleId = nil
196-
currentAppProcessIdentifier = nil
195+
mainOwned.app = app
196+
mainOwned.bundleId = nil
197+
mainOwned.processIdentifier = nil
197198
resetTargetBoundState()
198199
}
199200

@@ -207,16 +208,18 @@ extension RunnerTests {
207208
lastLoggedGesturePolicyLines.removeAll()
208209
}
209210

211+
@MainActor
210212
func invalidateCachedTarget(reason: String) {
211-
if currentApp != nil || currentBundleId != nil {
213+
if mainOwned.app != nil || mainOwned.bundleId != nil {
212214
NSLog("AGENT_DEVICE_RUNNER_TARGET_CACHE_INVALIDATE reason=%@", reason)
213215
}
214-
currentApp = nil
215-
currentBundleId = nil
216-
currentAppProcessIdentifier = nil
216+
mainOwned.app = nil
217+
mainOwned.bundleId = nil
218+
mainOwned.processIdentifier = nil
217219
resetTargetBoundState()
218220
}
219221

222+
@MainActor
220223
func resetTargetAfterExternalRelaunch() -> Response {
221224
invalidateCachedTarget(reason: "external_app_relaunch")
222225
// The app process is replaced, but the retained runner survives. Clear
@@ -228,22 +231,23 @@ extension RunnerTests {
228231
return Response(ok: true, data: DataPayload(message: "target reset"))
229232
}
230233

234+
@MainActor
231235
func refreshCachedTargetIfProcessChanged(bundleId: String) {
232-
guard currentBundleId == bundleId, currentApp != nil else { return }
236+
guard mainOwned.bundleId == bundleId, mainOwned.app != nil else { return }
233237
let candidate = XCUIApplication(bundleIdentifier: bundleId)
234238
let observedProcessIdentifier = Self.processIdentifier(of: candidate)
235239
guard Self.shouldRefreshCachedTarget(
236-
cachedProcessIdentifier: currentAppProcessIdentifier,
240+
cachedProcessIdentifier: mainOwned.processIdentifier,
237241
observedProcessIdentifier: observedProcessIdentifier
238242
) else { return }
239243
NSLog(
240244
"AGENT_DEVICE_RUNNER_TARGET_CACHE_REFRESH bundle=%@ previousPid=%d currentPid=%d",
241245
bundleId,
242-
currentAppProcessIdentifier ?? 0,
246+
mainOwned.processIdentifier ?? 0,
243247
observedProcessIdentifier ?? 0
244248
)
245-
currentApp = candidate
246-
currentAppProcessIdentifier = observedProcessIdentifier
249+
mainOwned.app = candidate
250+
mainOwned.processIdentifier = observedProcessIdentifier
247251
resetTargetBoundState()
248252
clearSnapshotXCTestChannelPenalty(reason: "target_process_changed")
249253
clearPrivateAXAcceptedDepth(reason: "target_process_changed")
@@ -280,18 +284,20 @@ extension RunnerTests {
280284
return false
281285
}
282286

287+
@MainActor
283288
func canUseFastForegroundAppGuard(
284289
activeApp: XCUIApplication,
285290
requestedBundleId: String?
286291
) -> Bool {
287-
guard let requestedBundleId, currentBundleId == requestedBundleId, currentApp != nil else {
292+
guard let requestedBundleId, mainOwned.bundleId == requestedBundleId, mainOwned.app != nil else {
288293
return false
289294
}
290295
guard activeApp.state == .runningForeground else { return false }
291296
writeFastAppGuardMarker(bundleId: requestedBundleId, state: activeApp.state)
292297
return true
293298
}
294299

300+
@MainActor
295301
func writeFastAppGuardMarker(bundleId: String, state: XCUIApplication.State) {
296302
// The command is on the adjacent COMMAND_ACCEPTED line; repeating it here would make a deduped
297303
// marker read as if only that command ever passed the guard.
@@ -341,6 +347,7 @@ extension RunnerTests {
341347
#endif
342348
}
343349

350+
@MainActor
344351
func activateTarget(bundleId: String, reason: String) -> XCUIApplication {
345352
let target = XCUIApplication(bundleIdentifier: bundleId)
346353
let initialState = target.state
@@ -374,9 +381,9 @@ extension RunnerTests {
374381
otherActiveApplicationPid.map(String.init) ?? "-"
375382
)
376383
}
377-
currentApp = target
378-
currentBundleId = bundleId
379-
currentAppProcessIdentifier = Self.processIdentifier(of: target)
384+
mainOwned.app = target
385+
mainOwned.bundleId = bundleId
386+
mainOwned.processIdentifier = Self.processIdentifier(of: target)
380387
resetTargetBoundState()
381388
beginFirstInteractionStabilization()
382389
return target
@@ -387,6 +394,7 @@ extension RunnerTests {
387394
/// interaction themselves first (a scroll needs no extra wait, a text field is located, an alert
388395
/// button is read as hittable), which is what the dropped pre-event wait replaces rather than a
389396
/// check the runner skips (#2546).
397+
@MainActor
390398
func withBoundedInteractionIdleTimeoutIfSupported(
391399
_ target: XCUIApplication,
392400
waits: RunnerInteractionIdleWaits,
@@ -409,6 +417,7 @@ extension RunnerTests {
409417
}
410418

411419
// Some apps never report post-gesture quiescence, even after XCTest has synthesized the event.
420+
@MainActor
412421
private func performWithQuiescenceSkippedIfSupported(
413422
_ target: XCUIApplication,
414423
waits: RunnerInteractionIdleWaits,
@@ -440,7 +449,7 @@ extension RunnerTests {
440449
options = skipPreEventQuiescence
441450
}
442451
withoutActuallyEscaping(operation) { escapableOperation in
443-
let block: @convention(block) () -> Void = escapableOperation
452+
let block: @MainActor @convention(block) () -> Void = { escapableOperation() }
444453
performWithOptions(
445454
target,
446455
selector,
@@ -489,10 +498,11 @@ extension RunnerTests {
489498

490499
// MARK: - Interaction Stabilization
491500

501+
@MainActor
492502
func applyInteractionStabilizationIfNeeded() {
493-
if needsPostSnapshotInteractionDelay {
503+
if mainOwned.needsPostSnapshotInteractionDelay {
494504
sleepFor(postSnapshotInteractionDelay)
495-
needsPostSnapshotInteractionDelay = false
505+
mainOwned.needsPostSnapshotInteractionDelay = false
496506
}
497507
if let readyUptime = firstInteractionReadyUptime {
498508
sleepFor(readyUptime - ProcessInfo.processInfo.systemUptime)

0 commit comments

Comments
 (0)