diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift index eb8aad99d6..05f3b5b00d 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift @@ -280,23 +280,14 @@ extension RunnerTests { return (wasVisible: wasVisible, pressed: true, visible: isKeyboardVisible(app: app)) } - var typed = false - let exceptionMessage = RunnerObjCExceptionCatcher.catchException({ - app.typeText(XCUIKeyboardKey.return.rawValue) - typed = true - }) - if let exceptionMessage { - NSLog( - "AGENT_DEVICE_RUNNER_KEYBOARD_RETURN_IGNORED_EXCEPTION=%@", - exceptionMessage - ) + guard typeKeyboardReturn({ app.typeText(XCUIKeyboardKey.return.rawValue) }) else { if let singleTarget = singleTextEntryElement(app: app) { return pressKeyboardReturn(on: singleTarget, app: app, wasVisible: wasVisible) } return (wasVisible: wasVisible, pressed: false, visible: isKeyboardVisible(app: app)) } sleepFor(0.2) - return (wasVisible: wasVisible, pressed: typed, visible: isKeyboardVisible(app: app)) + return (wasVisible: wasVisible, pressed: true, visible: isKeyboardVisible(app: app)) #else return (wasVisible: false, pressed: false, visible: false) #endif @@ -322,15 +313,13 @@ extension RunnerTests { wasVisible: Bool ) -> (wasVisible: Bool, pressed: Bool, visible: Bool) { #if os(iOS) - let exceptionMessage = RunnerObjCExceptionCatcher.catchException({ + // `element` is bound by index, and the keyboard the tap raises shifts those indices, so the + // return goes to whatever the tap focused rather than to a re-resolved `element`. + let typed = typeKeyboardReturn({ element.tap() - element.typeText(XCUIKeyboardKey.return.rawValue) + app.typeText(XCUIKeyboardKey.return.rawValue) }) - if let exceptionMessage { - NSLog( - "AGENT_DEVICE_RUNNER_KEYBOARD_RETURN_TARGET_IGNORED_EXCEPTION=%@", - exceptionMessage - ) + guard typed else { return (wasVisible: wasVisible, pressed: false, visible: isKeyboardVisible(app: app)) } sleepFor(0.2) @@ -340,6 +329,26 @@ extension RunnerTests { #endif } + /// Types a return, false when nothing was typed: an ObjC exception, or XCTest's refusal to type + /// with nothing focused. XCTest records that refusal as an issue, which would invalidate the runner + /// session, so it alone is dropped; every other issue is recorded as usual. + private func typeKeyboardReturn(_ type: () -> Void) -> Bool { + let (issues, exceptionMessage) = holdingRecordedIssues(type) + let noFocus = issues.filter { Self.isNoKeyboardFocusIssue($0.compactDescription) } + issues.filter { !Self.isNoKeyboardFocusIssue($0.compactDescription) }.forEach { record($0) } + if !noFocus.isEmpty { NSLog("AGENT_DEVICE_RUNNER_KEYBOARD_RETURN_NO_FOCUS") } + if let exceptionMessage { + NSLog("AGENT_DEVICE_RUNNER_KEYBOARD_RETURN_IGNORED_EXCEPTION=%@", exceptionMessage) + } + return noFocus.isEmpty && exceptionMessage == nil + } + + /// XCTest names this refusal only in its English issue text, as it does the AX failures that + /// `isSuppressedAxSnapshotIssueDescription` matches. + static func isNoKeyboardFocusIssue(_ description: String) -> Bool { + description.contains("Neither element nor any descendant has keyboard focus") + } + private func singleTextEntryElement(app: XCUIApplication) -> XCUIElement? { #if os(iOS) let matches = safely("KEYBOARD_RETURN_TEXT_ENTRY_QUERY", []) { diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift index 78dc4c6708..82b0bf558c 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift @@ -4,6 +4,7 @@ import AgentDeviceSnapshotPresentation final class TextInputProbeIssues { let thread = Thread.current var count = 0 + var held: [XCTIssue] = [] } enum TextInputProbeFailure: String, Error { @@ -117,6 +118,28 @@ extension RunnerTests { fallback: T, _ probe: (_ shouldStop: () -> Bool) -> T ) -> Result { + withIssueScope { issues in + let (value, exception) = catchingObjCException(fallback: fallback) { + probe({ self.hasTextInputProbeIssues(issues) }) + } + if hasTextInputProbeIssues(issues) { return .failure(.recordedIssue) } + if exception != nil { return .failure(.exception) } + return .success(value) + } + } + + /// Runs `body` with its XCTest issues held back instead of recorded, and hands them to the caller, + /// which records the ones it does not explain. + func holdingRecordedIssues(_ body: () -> Void) -> (issues: [XCTIssue], exceptionMessage: String?) { + withIssueScope { issues in + let (_, exceptionMessage) = catchingObjCException(fallback: ()) { body() } + suppressedIssueLock.lock() + defer { suppressedIssueLock.unlock() } + return (issues.held, exceptionMessage) + } + } + + private func withIssueScope(_ body: (TextInputProbeIssues) -> T) -> T { precondition(Thread.isMainThread) let issues = TextInputProbeIssues() suppressedIssueLock.lock() @@ -128,12 +151,7 @@ extension RunnerTests { textInputProbeIssues = previous suppressedIssueLock.unlock() } - let (value, exception) = catchingObjCException(fallback: fallback) { - probe({ self.hasTextInputProbeIssues(issues) }) - } - if hasTextInputProbeIssues(issues) { return .failure(.recordedIssue) } - if exception != nil { return .failure(.exception) } - return .success(value) + return body(issues) } private func hasTextInputProbeIssues(_ scope: TextInputProbeIssues) -> Bool { @@ -149,8 +167,9 @@ extension RunnerTests { return false } scope.count += 1 + scope.held.append(issue) suppressedIssueLock.unlock() - NSLog("AGENT_DEVICE_RUNNER_TEXT_INPUT_PROBE_UNAVAILABLE issue=%@", issue.compactDescription) + NSLog("AGENT_DEVICE_RUNNER_RECORDED_ISSUE_HELD issue=%@", issue.compactDescription) return true } diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardTests.swift index ae79686351..7139ce0704 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardTests.swift @@ -243,5 +243,71 @@ extension RunnerTests { runnerScreenshotStabilitySettled([Data([1])], requiredConsecutiveMatches: 1) ) } + + func testNoKeyboardFocusIssueIsOnlyXCTestsRefusalToTypeUnfocused() { + XCTAssertTrue(Self.isNoKeyboardFocusIssue( + "Failed to synthesize event: Neither element nor any descendant has keyboard focus. Event dispatch snapshot: Application" + )) + XCTAssertFalse(Self.isNoKeyboardFocusIssue("Timed out while evaluating UI query.")) + } + +#if os(iOS) + @MainActor + func testKeyboardReturnWithNothingFocusedSubmitsTheSoleTextInput() throws { + app.launchArguments = [ + "--agent-device-text-entry-regression", + "--agent-device-text-entry-soft-keyboard", + "--agent-device-text-entry-submit-clears", + "--agent-device-text-entry-long-prefill", + ] + let (response, recordedFailures) = try keyboardReturnOnLaunchedFixture( + waitingForTextInput: "agent-device-hardware-keyboard-input" + ) + let field = app.textFields["agent-device-hardware-keyboard-input"] + + XCTAssertEqual(textEntryInputCount(), 1) + XCTAssertEqual(recordedFailures, 0) + XCTAssertTrue(response.ok, String(describing: response.error)) + XCTAssertEqual(field.value as? String, "", "the field's submit clears it") + } + + @MainActor + func testKeyboardReturnWithNothingFocusedAndNoTextInputFailsWithoutInvalidatingTheRunnerSession() throws { + app.launchArguments = [] + let (response, recordedFailures) = try keyboardReturnOnLaunchedFixture() + + XCTAssertEqual(textEntryInputCount(), 0) + XCTAssertEqual(recordedFailures, 0) + XCTAssertEqual(response.error?.code, "UNSUPPORTED_OPERATION") + } + + @MainActor + private func keyboardReturnOnLaunchedFixture( + waitingForTextInput identifier: String? = nil + ) throws -> (response: Response, recordedFailures: Int) { + app.launch() + addTeardownBlock { @MainActor in + self.invalidateCachedTarget(reason: "unit_test_cleanup") + self.app.terminate() + } + XCTAssertTrue(app.wait(for: .runningForeground, timeout: appExistenceTimeout)) + if let identifier { + XCTAssertTrue(app.textFields[identifier].waitForFixtureExistence(timeout: appExistenceTimeout)) + } + mainOwned.app = app + mainOwned.bundleId = "com.callstack.agentdevice.runner" + mainOwned.processIdentifier = try XCTUnwrap(Self.processIdentifier(of: app)) + let failures = currentXCTestFailureCount() + let command = try runnerCommandFixture( + #"{"appBundleId":"com.callstack.agentdevice.runner","command":"keyboardReturn","commandId":"return-unfocused"}"# + ) + let response = try execute(command: command) + return (response, currentXCTestFailureCount() - failures) + } + + private func textEntryInputCount() -> Int { + app.textFields.count + app.secureTextFields.count + app.searchFields.count + app.textViews.count + } +#endif } #endif