diff --git a/.github/workflows/perf-nightly.yml b/.github/workflows/perf-nightly.yml index a113d4db34..826fa30807 100644 --- a/.github/workflows/perf-nightly.yml +++ b/.github/workflows/perf-nightly.yml @@ -114,7 +114,7 @@ jobs: env: UDID: ${{ steps.ios-simulator.outputs.simulator-udid }} run: | - # The keyboard must stay expanded for keyboard dismiss to find its Done key. + # The keyboard must stay expanded for the form step to find the return key labelled Done. xcrun simctl spawn "$UDID" defaults write com.apple.keyboard.preferences AutomaticMinimizationEnabled -bool false pnpm clean:daemon node bin/agent-device.mjs prepare ios-runner --platform ios --udid "$UDID" --timeout "$AGENT_DEVICE_IOS_PREPARE_TIMEOUT_MS" diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerAppFixtures.m b/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerAppFixtures.m index f6df76a93c..32426718c5 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerAppFixtures.m +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerAppFixtures.m @@ -435,6 +435,23 @@ - (void)stopAlertActivationBusy { self.alertActivationBusyBackstop = nil; } +// Places a keyboard fixture's field below `above`, and the label that answers what its controls did +// below the field. +static void AgentDeviceAddKeyboardFieldWithAnswer(UIView *view, UITextField *field, UILabel *answer, UIView *above) { + field.translatesAutoresizingMaskIntoConstraints = NO; + answer.translatesAutoresizingMaskIntoConstraints = NO; + [view addSubview:field]; + [view addSubview:answer]; + [NSLayoutConstraint activateConstraints:@[ + [field.centerXAnchor constraintEqualToAnchor:view.centerXAnchor], + [field.topAnchor constraintEqualToAnchor:above.bottomAnchor constant:24], + [field.widthAnchor constraintEqualToConstant:240], + [field.heightAnchor constraintEqualToConstant:44], + [answer.centerXAnchor constraintEqualToAnchor:view.centerXAnchor], + [answer.topAnchor constraintEqualToAnchor:field.bottomAnchor constant:12], + ]]; +} + // The keyboard counterpart of the busy alert: the field starts the same never-ending UIView animation // when it takes focus, so XCTest sees work in flight for as long as the keyboard is up. Its Done // accessory and its return key record whether they landed while the app was still busy. The backstop @@ -928,25 +945,106 @@ - (void)viewDidLoad { [field addTarget:self action:@selector(keyboardBusyReturnPressed) forControlEvents:UIControlEventEditingDidEndOnExit]; - field.translatesAutoresizingMaskIntoConstraints = NO; - [self.view addSubview:field]; UILabel *answer = [[UILabel alloc] init]; answer.text = @"Unanswered"; answer.accessibilityIdentifier = @"agent-device-keyboard-busy-answer"; - answer.translatesAutoresizingMaskIntoConstraints = NO; - [self.view addSubview:answer]; - [NSLayoutConstraint activateConstraints:@[ - [field.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor], - [field.topAnchor constraintEqualToAnchor:label.bottomAnchor constant:24], - [field.widthAnchor constraintEqualToConstant:240], - [field.heightAnchor constraintEqualToConstant:44], - [answer.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor], - [answer.topAnchor constraintEqualToAnchor:field.bottomAnchor constant:12], - ]]; + AgentDeviceAddKeyboardFieldWithAnswer(self.view, field, answer, label); self.keyboardBusyField = field; self.keyboardBusyAnswer = answer; } + // A field whose return key reads "Done" and submits, which `keyboard dismiss` must never press. The + // optional `accessory` argument adds a Done toolbar above the keys, the one control it may press. + NSArray *launchArguments = NSProcessInfo.processInfo.arguments; + NSUInteger doneReturnFlag = [launchArguments indexOfObject:@"--agent-device-keyboard-done-return"]; + if (doneReturnFlag != NSNotFound) { + NSString *accessoryShape = doneReturnFlag + 1 < launchArguments.count ? launchArguments[doneReturnFlag + 1] : @""; + BOOL plainAccessory = [accessoryShape isEqualToString:@"plain-accessory"]; + BOOL withAccessory = plainAccessory || [accessoryShape isEqualToString:@"accessory"]; + UITextField *field = [[UITextField alloc] init]; + field.accessibilityIdentifier = @"agent-device-keyboard-done-return-input"; + field.placeholder = @"Return key is Done"; + field.borderStyle = UITextBorderStyleRoundedRect; + field.returnKeyType = UIReturnKeyDone; + UILabel *answer = [[UILabel alloc] init]; + answer.text = @"Unanswered"; + answer.accessibilityIdentifier = @"agent-device-keyboard-done-return-answer"; + __weak UITextField *weakField = field; + __weak UILabel *weakAnswer = answer; + [field addAction:[UIAction actionWithHandler:^(__kindof UIAction *action) { + weakAnswer.text = @"Submitted"; + [weakField resignFirstResponder]; + }] + forControlEvents:UIControlEventEditingDidEndOnExit]; + if (plainAccessory) { + // An accessory that is no toolbar: a plain view holding a button, as a custom or React Native + // input accessory is. + UIView *accessory = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; + accessory.backgroundColor = UIColor.systemGray5Color; + UIButton *accessoryDone = [UIButton buttonWithType:UIButtonTypeSystem]; + [accessoryDone setTitle:@"Done" forState:UIControlStateNormal]; + accessoryDone.frame = CGRectMake(240, 0, 70, 44); + [accessoryDone addAction:[UIAction actionWithHandler:^(__kindof UIAction *action) { + weakAnswer.text = @"Accessory"; + [weakField resignFirstResponder]; + }] + forControlEvents:UIControlEventTouchUpInside]; + [accessory addSubview:accessoryDone]; + field.inputAccessoryView = accessory; + } else if (withAccessory) { + UIToolbar *accessory = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; + accessory.items = @[ + [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace + target:nil + action:nil], + [[UIBarButtonItem alloc] + initWithPrimaryAction:[UIAction actionWithTitle:@"Done" + image:nil + identifier:nil + handler:^(__kindof UIAction *action) { + weakAnswer.text = @"Accessory"; + [weakField resignFirstResponder]; + }]], + ]; + field.inputAccessoryView = accessory; + } + AgentDeviceAddKeyboardFieldWithAnswer(self.view, field, answer, label); + if (withAccessory) { + // A screen-level Done with the toolbar Done's label and no identifier, far from the keyboard, as a + // navigation bar's would be: dismiss must still press the toolbar's, never this one. + UIButton *screenDone = [UIButton buttonWithType:UIButtonTypeSystem]; + [screenDone setTitle:@"Done" forState:UIControlStateNormal]; + [screenDone addAction:[UIAction actionWithHandler:^(__kindof UIAction *action) { + weakAnswer.text = @"Screen"; + }] + forControlEvents:UIControlEventTouchUpInside]; + screenDone.translatesAutoresizingMaskIntoConstraints = NO; + [self.view addSubview:screenDone]; + [NSLayoutConstraint activateConstraints:@[ + [screenDone.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:8], + [screenDone.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16], + ]]; + } + } + + // A text field nested far deeper than XCTest's whole-app snapshot can read, so the keyboard's own + // snapshot is the only read that works while its field has focus. + if ([NSProcessInfo.processInfo.arguments containsObject:@"--agent-device-keyboard-deep-tree"]) { + UIView *parent = self.view; + for (NSUInteger depth = 0; depth < 70; depth++) { + UIView *group = [[UIView alloc] initWithFrame:parent.bounds]; + group.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + group.accessibilityContainerType = UIAccessibilityContainerTypeSemanticGroup; + [parent addSubview:group]; + parent = group; + } + UITextField *deepField = [[UITextField alloc] initWithFrame:CGRectMake(40, 140, 260, 44)]; + deepField.accessibilityIdentifier = @"agent-device-keyboard-deep-input"; + deepField.placeholder = @"Deep field"; + deepField.borderStyle = UITextBorderStyleRoundedRect; + [parent addSubview:deepField]; + } + if ([NSProcessInfo.processInfo.arguments containsObject:@"--agent-device-native-states"]) { for (NSUInteger index = 0; index < 3; index++) { UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(40, 120 + index * 60, 260, 44)]; diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardStatus.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardStatus.swift index c285771d2e..3799e00028 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardStatus.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardStatus.swift @@ -24,6 +24,25 @@ extension RunnerKeyboardStatus { struct ObservedKeyboardKey { let text: String? let frame: CGRect + /// The control's accessibility identifier, where the read carries it. A return key can show + /// `done` as its label and `Done` as its identifier, so dismiss matches either. + var identifier: String? = nil + /// Whether the tree carries the control as a key or as a button. Only keys are character keys: a + /// QuickType candidate or an accessory toolbar's control is a button, whatever its wording. + var kind: Kind = .key + enum Kind: Equatable { + case key + case button + } + } + + /// One snapshot of the keyboard: its frame and every key's wording and frame, taken together so a + /// decision never mixes two reads of a keyboard that may be sliding. The dismiss read also carries, + /// as buttons, the dismiss-worded controls the app holds outside the keyboard, such as + /// an input accessory's `Done`, from the same snapshot. + struct ObservedKeyboard { + let frame: CGRect + let keys: [ObservedKeyboardKey] } /// What identifies Apple's space bar in the accessibility tree: wording that is whitespace and @@ -91,13 +110,92 @@ extension RunnerKeyboardStatus { guard visible else { return RunnerKeyboardStatus(visible: false, returnKey: nil, returnKeyLabel: nil) } - let worded = keyboardKeys.filter { key in - !(key.text ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + return observed(visible: true, returnControlText: returnControl(in: keyboardKeys)?.text) + } + + /// The top edge of the first row of character keys: the highest single-character control of key type. + /// It anchors where the key rows start, so a control wholly above it is an input accessory's, not a + /// key. A button never anchors, however short its wording: a QuickType candidate such as `I` or `A` + /// is a button above the key rows and would pull the anchor up to the prediction bar. `nil` when no + /// character key was read with wording and a frame, and then nothing can be placed relative to the + /// key rows. + static func characterKeyRowTop(in keys: [ObservedKeyboardKey]) -> CGFloat? { + keys + .filter { + $0.kind == .key && $0.text?.trimmingCharacters(in: .whitespacesAndNewlines).count == 1 + && !$0.frame.isEmpty + } + .map { $0.frame.minY } + .min() + } + + /// The one decision that a control is the visible keyboard's return key, by wording first and by + /// slot otherwise (see `observed(visible:keyboardKeys:)`). `keyboard status` reports it, and + /// `keyboard dismiss` presses nothing that could be it, so the two commands cannot disagree about + /// which key is the return key. + /// + /// A wording match is the return key only when it is placed inside the key rows: below the top of + /// the first row of character keys. A control above that line is an input accessory's `Next` or + /// `Done`, and with no character key to anchor on, nothing can be placed, so no wording names it. + static func returnControl(in keys: [ObservedKeyboardKey]) -> ObservedKeyboardKey? { + let rowTop = characterKeyRowTop(in: keys) + let named = keys.first { key in + guard RunnerKeyboardReturnKey.kind(of: key.text ?? "") != .unknown, let rowTop else { return false } + return !key.frame.isEmpty && key.frame.maxY > rowTop } - if let named = worded.first(where: { RunnerKeyboardReturnKey.kind(of: $0.text ?? "") != .unknown }) { - return observed(visible: true, returnControlText: named.text) + return named ?? returnKeySlot(in: keys) + } + + /// Wording of the controls that only hide the keyboard. Neither can be a return key. + static let hideKeyboardLabels = ["Hide keyboard", "Dismiss keyboard"] + + /// The dismiss controls `keyboard dismiss` may press, in the order it tries them. + static let dismissLabels = hideKeyboardLabels + ["Done"] + + /// How far above the keyboard an accessory's button can sit and still belong to it. + static let accessoryReach: CGFloat = 80 + + /// True when `frame` belongs to the keyboard: it has a frame, it does not start below the keyboard, + /// and it is inside the keyboard or no more than `accessoryReach` above it. An app button with the + /// same wording elsewhere on screen is not the keyboard's. + static func isNearKeyboard(_ frame: CGRect, keyboardFrame: CGRect) -> Bool { + !frame.isEmpty && !keyboardFrame.isEmpty + && frame.minY < keyboardFrame.maxY + && keyboardFrame.minY - frame.maxY <= accessoryReach + } + + /// Whether a refusal should say the screen could not be read: the app tree was unreadable and the + /// keyboard's own read, the only one left, held no dismiss candidate. A fallback that held a candidate + /// the live lookup then rejected, as covered or ambiguous, is a keyboard whose key could not be pressed, + /// which is a different cause. + static func refusalIsTreeUnreadable(treeReadable: Bool, surface: ObservedKeyboard?) -> Bool { + !treeReadable && (surface.map { dismissControls(in: $0).isEmpty } ?? true) + } + + /// Every control `keyboard dismiss` may press, in dismiss-label order then tree order, all read from + /// one snapshot so no decision mixes two reads of a keyboard that may be sliding. + /// + /// A candidate carries dismiss wording as its label or identifier and is near the keyboard. A + /// hide-keyboard control is never a return key. A `Done` is pressed only when it cannot be the return + /// key: wholly above the keyboard, which holds an input accessory of any shape, or inside the keyboard + /// and above the first row of character keys, which needs that row as an anchor and so fails closed + /// without one. A candidate whose type, label and identifier name another control near the keyboard is + /// left out, because a live lookup could not tell the two apart; a same-wording button far from the + /// keyboard, such as a header `Done`, does not count. + static func dismissControls(in keyboard: ObservedKeyboard) -> [ObservedKeyboardKey] { + let near = keyboard.keys.filter { isNearKeyboard($0.frame, keyboardFrame: keyboard.frame) } + let rowTop = characterKeyRowTop(in: keyboard.keys) + return dismissLabels.flatMap { label in + near.filter { key in + guard key.text == label || key.identifier == label else { return false } + let canBeReturnKey = !hideKeyboardLabels.contains(label) + && key.frame.maxY > keyboard.frame.minY && key.frame.maxY > (rowTop ?? -.infinity) + let identity = near.filter { + $0.kind == key.kind && $0.text == key.text && ($0.identifier ?? "") == (key.identifier ?? "") + } + return !canBeReturnKey && identity.count == 1 + } } - return observed(visible: true, returnControlText: returnKeySlot(in: keyboardKeys)?.text) } /// The worded control in the return key's slot, or `nil` when the keyboard exposes no space bar to diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift index a8e9171cdc..59c958226e 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift @@ -602,7 +602,13 @@ extension RunnerTests { return Response(ok: false, error: ErrorPayload(message: "keyboardDismiss produced no result")) } if result.wasVisible && !result.dismissed { - return Response(ok: false, error: keyboardDismissRefusal(dispatchedDismissal: result.dispatchedDismissal)) + return Response( + ok: false, + error: keyboardDismissRefusal( + dispatchedDismissal: result.dispatchedDismissal, + treeUnreadable: result.treeUnreadable + ) + ) } return Response( ok: true, diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift index bc7c68ef8c..8e9f47aea4 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift @@ -31,6 +31,14 @@ enum RunnerKeyboardDismissMechanism: String { case dismissKey } +/// What looking for a dismiss control to tap came to: one was tapped, none exists, or none was found +/// because the app tree could not be read and the keyboard's own read held none. +enum KeyboardDismissTap { + case tapped + case notFound + case treeUnreadable +} + /// One `keyboard dismiss` attempt, plus the fact that decides how a refusal is classified: /// `dispatchedDismissal` says whether the runner ever dispatched a dismissal. struct RunnerKeyboardDismissOutcome { @@ -41,6 +49,9 @@ struct RunnerKeyboardDismissOutcome { /// Whether a dismissal was dispatched — the keyboard's own control was tapped, or the tvOS remote's /// Menu press landed. Only its absence proves the command sent nothing. let dispatchedDismissal: Bool + /// Whether the app tree could not be read and the keyboard's own read found no dismiss control, so + /// the refusal can say it could not see the screen instead of claiming the keyboard has no key. + var treeUnreadable = false } /// Keyboard coverage read from the capture's complete pre-projection root snapshot on iOS XCTest. @@ -213,11 +224,10 @@ extension RunnerTests { /// is one round trip instead of one per key. func keyboardStatus(app: XCUIApplication) -> RunnerKeyboardStatus { #if os(iOS) - let snapshot = safely("KEYBOARD_STATUS_SNAPSHOT") { try? app.keyboards.firstMatch.snapshot() } - guard let snapshot, !snapshot.frame.isEmpty else { + guard let keyboard = readKeyboard(app: app) else { return RunnerKeyboardStatus.observed(visible: false, returnControlText: nil) } - return RunnerKeyboardStatus.observed(visible: true, keyboardKeys: observedKeyboardKeys(in: snapshot)) + return RunnerKeyboardStatus.observed(visible: true, keyboardKeys: keyboard.keys) #else guard isKeyboardVisible(app: app) else { return RunnerKeyboardStatus.observed(visible: false, returnControlText: nil) @@ -238,14 +248,89 @@ extension RunnerTests { var pending = Array(keyboard.children.reversed()) while let node = pending.popLast() { pending.append(contentsOf: node.children.reversed()) - guard node.elementType == .key || node.elementType == .button, !node.label.isEmpty else { continue } - let observed = RunnerKeyboardStatus.ObservedKeyboardKey(text: node.label, frame: node.frame) + guard node.elementType == .key || node.elementType == .button, + !node.label.isEmpty || !node.identifier.isEmpty + else { continue } + let observed = RunnerKeyboardStatus.ObservedKeyboardKey( + text: node.label, + frame: node.frame, + identifier: node.identifier.isEmpty ? nil : node.identifier, + kind: node.elementType == .key ? .key : .button + ) if node.elementType == .key { keys.append(observed) } else { buttons.append(observed) } } return keys + buttons } #endif + /// The visible keyboard as one snapshot read, or `nil` when there is none to read: the read failed or + /// came back empty, or the platform has no software keyboard. `nil` is not "a keyboard with no keys", + /// and a decision that needs the keys must not treat it as one. + func readKeyboard(app: XCUIApplication) -> RunnerKeyboardStatus.ObservedKeyboard? { +#if os(iOS) + let snapshot = safely("KEYBOARD_SNAPSHOT") { try? app.keyboards.firstMatch.snapshot() } + guard let snapshot, !snapshot.frame.isEmpty else { return nil } + return RunnerKeyboardStatus.ObservedKeyboard(frame: snapshot.frame, keys: observedKeyboardKeys(in: snapshot)) +#else + return nil +#endif + } + +#if os(iOS) + /// The keyboard and the dismiss-worded buttons outside it, such as an input accessory's `Done`, from + /// one snapshot of the app. The keyboard's own snapshot does not hold an accessory's buttons, and the + /// keyboard and an accessory must be judged from one read. + func readKeyboardSurface(app: XCUIApplication) -> ( + surface: RunnerKeyboardStatus.ObservedKeyboard?, treeReadable: Bool + ) { + resolveKeyboardSurface( + appRoot: safely("KEYBOARD_SURFACE_SNAPSHOT", { try? app.snapshot() }), + keyboardRead: { self.readKeyboard(app: app) } + ) + } + + /// The surface when the app snapshot holds a keyboard with a frame. When it does not, because the read + /// failed or a tree too deep to serialize came back without its keyboard node, the keyboard's own read + /// answers instead, so its dismiss key still works, and the tree counts as unreadable: a refusal that + /// finds nothing there says so. Callers ask only while the keyboard is up. + func resolveKeyboardSurface( + appRoot: XCUIElementSnapshot?, + keyboardRead: () -> RunnerKeyboardStatus.ObservedKeyboard? + ) -> (surface: RunnerKeyboardStatus.ObservedKeyboard?, treeReadable: Bool) { + if let appRoot, let surface = keyboardSurface(in: appRoot) { return (surface, true) } + return (keyboardRead(), false) + } + + private func keyboardSurface(in root: XCUIElementSnapshot) -> RunnerKeyboardStatus.ObservedKeyboard? { + var keyboard: XCUIElementSnapshot? + var outside: [RunnerKeyboardStatus.ObservedKeyboardKey] = [] + var pending = [root] + while let node = pending.popLast() { + if node.elementType == .keyboard, keyboard == nil { + keyboard = node + continue + } + pending.append(contentsOf: node.children.reversed()) + let wording = RunnerKeyboardStatus.dismissLabels + if node.elementType == .button, wording.contains(node.label) || wording.contains(node.identifier) { + outside.append( + RunnerKeyboardStatus.ObservedKeyboardKey( + text: node.label, + frame: node.frame, + identifier: node.identifier.isEmpty ? nil : node.identifier, + kind: .button + ) + ) + } + } + guard let keyboard, !keyboard.frame.isEmpty else { return nil } + return RunnerKeyboardStatus.ObservedKeyboard( + frame: keyboard.frame, + keys: observedKeyboardKeys(in: keyboard) + outside + ) + } +#endif + func dismissKeyboard(app: XCUIApplication) -> RunnerKeyboardDismissOutcome { let keyboard = app.keyboards.firstMatch let wasVisible = isKeyboardVisible(app: app) @@ -273,7 +358,8 @@ extension RunnerTests { dispatchedDismissal: true ) #else - if tapKeyboardDismissControl(app: app) { + let tap = tapKeyboardDismissControl(app: app) + if tap == .tapped { _ = keyboard.waitForNonExistence(timeout: KeyboardDismissObservationTiming.timeout) waitForScreenshotStability( app: app, @@ -302,7 +388,8 @@ extension RunnerTests { dismissed: false, visible: isKeyboardVisible(app: app), mechanism: nil, - dispatchedDismissal: false + dispatchedDismissal: false, + treeUnreadable: tap == .treeUnreadable ) #endif } @@ -312,7 +399,7 @@ extension RunnerTests { /// nothing and is the runner's own typed refusal (`KEYBOARD_DISMISS_UNAVAILABLE`, so the host /// publishes its `details.reason` instead of leaving callers to read the prose), while a control /// that was tapped and left the keys up did dispatch and keeps the generic code. - func keyboardDismissRefusal(dispatchedDismissal: Bool) -> ErrorPayload { + func keyboardDismissRefusal(dispatchedDismissal: Bool, treeUnreadable: Bool = false) -> ErrorPayload { if dispatchedDismissal { return ErrorPayload( code: "UNSUPPORTED_OPERATION", @@ -322,8 +409,11 @@ extension RunnerTests { } return ErrorPayload( code: RunnerWireErrorCode.keyboardDismissUnavailable, - message: "Unable to dismiss the keyboard: it exposes no dismiss key, and background taps are never attempted (no tap outside the keyboard can be proven side-effect-free)", - hint: keyboardDismissRefusalHint + message: treeUnreadable + ? "Unable to dismiss the keyboard: the screen could not be read and the keyboard itself exposes no dismiss key, and background taps are never attempted" + : "Unable to dismiss the keyboard: it exposes no dismiss key, and background taps are never attempted (no tap outside the keyboard can be proven side-effect-free)", + hint: keyboardDismissRefusalHint, + cause: treeUnreadable ? "tree_unreadable" : nil ) } @@ -501,40 +591,40 @@ extension RunnerTests { #endif } - private func tapKeyboardDismissControl(app: XCUIApplication) -> Bool { -#if os(tvOS) - return false -#else - guard let keyboardFrame = visibleKeyboardFrame(app: app) else { - return false + /// Taps a dismiss control `RunnerKeyboardStatus.dismissControls` admits, and nothing else: never the + /// return key, which submits the focused field, and nothing at all when the keyboard cannot be read. + /// + /// One read decides which controls are candidates. Each candidate is then looked up live by type, + /// label and identifier, the matches kept are those near the keyboard, and the control is tapped only + /// when exactly one remains and it is hittable. A candidate that does not meet that is passed over + /// for the next; when none does, nothing is tapped. No snapshot coordinate is ever tapped. + private func tapKeyboardDismissControl(app: XCUIApplication) -> KeyboardDismissTap { +#if os(iOS) + let read = readKeyboardSurface(app: app) + let none: KeyboardDismissTap = + RunnerKeyboardStatus.refusalIsTreeUnreadable(treeReadable: read.treeReadable, surface: read.surface) + ? .treeUnreadable : .notFound + guard let surface = read.surface else { + return none } - for label in ["Hide keyboard", "Dismiss keyboard", "Done"] { - let candidates = [ - app.keyboards.buttons[label], - app.keyboards.keys[label], - app.keyboards.toolbars.buttons[label], - ] - if let hittable = candidates.first(where: { $0.exists && $0.isHittable }) { - hittable.tap() - return true - } - - let toolbarButtonPredicate = NSPredicate( - format: "label == %@ OR identifier == %@", - label, - label - ) - let toolbarButtons = app.descendants(matching: .button) - .matching(toolbarButtonPredicate) + for control in RunnerKeyboardStatus.dismissControls(in: surface) { + let identifier = control.identifier ?? "" + let predicate = + identifier.isEmpty + ? NSPredicate(format: "label == %@", control.text ?? "") + : NSPredicate(format: "label == %@ AND identifier == %@", control.text ?? "", identifier) + let near = app.descendants(matching: control.kind == .key ? .key : .button) + .matching(predicate) .allElementsBoundByIndex - if let hittable = toolbarButtons.first(where: { - $0.exists && $0.isHittable && isKeyboardAccessoryControl($0, keyboardFrame: keyboardFrame) - }) { - hittable.tap() - return true + .filter { RunnerKeyboardStatus.isNearKeyboard($0.frame, keyboardFrame: surface.frame) } + if near.count == 1, near[0].exists, near[0].isHittable { + near[0].tap() + return .tapped } } - return false + return none +#else + return .notFound #endif } @@ -567,14 +657,6 @@ extension RunnerTests { return false #endif } - - private func isKeyboardAccessoryControl(_ element: XCUIElement, keyboardFrame: CGRect) -> Bool { - let frame = element.frame - guard !frame.isEmpty && !keyboardFrame.isEmpty else { - return false - } - return frame.intersects(keyboardFrame) || abs(frame.maxY - keyboardFrame.minY) <= 80 - } } /// True once the `requiredConsecutiveMatches` most recent samples are all present diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift index 15d4a12c33..ae642c1e8a 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift @@ -712,12 +712,16 @@ struct ErrorPayload: Codable { /// Only on an iOS `BACK_SWIPE_NO_CHANGE`: the dismiss controls in the top band the caller may press /// instead. Absent when there are none. var dismissControls: [DismissControlPayload]? = nil + /// Only on a `KEYBOARD_DISMISS_UNAVAILABLE` whose cause is known: `tree_unreadable` says the screen + /// could not be read, so no dismiss key was found, rather than that the keyboard has none. + var cause: String? = nil private enum CodingKeys: String, CodingKey { case code case message case hint case dismissControls + case cause } static func targetAppUnavailable(bundleId: String?) -> ErrorPayload { diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardReturnKeyTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardReturnKeyTests.swift index 8d743f7dda..aab8522219 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardReturnKeyTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardReturnKeyTests.swift @@ -209,7 +209,7 @@ extension RunnerTests { /// populated here, which is what makes this a real preference rather than the only candidate. func testKeyboardStatusPrefersNamedWordingOverTheSlot() { let keys = observedKeyboardKeysFixture([ - ("Done", 5, 959, 39), (" ", 5, 1121, 197), ("ż", 202, 1121, 198), + ("Q", 5, 959, 39), ("Done", 50, 1067, 39), (" ", 5, 1121, 197), ("ż", 202, 1121, 198), ]) XCTAssertEqual( RunnerKeyboardStatus.observed(visible: true, keyboardKeys: keys), @@ -217,6 +217,160 @@ extension RunnerTests { ) } + /// One keyboard snapshot for the dismiss decision: a phone-sized keyboard unless `frame` says otherwise. + /// `outside` are dismiss-worded buttons the app tree holds beside the keyboard, such as an accessory's. + private func dismissSurface( + keys: [(text: String, x: CGFloat, y: CGFloat, width: CGFloat)], + outside: [(text: String, x: CGFloat, y: CGFloat, width: CGFloat, identifier: String?)] = [], + identifiers: [String: String] = [:], + frame: CGRect = CGRect(x: 0, y: 609, width: 440, height: 240) + ) -> RunnerKeyboardStatus.ObservedKeyboard { + let inside = observedKeyboardKeysFixture(keys).map { key in + RunnerKeyboardStatus.ObservedKeyboardKey( + text: key.text, + frame: key.frame, + identifier: key.text.flatMap { identifiers[$0] } + ) + } + let beside = outside.map { + RunnerKeyboardStatus.ObservedKeyboardKey( + text: $0.text, + frame: CGRect(x: $0.x, y: $0.y, width: $0.width, height: 38), + identifier: $0.identifier, + kind: .button + ) + } + return RunnerKeyboardStatus.ObservedKeyboard(frame: frame, keys: inside + beside) + } + + private func dismissControlFrames(_ surface: RunnerKeyboardStatus.ObservedKeyboard) -> [CGFloat] { + RunnerKeyboardStatus.dismissControls(in: surface).map(\.frame.minY) + } + + /// `keyboard dismiss` never presses a `Done` that could be the return key, which submits the field: + /// a `Done` inside the key rows is refused whether its wording is its label or only its identifier, + /// and the iPad hide-keyboard key is pressed. + func testKeyboardDismissNeverPressesADoneInsideTheKeyRows() { + let phone = dismissSurface( + keys: [("Q", 5, 616, 41), ("space", 108, 784, 207), ("done", 314, 784, 103)], + identifiers: ["done": "Done"] + ) + XCTAssertTrue(RunnerKeyboardStatus.dismissControls(in: phone).isEmpty) + + let pad = dismissSurface( + keys: [ + ("Tab", 6, 905, 81), ("Q", 87, 905, 65), ("Done", 691, 969, 126), ("numbers", 622, 1096, 97), + ("Hide keyboard", 720, 1096, 98), + ], + frame: CGRect(x: 0, y: 880, width: 834, height: 300) + ) + XCTAssertEqual(RunnerKeyboardStatus.dismissControls(in: pad).map(\.text), ["Hide keyboard"]) + } + + /// An accessory is pressed whatever view it is built from, because it is judged by where it sits: + /// a button wholly above the keyboard, with or without character keys to anchor on, or inside the + /// keyboard's frame between the prediction bar and the letter row. A same-wording `Done` far from the + /// keyboard, such as a header or a top toolbar, is not the keyboard's and does not make it ambiguous. + func testKeyboardDismissPressesAnAccessoryBesideAFarAwayDoneWithTheSameIdentity() { + let keys: [(text: String, x: CGFloat, y: CGFloat, width: CGFloat)] = [ + ("Q", 5, 666, 41), ("space", 108, 784, 207), ("done", 314, 784, 103), + ] + let withHeaders = dismissSurface( + keys: keys, + outside: [("Done", 330, 60, 63, nil), ("Done", 330, 524, 63, nil), ("Done", 20, 110, 63, nil)], + identifiers: ["done": "Done"] + ) + XCTAssertEqual(dismissControlFrames(withHeaders), [524]) + + let noCharacterKeys = dismissSurface(keys: [("space", 108, 784, 207)], outside: [("Done", 330, 524, 63, nil)]) + XCTAssertEqual(dismissControlFrames(noCharacterKeys), [524]) + + let betweenQuickTypeAndLetters = dismissSurface( + keys: keys, outside: [("Done", 330, 610, 63, nil)], frame: CGRect(x: 0, y: 549, width: 440, height: 300) + ) + XCTAssertEqual(dismissControlFrames(betweenQuickTypeAndLetters), [610]) + let unanchored = dismissSurface( + keys: [("space", 108, 784, 207)], outside: [("Done", 330, 610, 63, nil)], + frame: CGRect(x: 0, y: 549, width: 440, height: 300) + ) + XCTAssertTrue(RunnerKeyboardStatus.dismissControls(in: unanchored).isEmpty) + } + + /// A key whose label is empty and whose identifier is `Hide keyboard` is still a hide-keyboard control. + func testKeyboardDismissPressesAnIdentifierOnlyHideKey() { + let pad = dismissSurface( + keys: [("Q", 87, 905, 65), ("", 720, 1096, 98)], + identifiers: ["": "Hide keyboard"], + frame: CGRect(x: 0, y: 880, width: 834, height: 300) + ) + XCTAssertEqual(RunnerKeyboardStatus.dismissControls(in: pad).map(\.identifier), ["Hide keyboard"]) + } + + /// Two controls that cannot be told apart near the keyboard are both left out, and the next eligible + /// control is still pressed. A hide-keyboard control far from the keyboard is not the keyboard's. + func testKeyboardDismissSkipsTwinsAndKeepsTheNextControl() { + let pad = dismissSurface( + keys: [("Q", 5, 616, 41), ("Hide keyboard", 700, 1096, 98), ("Hide keyboard", 20, 1096, 98)], + outside: [("Done", 330, 524, 63, nil), ("Hide keyboard", 20, 40, 98, nil)], + frame: CGRect(x: 0, y: 609, width: 834, height: 600) + ) + XCTAssertEqual(RunnerKeyboardStatus.dismissControls(in: pad).map(\.text), ["Done"]) + let onlyTwins = dismissSurface( + keys: [("Q", 5, 616, 41), ("Hide keyboard", 700, 1096, 98), ("Hide keyboard", 20, 1096, 98)], + frame: CGRect(x: 0, y: 609, width: 834, height: 600) + ) + XCTAssertTrue(RunnerKeyboardStatus.dismissControls(in: onlyTwins).isEmpty) + } + + /// A QuickType candidate is a button in the prediction bar above the key rows, so a one-letter one + /// such as `I` or `A` must not pull the key-row anchor up to the bar: only keys anchor. With it + /// anchored on the bar, a `Done` in the key rows could look like an accessory button. + func testKeyboardRowAnchorIgnoresAOneLetterQuickTypeCandidate() { + let candidate = RunnerKeyboardStatus.ObservedKeyboardKey( + text: "I", frame: CGRect(x: 150, y: 560, width: 60, height: 40), kind: .button + ) + let keys = + [candidate] + + observedKeyboardKeysFixture([("Q", 5, 666, 41), ("space", 108, 784, 207), ("done", 314, 784, 103)]) + XCTAssertEqual(RunnerKeyboardStatus.characterKeyRowTop(in: keys), 666) + let keyboard = RunnerKeyboardStatus.ObservedKeyboard(frame: CGRect(x: 0, y: 549, width: 440, height: 300), keys: keys) + XCTAssertTrue(RunnerKeyboardStatus.dismissControls(in: keyboard).isEmpty) + XCTAssertEqual( + RunnerKeyboardStatus.observed(visible: true, keyboardKeys: keys), + RunnerKeyboardStatus(visible: true, returnKey: "done", returnKeyLabel: "done") + ) + XCTAssertNil(RunnerKeyboardStatus.characterKeyRowTop(in: [candidate])) + } + + /// An input accessory toolbar's `Next` or `Done` that the keyboard exposes beside its keys sits above + /// the first key row, so it is never the return key: the real return key is still named. With no + /// character key to place it against, wording alone names nothing, so a pad whose only `Done` is a + /// toolbar button, and a keyboard read without character keys, have no return key. + func testKeyboardReturnControlIgnoresAnAccessoryToolbarAboveTheKeys() { + let phone = observedKeyboardKeysFixture([ + ("Next", 20, 524, 60), ("Q", 5, 616, 41), ("W", 46, 616, 41), (" ", 108, 784, 207), + ("done", 314, 784, 103), + ]) + XCTAssertEqual( + RunnerKeyboardStatus.observed(visible: true, keyboardKeys: phone), + RunnerKeyboardStatus(visible: true, returnKey: "done", returnKeyLabel: "done") + ) + + let pad = observedKeyboardKeysFixture([ + ("Done", 300, 524, 90), ("1", 5, 881, 132), ("2", 136, 881, 132), ("Delete", 268, 1043, 132), + ]) + XCTAssertEqual( + RunnerKeyboardStatus.observed(visible: true, keyboardKeys: pad), + RunnerKeyboardStatus(visible: true, returnKey: "unknown", returnKeyLabel: nil) + ) + + let unanchored = observedKeyboardKeysFixture([("Done", 300, 524, 90), ("space", 108, 784, 207)]) + XCTAssertEqual( + RunnerKeyboardStatus.observed(visible: true, keyboardKeys: unanchored), + RunnerKeyboardStatus(visible: true, returnKey: "unknown", returnKeyLabel: nil) + ) + } + /// A visible keyboard with no return control this read can identify answers `unknown` with no label: /// nothing observed, only keys with no wording (a headless test IME), a space bar with nothing beside /// it, and wording carried only by a zero-frame padding element. @@ -267,6 +421,52 @@ extension RunnerTests { } #if os(iOS) + /// An app snapshot that carries no keyboard node, as a tree too deep to serialize comes back, is an + /// unreadable tree, not a keyboard without keys: the keyboard's own read answers, its hide-keyboard key + /// is the control pressed, and with nothing there the tree is reported unreadable so the refusal says so. + @MainActor + func testAppSnapshotWithoutAKeyboardFallsBackToTheKeyboardsOwnRead() throws { + let screen = CGRect(x: 0, y: 0, width: 834, height: 1194) + let appWithoutKeyboard = ElementAttributesFixture(.application, screen, children: [ + ElementAttributesFixture(.button, CGRect(x: 700, y: 40, width: 80, height: 40), label: "Done") + ]) + let ownRead = RunnerKeyboardStatus.ObservedKeyboard( + frame: CGRect(x: 0, y: 880, width: 834, height: 300), + keys: observedKeyboardKeysFixture([("Q", 87, 905, 65), ("Hide keyboard", 720, 1096, 98)]) + ) + let fallback = resolveKeyboardSurface(appRoot: appWithoutKeyboard, keyboardRead: { ownRead }) + XCTAssertFalse(fallback.treeReadable) + XCTAssertEqual(fallback.surface.map { RunnerKeyboardStatus.dismissControls(in: $0).map(\.text) }, ["Hide keyboard"]) + + let nothing = resolveKeyboardSurface(appRoot: appWithoutKeyboard, keyboardRead: { nil }) + XCTAssertNil(nothing.surface) + XCTAssertFalse(nothing.treeReadable) + + let withKeyboard = ElementAttributesFixture(.application, screen, children: [ + ElementAttributesFixture(.keyboard, ownRead.frame, children: [ + ElementAttributesFixture(.key, CGRect(x: 87, y: 905, width: 65, height: 54), label: "Q") + ]) + ]) + var fellBack = false + let read = resolveKeyboardSurface(appRoot: withKeyboard, keyboardRead: { fellBack = true; return nil }) + XCTAssertTrue(read.treeReadable) + XCTAssertFalse(fellBack) + XCTAssertEqual(read.surface?.frame, ownRead.frame) + + // The refusal blames the tree only when the keyboard's own read held no candidate to try: an empty + // fallback does, a fallback holding a hide key the live lookup then rejects does not, and a readable + // tree never does. + XCTAssertTrue(RunnerKeyboardStatus.refusalIsTreeUnreadable(treeReadable: false, surface: nil)) + XCTAssertTrue( + RunnerKeyboardStatus.refusalIsTreeUnreadable( + treeReadable: false, + surface: RunnerKeyboardStatus.ObservedKeyboard(frame: ownRead.frame, keys: observedKeyboardKeysFixture([("Q", 87, 905, 65)])) + ) + ) + XCTAssertFalse(RunnerKeyboardStatus.refusalIsTreeUnreadable(treeReadable: false, surface: ownRead)) + XCTAssertFalse(RunnerKeyboardStatus.refusalIsTreeUnreadable(treeReadable: true, surface: nil)) + } + /// One snapshot of the keyboard answers the whole read, so the walk has to reach keys nested below /// the keyboard's own children, answer keys before buttons the way two per-type queries did, keep the /// whitespace-only space bar, and drop what carries no wording or is not a key or a button. diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardTests.swift index 1de368fdcb..9ffc22549e 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardTests.swift @@ -154,6 +154,22 @@ extension RunnerTests { XCTAssertNotEqual(dispatched.code, notDispatched.code) } + /// When the app tree could not be read and the keyboard's own read held no dismiss control, the refusal + /// keeps its code and says so with a typed `cause`, so a caller can tell "no dismiss key" from + /// "could not read the screen". A refusal that read the screen, and one that dispatched, carry none. + func testKeyboardDismissRefusalNamesAnUnreadableTree() throws { + let unreadable = keyboardDismissRefusal(dispatchedDismissal: false, treeUnreadable: true) + XCTAssertEqual(unreadable.code, "KEYBOARD_DISMISS_UNAVAILABLE") + XCTAssertEqual(unreadable.cause, "tree_unreadable") + let encoded = try JSONEncoder().encode(unreadable) + XCTAssertEqual( + (try JSONSerialization.jsonObject(with: encoded) as? [String: Any])?["cause"] as? String, + "tree_unreadable" + ) + XCTAssertNil(keyboardDismissRefusal(dispatchedDismissal: false).cause) + XCTAssertNil(keyboardDismissRefusal(dispatchedDismissal: true, treeUnreadable: true).cause) + } + /// `keyboard enter` refusing for having nothing to submit is its own typed refusal, and the host /// reads this code's literal to publish `details.reason`. The wire code alone is the contract. func testKeyboardReturnRefusalNamesItsOwnCode() { @@ -397,6 +413,85 @@ extension RunnerTests { } } + /// A return key labelled `Done` submits the form, so `keyboard dismiss` refuses it as it refuses a + /// keyboard with no dismiss key: nothing is tapped, the field keeps focus, and nothing is submitted. + @MainActor + func testKeyboardDismissNeverPressesADoneReturnKey() throws { + try withDoneReturnField { answer in + XCTAssertEqual(keyboardStatus(app: app).returnKey, "done") + let response = try execute( + command: try runnerCommandFixture(#"{"command":"keyboardDismiss","commandId":"dismiss-done-return"}"#) + ) + + XCTAssertFalse(response.ok) + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.keyboardDismissUnavailable) + XCTAssertEqual(answer.label, "Unanswered") + XCTAssertTrue(isKeyboardVisible(app: app)) + } + } + + /// The `Done` toolbar above the keys is a real dismiss key even when the return key is also `Done`: + /// dismiss presses the toolbar and never submits through the return key. + @MainActor + func testKeyboardDismissPressesTheDoneToolbarNotTheDoneReturnKey() throws { + try assertDismissPressesTheAccessoryDone(shape: "accessory") + } + + /// The same holds for an accessory that is no toolbar, a plain view holding a button as a custom or + /// React Native input accessory is, with the screen's far `Done` carrying the same label. + @MainActor + func testKeyboardDismissPressesAPlainViewAccessoryDone() throws { + try assertDismissPressesTheAccessoryDone(shape: "plain-accessory") + } + + @MainActor + private func assertDismissPressesTheAccessoryDone(shape: String) throws { + try withDoneReturnField(accessory: shape) { answer in + // The return key is identified as the keyboard's own Done key, and the toolbar's Done is a + // different control, so only the toolbar can be pressed. + XCTAssertEqual(keyboardStatus(app: app).returnKey, "done") + let keyboard = try XCTUnwrap(readKeyboard(app: app)) + let returnControl = try XCTUnwrap(RunnerKeyboardStatus.returnControl(in: keyboard.keys)) + let surface = try XCTUnwrap(readKeyboardSurface(app: app).surface) + let toolbarDone = try XCTUnwrap(RunnerKeyboardStatus.dismissControls(in: surface).first) + XCTAssertNotEqual(toolbarDone.frame, returnControl.frame) + let response = try execute( + command: try runnerCommandFixture(#"{"command":"keyboardDismiss","commandId":"dismiss-done-accessory"}"#) + ) + + XCTAssertTrue(response.ok, String(describing: response.error)) + XCTAssertEqual(answer.label, "Accessory") + XCTAssertFalse(isKeyboardVisible(app: app)) + } + } + + @MainActor + private func withDoneReturnField(accessory: String? = nil, _ body: (XCUIElement) throws -> Void) throws { + app.launchArguments = ["--agent-device-keyboard-done-return"] + (accessory.map { [$0] } ?? []) + app.launch() + defer { + invalidateCachedTarget(reason: "unit_test_cleanup") + app.terminate() + } + let field = app.textFields["agent-device-keyboard-done-return-input"] + XCTAssertTrue(field.waitForFixtureExistence(timeout: appExistenceTimeout)) + mainOwned.app = app + mainOwned.bundleId = "com.callstack.agentdevice.runner" + mainOwned.processIdentifier = try XCTUnwrap(Self.processIdentifier(of: app)) + field.tap() + let keyboardDeadline = Date().addingTimeInterval(5) + while !isKeyboardVisible(app: app) && Date() < keyboardDeadline { + sleepFor(0.2) + } + XCTAssertTrue( + isKeyboardVisible(app: app), + "Enable the simulator software keyboard before running the keyboard dismiss tests; see apple/runner/README.md" + ) + let answer = app.staticTexts["agent-device-keyboard-done-return-answer"] + XCTAssertEqual(answer.label, "Unanswered") + try body(answer) + } + @MainActor private func withBusyKeyboardField(_ body: () throws -> Void) throws { app.launchArguments = ["--agent-device-keyboard-busy", String(Self.keyboardBusyBackstop)] diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+ModelsTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+ModelsTests.swift index 981563d98c..2abfd26bb2 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+ModelsTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+ModelsTests.swift @@ -9,7 +9,8 @@ extension RunnerTests { message: "message", hint: "hint", retryableFailure: .targetAppUnavailable, - dismissControls: [DismissControlPayload(label: "Close", identifier: "close", pressBy: .label)] + dismissControls: [DismissControlPayload(label: "Close", identifier: "close", pressBy: .label)], + cause: "tree_unreadable" ) let encoded = try JSONEncoder().encode(payload) let object = try XCTUnwrap(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) diff --git a/apple/runner/RUNNER_PROTOCOL.md b/apple/runner/RUNNER_PROTOCOL.md index 08732576d6..d4bf0bf86e 100644 --- a/apple/runner/RUNNER_PROTOCOL.md +++ b/apple/runner/RUNNER_PROTOCOL.md @@ -304,7 +304,9 @@ next step also carries `hint`, omitted here. A keyboard that stayed up answers o `KEYBOARD_DISMISS_UNAVAILABLE` when it found no dismiss control and so sent nothing, or `UNSUPPORTED_OPERATION` when a dismiss control was tapped, or the tvOS remote's Menu press was sent, and the keyboard stayed visible. The host reports both under `UNSUPPORTED_OPERATION` and publishes the -first one's `details.reason`. +first one's `details.reason`. The first one adds `error.cause: "tree_unreadable"`, which the host +publishes as `details.cause`, when the app tree could not be read and the keyboard's own read held no +dismiss control. Three more refusals name the control the target could not supply, so a caller never reads the refusal off `message`. `KEYBOARD_RETURN_UNAVAILABLE` is a `keyboard enter` whose keyboard exposed no return-like diff --git a/examples/test-app/README.md b/examples/test-app/README.md index 963ae22097..c616b4000f 100644 --- a/examples/test-app/README.md +++ b/examples/test-app/README.md @@ -14,7 +14,7 @@ It is intentionally small, but each surface is dense with durable accessibility - `Home`: visible-text checks, dismissible banner, modal open/close, async loading, status badge, switch state - `Catalog`: search debounce, filter chips, direction-aware scroll canary, favorite toggles, cart updates, drill-in navigation - `Product detail`: back navigation, quantity stepper, multiline notes, save action -- `Checkout form`: required-field validation, fill vs type, checkbox state, choice groups, keyboard dismiss, success summary +- `Checkout form`: required-field validation, fill vs type, checkbox state, choice groups, keyboard enter (the email field's Done return key hides the keyboard), success summary - `Settings`: switch rows, accordion content, loading and error states, retry flow, destructive-confirm modal - `Automation lab`: long-press, alert-result, app-event, app-state, appearance, orientation, permission-recovery, log canaries, a flattened (`accessible={true}`) text input, and an Apple Pay sheet hosted in `com.apple.PassbookUIService` - `WebView accessibility`: a deterministic semantic fixture plus live websites with varied HTML for native accessibility snapshot verification diff --git a/examples/test-app/replays/checkout-form.ad b/examples/test-app/replays/checkout-form.ad index 4c89212dfa..0a241330c3 100644 --- a/examples/test-app/replays/checkout-form.ad +++ b/examples/test-app/replays/checkout-form.ad @@ -8,7 +8,7 @@ click "label=\"Form\"" wait "Checkout form" 5000 fill id="field-name" "Ada Lovelace" fill id="field-email" "ada@example.com" -keyboard dismiss +keyboard enter wait "Checkout form" 5000 scroll down 0.6 click id="shipping-pickup" diff --git a/examples/test-app/src/screens/FormScreen.tsx b/examples/test-app/src/screens/FormScreen.tsx index 0315ee094c..675e952d2f 100644 --- a/examples/test-app/src/screens/FormScreen.tsx +++ b/examples/test-app/src/screens/FormScreen.tsx @@ -101,7 +101,7 @@ export function FormScreen(props: FormScreenProps) { ) : null} { assert.equal(error.details?.dismissControls, undefined); assert.equal(error.details?.hint, RUNNER_HINT); }); + +test('a keyboard dismiss refusal says when the screen could not be read, and only then', () => { + const refusal = (code: string, cause?: unknown) => + buildRunnerResponseError({ + ok: false, + error: { code, message: 'Unable to dismiss the keyboard.', cause }, + }); + const unreadable = refusal('KEYBOARD_DISMISS_UNAVAILABLE', 'tree_unreadable'); + assert.equal(unreadable.details?.reason, 'keyboard_dismiss_unavailable'); + assert.equal(unreadable.details?.dispatched, 'no'); + assert.equal(unreadable.details?.cause, 'tree_unreadable'); + assert.equal('cause' in (refusal('KEYBOARD_DISMISS_UNAVAILABLE').details ?? {}), false); + assert.equal( + 'cause' in (refusal('KEYBOARD_DISMISS_UNAVAILABLE', 'something_else').details ?? {}), + false, + ); + assert.equal( + 'cause' in (refusal('KEYBOARD_RETURN_UNAVAILABLE', 'tree_unreadable').details ?? {}), + false, + ); +}); diff --git a/packages/apple-runner/src/runner-contract.ts b/packages/apple-runner/src/runner-contract.ts index f71f3f785f..27f8d4a7f1 100644 --- a/packages/apple-runner/src/runner-contract.ts +++ b/packages/apple-runner/src/runner-contract.ts @@ -555,7 +555,13 @@ export function classifyRunnerReportedError( export type RunnerResponsePayload = { ok?: unknown; - error?: { code?: unknown; message?: unknown; hint?: unknown; dismissControls?: unknown }; + error?: { + code?: unknown; + message?: unknown; + hint?: unknown; + dismissControls?: unknown; + cause?: unknown; + }; data?: unknown; }; @@ -658,10 +664,17 @@ export function buildRunnerResponseError( const hint = typeof payload.error?.hint === 'string' ? payload.error.hint : undefined; const classification = classifyRunnerReportedError(runnerErrorCode); const dismissControls = readBackDismissControls(runnerErrorCode, payload.error); + // Only the dismiss refusal carries a cause: `tree_unreadable`, the screen could not be read. + const cause = + runnerErrorCode === KEYBOARD_DISMISS_UNAVAILABLE_RUNNER_CODE && + payload.error?.cause === 'tree_unreadable' + ? 'tree_unreadable' + : undefined; return new AppError(classification.code, errorMessage ?? 'Runner error', { runner: payload, ...classification.details, ...(dismissControls.length > 0 ? { dismissControls } : {}), + ...(cause === undefined ? {} : { cause }), xcodebuild: { exitCode: 1, stdout: '', diff --git a/packages/command-surface/src/system/index.ts b/packages/command-surface/src/system/index.ts index 2bf08dc1bd..708df0273c 100644 --- a/packages/command-surface/src/system/index.ts +++ b/packages/command-surface/src/system/index.ts @@ -319,7 +319,7 @@ const foldCommandDescription = `Fold or unfold a foldable iPhone simulator (iPho const appSwitcherCommandDescription = 'Open the device app switcher to inspect or change foreground apps. This changes the visible system UI and may move focus away from the current app.'; const keyboardCommandDescription = - "Report or act on the device keyboard. The status action reports whether the keyboard is visible and, when it is, what its return key offers: `returnKey` is go, search, send, next, done, previous, join, route, continue, enter, none, or unknown, and `returnKeyLabel` is the wording that return key itself shows when the platform can read it, trimmed of surrounding whitespace, which can be an app's custom or a localized string. A label appears only for a key the platform identified as the return key. `none` means the field offers no action key, which only Android can establish; `unknown` means this read could not name the key, not that the keyboard has one: on iOS the identified key carries wording this read does not map, or the keyboard exposes no return key it can identify at all — a number, decimal or phone pad has none, and then no label is reported either; on Android the editor's imeOptions name no action. A hidden keyboard reports neither field. The get action answers the same as status. The dismiss action hides the keyboard. It taps the keyboard dismiss/hide key when one is exposed, verifies the keyboard closed, and reports UNSUPPORTED_OPERATION when the keyboard stays up \u2014 background taps are never attempted. On iOS a keyboard with no dismiss key adds error.details.reason keyboard_dismiss_unavailable with dispatched: no; one whose key was tapped and stayed visible has no reason and dispatched: unknown. Android reports keyboard_dismiss_unavailable with dispatched: unknown, since its own dismiss keyevents were already sent. The enter action presses the return key."; + "Report or act on the device keyboard. The status action reports whether the keyboard is visible and, when it is, what its return key offers: `returnKey` is go, search, send, next, done, previous, join, route, continue, enter, none, or unknown, and `returnKeyLabel` is the wording that return key itself shows when the platform can read it, trimmed of surrounding whitespace, which can be an app's custom or a localized string. A label appears only for a key the platform identified as the return key. `none` means the field offers no action key, which only Android can establish; `unknown` means this read could not name the key, not that the keyboard has one: on iOS the identified key carries wording this read does not map, or the keyboard exposes no return key it can identify at all — a number, decimal or phone pad has none, and then no label is reported either; on Android the editor's imeOptions name no action. A hidden keyboard reports neither field. The get action answers the same as status. The dismiss action hides the keyboard. It taps the keyboard dismiss/hide key when one is exposed, verifies the keyboard closed, and reports UNSUPPORTED_OPERATION when the keyboard stays up \u2014 background taps are never attempted. It never presses the return key, so it never submits the focused field: on iOS the key that status identifies as the return key is excluded whatever it reads, including Done, while the iPad hide-keyboard key and a Done toolbar above the key rows remain dismiss keys, and a Done among the key rows is never pressed, and without a readable key row a Done inside the keyboard is refused (keyboard_dismiss_unavailable) while the hide-keyboard key and a Done wholly above the keyboard still dismiss, and error.details.cause tree_unreadable adds that the screen could not be read and the keyboard's own read held no dismiss key. Use enter or return to submit. On iOS a keyboard whose only candidate is its return key counts as having no dismiss key and adds error.details.reason keyboard_dismiss_unavailable with dispatched: no; one whose key was tapped and stayed visible has no reason and dispatched: unknown. Android reports keyboard_dismiss_unavailable with dispatched: unknown, since its own dismiss keyevents were already sent. The enter action presses the return key."; const clipboardCommandDescription = 'Read the current device clipboard text, or replace its contents with the given text. Android runs both through the clipboard service shell command, and a build that implements none (Android 16 does not) refuses with UNSUPPORTED_OPERATION rather than reporting an empty clipboard.'; const actionButtonCommandDescription = @@ -723,7 +723,7 @@ const keyboardCommandFacet = defineCommandFacet({ effect: 'destructive', text: { summary: 'Inspect, press, or dismiss the device keyboard', - searchHint: 'ime gboard submit', + searchHint: 'ime gboard', }, metadata: keyboardCommandMetadata, run: (client, input) => client.command.keyboard(input), diff --git a/scripts/perf/suite.ts b/scripts/perf/suite.ts index 33a219af36..e6881baf19 100644 --- a/scripts/perf/suite.ts +++ b/scripts/perf/suite.ts @@ -301,10 +301,13 @@ export const SUITE: readonly SuiteScenario[] = [ step('fill-name', C.fill, ['fill', 'id="field-name"', 'Ada Lovelace']), step('fill-email', C.fill, ['fill', 'id="field-email"', 'ada@example']), step('type-suffix', C.type, ['type', '.test']), - step('keyboard-dismiss', C.keyboard, ['keyboard', 'dismiss'], { + // iOS's only Done key is the field's return key, which `keyboard dismiss` never presses, so + // `keyboard enter` submits the field and hides the keyboard. Android emulators type through the + // headless test IME, which has no Done key, so `keyboard dismiss` hides it. The step id stays + // `keyboard-dismiss` because the harness keys every sample by it, and a rename drops its baseline. + step('keyboard-dismiss', C.keyboard, ['keyboard', 'enter'], { before: [['wait', 'label="Done" visible=true', '10000']], - // Android emulators type through the headless test IME, which has no Done key. - on: { android: { before: [] } }, + on: { android: { args: ['keyboard', 'dismiss'], before: [] } }, }), step('press-checkbox', C.press, ['press', 'id="checkbox-agree"'], { before: [['scroll', 'down', '--until', 'id="checkbox-agree"']], diff --git a/test/integration/command-coverage/declarations.ts b/test/integration/command-coverage/declarations.ts index c306bcc0f9..6d02e32e91 100644 --- a/test/integration/command-coverage/declarations.ts +++ b/test/integration/command-coverage/declarations.ts @@ -453,7 +453,7 @@ const COMMAND_COVERAGE_DECLARATIONS = { ), iosSimulator: iosSimulator.live( 'smoke:form-input', - 'real keyboard dismissal reports dismissed=true and visible=false', + 'a Done return key is refused by dismiss untapped and hidden by enter', ), macos: macos.contract( APPLE_NAVIGATION_FACTS_EVIDENCE.path, diff --git a/test/integration/ios-simulator-e2e/README.md b/test/integration/ios-simulator-e2e/README.md index 26eb5116b1..3ec1f17f22 100644 --- a/test/integration/ios-simulator-e2e/README.md +++ b/test/integration/ios-simulator-e2e/README.md @@ -37,7 +37,7 @@ Automatic confirmation remains covered by the launch-confirmation and lifecycle Use semantic readiness landmarks before interaction. A title alone can precede the React tab controls. -Before testing keyboard dismissal, require the fixture's visible Done control. +Before testing keyboard dismissal, require the fixture's visible Done return key. `keyboard dismiss` refuses it, and `keyboard enter` submits. Enable the simulator software keyboard for that lifecycle contract. For intentionally truncated raw-depth assertions, validate the structural frontier; require semantic capture quality on regular and full-raw observations. Use the built CLI for preparation and execution after building once. diff --git a/test/integration/ios-simulator-e2e/live-runner.ts b/test/integration/ios-simulator-e2e/live-runner.ts index 5607b85394..bb91f3af7d 100644 --- a/test/integration/ios-simulator-e2e/live-runner.ts +++ b/test/integration/ios-simulator-e2e/live-runner.ts @@ -329,40 +329,52 @@ async function assertFormInput(context: LiveContext): Promise { await runStep(context, 'seed email field', ['fill', 'id="field-email"', 'ada@example']); // Pins the exact point a truncated field value first appears, rather than inferring it from - // the final read. If this fails, `fill` itself lost the seed — the dismiss/refocus/type steps + // the final read. If this fails, `fill` itself lost the seed — the submit/refocus/type steps // below never ran on the wrong content in the first place. - const seededEmail = await runStep(context, 'read seeded email before dismiss', [ + const seededEmail = await runStep(context, 'read seeded email before submit', [ 'get', 'attrs', 'id="field-email"', ]); - assertJsonContains( - seededEmail, - 'ada@example', - 'seeded email should be observable before dismiss', - ); + assertJsonContains(seededEmail, 'ada@example', 'seeded email should be observable before submit'); await assertWaitSelector(context, 'label="Done" visible=true'); const keyboardVisiblePath = path.join(context.artifactDir, 'keyboard-visible.png'); await capturePng(context, 'capture visible input keyboard', keyboardVisiblePath); - const keyboard = await runStep(context, 'dismiss input keyboard', ['keyboard', 'dismiss']); - assert.equal(keyboard.json?.data?.dismissed, true, JSON.stringify(keyboard.json)); - assert.equal(keyboard.json?.data?.visible, false, JSON.stringify(keyboard.json)); + // The email field's return key reads "Done" and submits, so `keyboard dismiss` must refuse it + // untapped; `keyboard enter` is the way to submit, and this field's submit hides the keyboard. + const refused = await runStep( + context, + 'refuse to dismiss through the Done return key', + ['keyboard', 'dismiss'], + { allowFailure: true }, + ); + assert.equal(refused.json?.success, false, JSON.stringify(refused.json)); + assert.equal( + refused.json?.error?.details?.reason, + 'keyboard_dismiss_unavailable', + JSON.stringify(refused.json), + ); + assert.equal(refused.json?.error?.details?.dispatched, 'no', JSON.stringify(refused.json)); + await runStep(context, 'submit input keyboard through its return key', ['keyboard', 'enter']); + await runStep(context, 'let the keyboard finish hiding', ['wait', '1000']); + const hidden = await runStep(context, 'read keyboard after submit', ['keyboard', 'status']); + assert.equal(hidden.json?.data?.visible, false, JSON.stringify(hidden.json)); const keyboardHiddenPath = path.join(context.artifactDir, 'keyboard-hidden.png'); - await capturePng(context, 'capture dismissed input keyboard', keyboardHiddenPath); + await capturePng(context, 'capture hidden input keyboard', keyboardHiddenPath); assertFilesDiffer( keyboardVisiblePath, keyboardHiddenPath, - 'keyboard dismissal should change simulator pixels', + 'hiding the keyboard should change simulator pixels', ); verifyCommand( context, C.keyboard, - 'dismiss reports dismissed=true and visible=false while before/after pixels differ', + 'dismiss refuses a Done return key untapped, and enter hides the keyboard while before/after pixels differ', ); - // Pins whether `keyboard dismiss` itself clears the field, independent of the coordinate + // Pins whether the keyboard hiding itself clears the field, independent of the coordinate // refocus + type steps that follow. - const emailAfterDismiss = await runStep(context, 'read email after dismiss', [ + const emailAfterDismiss = await runStep(context, 'read email after submit', [ 'get', 'attrs', 'id="field-email"', @@ -370,7 +382,7 @@ async function assertFormInput(context: LiveContext): Promise { assertJsonContains( emailAfterDismiss, 'ada@example', - 'seeded email should survive keyboard dismiss, before any refocus or further typing', + 'seeded email should survive the keyboard hiding, before any refocus or further typing', ); const formSnapshot = await runStep(context, 'locate email coordinates', [ @@ -400,7 +412,7 @@ async function assertFormInput(context: LiveContext): Promise { verifyBehavior( context, 'text-entry-keyboard-lifecycle', - 'fill showed the keyboard, dismissal changed pixels, and coordinate focus enabled typed text', + 'fill showed the keyboard, enter hid it and changed pixels, and coordinate focus enabled typed text', ); verifyCommand(context, C.focus, 'snapshot-derived coordinate focus directs subsequent typing'); verifyCommand( @@ -413,9 +425,9 @@ async function assertFormInput(context: LiveContext): Promise { } async function assertSnapshotBackendConformanceLive(context: LiveContext): Promise { - await runStep(context, 'dismiss keyboard before backend conformance capture', [ + await runStep(context, 'submit keyboard before backend conformance capture', [ 'keyboard', - 'dismiss', + 'enter', ]); const fixture = loadSnapshotBackendConformanceFixture(); const createAgentDeviceClient = await loadBuiltAgentDeviceClient(); diff --git a/test/integration/replays/ios/fixture/02-checkout-release.ad b/test/integration/replays/ios/fixture/02-checkout-release.ad index 796c975673..dea2e13ecd 100644 --- a/test/integration/replays/ios/fixture/02-checkout-release.ad +++ b/test/integration/replays/ios/fixture/02-checkout-release.ad @@ -9,7 +9,7 @@ click "label=\"Form\"" wait "Checkout form" 5000 fill id="field-name" "Ada Lovelace" fill id="field-email" "ada@example.com" -keyboard dismiss +keyboard enter wait "Checkout form" 5000 swipe 190 480 190 180 is visible id="shipping-pickup" diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 7c62cb093f..8c33dbcc03 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -943,8 +943,8 @@ agent-device keyboard enter ``` - `keyboard status` (or `keyboard get`) reports whether the keyboard is visible, on every platform that serves the command. On a visible keyboard it also reports `returnKey` — what that keyboard's return key offers, as `go`, `search`, `send`, `next`, `done`, `previous`, `join`, `route`, `continue`, `enter`, `none`, or `unknown` — and `returnKeyLabel`, the wording the key itself shows where the platform can read it, trimmed of surrounding whitespace, which can be an app's custom or a localized string. A label appears only for a key the platform identified as the return key. `none` means the field offers no action key, which only Android establishes. `unknown` means the read could not name the visible keyboard's return key, not that one is there: on iOS the key it identified carries wording this read does not map (its label is still reported), or the keyboard exposes no return key it can identify at all — a number, decimal or phone pad has none, and an iPad keyboard keeps numbers and hide keys in the slot the rule reads — and then there is no label either; on Android it means the editor's `imeOptions` named no action. Treat it as "read the keyboard before submitting", not as a safe key to press. A hidden keyboard reports neither field. Android adds its best-effort input type and IME fields; iOS adds nothing else. -- `keyboard enter` presses the return key. -- `keyboard dismiss` taps a safe control such as `Done` when available and checks that the keyboard closed. It works on Android and, best-effort, on iOS simulators and devices. Both report `UNSUPPORTED_OPERATION` when the keyboard stays up. On iOS, a keyboard that exposes no dismiss control adds `error.details.reason: keyboard_dismiss_unavailable` with `dispatched: no`, because nothing was tapped; one whose control was tapped and stayed open has no `reason` and `dispatched: unknown`. Android reports `error.details.reason: keyboard_dismiss_unavailable` with `dispatched: unknown` — its escape keyevents were already sent — alongside its own `attempts` and IME fields. Either way, press a visible app control such as `Done` only when that is the intended fallback. +- `keyboard enter` (or `keyboard return`) presses the return key. It is the way to submit the focused field. +- `keyboard dismiss` taps the keyboard's own dismiss control, such as the iPad hide-keyboard key or a `Done` toolbar above the key rows, and checks that the keyboard closed. It never presses the return key: on iOS the key that `keyboard status` identifies as the return key is excluded whatever it reads, including `Done`, because pressing it submits the focused field. A `Done` among the key rows is never pressed. Without a readable key row, a `Done` inside the keyboard is refused with `keyboard_dismiss_unavailable` (`dispatched: no`), while the hide-keyboard key and a `Done` accessory wholly above the keyboard still dismiss. When the app tree could not be read and the keyboard's own read held no dismiss key, the refusal adds `error.details.cause: tree_unreadable`, so a caller can tell "no dismiss key" from "could not read the screen". A field whose only `Done` is its return key refuses with `keyboard_dismiss_unavailable` (`dispatched: no`); use `keyboard enter` when submitting is what you want. It works on Android and, best-effort, on iOS simulators and devices. Both report `UNSUPPORTED_OPERATION` when the keyboard stays up. On iOS, a keyboard that exposes no dismiss control adds `error.details.reason: keyboard_dismiss_unavailable` with `dispatched: no`, because nothing was tapped; one whose control was tapped and stayed open has no `reason` and `dispatched: unknown`. Android reports `error.details.reason: keyboard_dismiss_unavailable` with `dispatched: unknown` — its escape keyevents were already sent — alongside its own `attempts` and IME fields. Either way, press a visible app control such as `Done` only when that is the intended fallback. - Works with the session device or a device selector (`--platform`, `--device`, `--udid`, `--serial`). ## Performance diagnostics