diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerAppFixtures.m b/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerAppFixtures.m index fe58e73e50..b2c46d0a0e 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerAppFixtures.m +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerAppFixtures.m @@ -11,6 +11,7 @@ #import "AgentDeviceRunnerApp.h" #import #import +#import #import "UnitTests/AgentDeviceTextEntryFields.h" // Mirrors the App Tracking Transparency prompt's real button order: the affirmative button is @@ -988,14 +989,29 @@ - (void)viewDidLoad { 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; + if ([launchArguments containsObject:@"--agent-device-keyboard-webview"]) { + WKWebView *webView = [[WKWebView alloc] init]; + webView.translatesAutoresizingMaskIntoConstraints = NO; + [self.view addSubview:webView]; + UILayoutGuide *safeArea = self.view.safeAreaLayoutGuide; + [NSLayoutConstraint activateConstraints:@[ + [webView.topAnchor constraintEqualToAnchor:safeArea.topAnchor], + [webView.leadingAnchor constraintEqualToAnchor:safeArea.leadingAnchor], + [webView.trailingAnchor constraintEqualToAnchor:safeArea.trailingAnchor], + [webView.bottomAnchor constraintEqualToAnchor:safeArea.bottomAnchor], + ]]; + [webView loadHTMLString:@"" + "" + "

No Return

" + "" + baseURL:nil]; + } 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"; @@ -1011,22 +1027,7 @@ - (void)viewDidLoad { [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) { + if ([accessoryShape isEqualToString:@"accessory"]) { UIToolbar *accessory = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; accessory.items = @[ [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace @@ -1044,19 +1045,19 @@ - (void)viewDidLoad { 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. + if ([accessoryShape isEqualToString:@"adjacent-app-button"]) { UIButton *screenDone = [UIButton buttonWithType:UIButtonTypeSystem]; + screenDone.accessibilityIdentifier = @"agent-device-adjacent-done"; [screenDone setTitle:@"Done" forState:UIControlStateNormal]; [screenDone addAction:[UIAction actionWithHandler:^(__kindof UIAction *action) { weakAnswer.text = @"Screen"; + [weakField resignFirstResponder]; }] forControlEvents:UIControlEventTouchUpInside]; screenDone.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:screenDone]; [NSLayoutConstraint activateConstraints:@[ - [screenDone.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:8], + [screenDone.bottomAnchor constraintEqualToAnchor:self.view.keyboardLayoutGuide.topAnchor constant:-6], [screenDone.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16], ]]; } diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardReturnKey.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardReturnKey.swift index ce850e8d65..0a210d23d5 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardReturnKey.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardReturnKey.swift @@ -1,26 +1,6 @@ import Foundation -/// What the keyboard's return key offers, read from the key's own label or identifier. -/// -/// The key is the app's declaration of what submitting the focused field does, and only the app -/// can answer that: `UITextInput.returnKeyType` reaches the keyboard as one of Apple's return-key -/// types, whose English wording is what XCTest exposes. This maps that wording to one stable kind. -/// -/// Exact, case-insensitive matches only. An unlisted label stays `.unknown` rather than being -/// guessed: iOS localizes these keys unevenly, so a prefix or fuzzy rule would report a localized -/// "Done" as something else. Absence is not a kind either — only a control this module cannot read -/// is `.unknown`; a keyboard with no return control is reported by the caller that looked for one. -/// -/// Three of Apple's return-key types are deliberately unmapped and answer `.unknown`: `Google` and -/// `Yahoo` are vendor-branded keys whose wording names a vendor rather than a submit action, and -/// `Emergency Call` places a call, which no caller of this should ever report as a submit. Every -/// other Apple type has a case above. -/// -/// `probeLabels` is the order `findKeyboardReturnControl(app:)` presses in. It is the -/// runner's own vocabulary, so it is not derived from the cases: it carries the two spellings of the -/// plain return key, in the order that found a hittable control before this rule existed. The -/// `keyboard status` read does not use it: it reads the keyboard's own key elements, so it needs no -/// English to find the return key. +/// The known identifiers of system Return controls. The displayed label can be localized. enum RunnerKeyboardReturnKey: String { case go case search @@ -33,13 +13,9 @@ enum RunnerKeyboardReturnKey: String { case enter case unknown - /// The keyboard control labels `findKeyboardReturnControl(app:)` tries, in order. - static let probeLabels = ["return", "Return", "Enter", "Go", "Search", "Next", "Done", "Send", "Join"] - - /// The kind an accessibility label or identifier names. Surrounding whitespace is trimmed - /// because the accessibility tree carries it; nothing else is normalized. - static func kind(of text: String) -> RunnerKeyboardReturnKey { - switch text.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { + /// Classify an observed accessibility identifier for status metadata. + static func kind(forIdentifier identifier: String) -> RunnerKeyboardReturnKey { + switch identifier.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { case "go": return .go case "search": return .search case "send": return .send diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardStatus.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardStatus.swift index 3799e00028..634b29aaf7 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardStatus.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardStatus.swift @@ -1,238 +1,68 @@ -import Foundation import CoreGraphics +import Foundation +import AgentDeviceSnapshotPresentation -/// One `keyboard status` answer: whether the software keyboard is on screen and, when it is, what -/// its return key offers. -/// -/// `returnKey` is a `RunnerKeyboardReturnKey` raw value, or `nil` when the keyboard is hidden — a -/// hidden keyboard has no return key to report, which is a different fact from one this read cannot -/// name. `returnKeyLabel` is the wording the return key itself carries, with surrounding whitespace -/// trimmed, so a localized or an app's custom key stays readable even where the kind is `unknown`. -/// It is present only for a control this read identified as the return key: a keyboard whose return -/// key cannot be identified — a number or phone pad has none — answers `unknown` with no label, so a -/// caller is never told a key exists on a layout that has no key to press. struct RunnerKeyboardStatus: Equatable { let visible: Bool let returnKey: String? let returnKeyLabel: String? -} -extension RunnerKeyboardStatus { - /// One control the status read observed on the visible keyboard: the wording it carries in the - /// accessibility tree, and the frame it occupies. `frame` is what locates the return key by slot — - /// the space bar's immediate right neighbour, when that neighbour is also its row's last worded key. - 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 - } - } + static let hidden = RunnerKeyboardStatus(visible: false, returnKey: nil, returnKeyLabel: nil) + private static let visibleWithUnknownReturn = RunnerKeyboardStatus(visible: true, returnKey: "unknown", returnKeyLabel: nil) - /// 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 { + struct ObservedKeyboardKey { + let label: String + let identifier: String let frame: CGRect - let keys: [ObservedKeyboardKey] + let isKey: Bool } - /// What identifies Apple's space bar in the accessibility tree: wording that is whitespace and - /// nothing else. This read measured a single space on an English and a Polish iOS layout, so the - /// anchor survives the localization the positional rule exists for. A pad's keys all carry digit or - /// `Delete` wording, so a pad has no anchor, and therefore no candidate. - private static func isSpaceBar(_ text: String?) -> Bool { - guard let text, !text.isEmpty else { return false } - return text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - } - - /// Builds the answer from what the runner observed. The keyboard decides whether a return key is - /// reported at all: a hidden one has none, which is a different fact from one this read cannot - /// name. Only Android's `IME_ACTION_NONE` can establish that a field offers no action key, so - /// `none` is never this runner's answer. - /// - /// The key's own wording decides the kind, through the one rule `keyboard enter` probes with - /// (`RunnerKeyboardReturnKey.kind(of:)`), so the two commands can never disagree about the same - /// key. The label itself is kept as the accessibility tree carries it apart from its surrounding - /// whitespace, so a localized or an app's custom key stays readable even where the kind is - /// `unknown`. + /// An iPad accessory can appear as the keyboard while its keys sit below the display. static func observed( - visible: Bool, - returnControlText: String? - ) -> RunnerKeyboardStatus { - guard visible else { - return RunnerKeyboardStatus(visible: false, returnKey: nil, returnKeyLabel: nil) + keyboardFrame: CGRect, + keys: [ObservedKeyboardKey], + nativeDisplaySize: CGSize?, + interfaceOrientation: Int + ) -> RunnerKeyboardStatus? { + guard SnapshotGeometry.isPositiveFinite(keyboardFrame), + let nativeDisplaySize, + let frame = SurfaceGeometry.panelFrame(nativeSize: nativeDisplaySize, orientation: interfaceOrientation), + case .reported(let bounds, _) = SnapshotViewport.reported(box: frame) + else { return nil } + let space = keyboardSpace(keyboardFrame, displayBounds: bounds, interfaceOrientation: interfaceOrientation) + let visibleFrame = space.orientedFrame(of: keyboardFrame).intersection(bounds.rect) + guard SnapshotGeometry.isPositiveFinite(visibleFrame) else { return .hidden } + + let measuredKeys = keys.compactMap { key -> ObservedKeyboardKey? in + guard SnapshotGeometry.isPositiveFinite(key.frame) else { return nil } + return ObservedKeyboardKey(label: key.label, identifier: key.identifier, frame: space.orientedFrame(of: key.frame), isKey: key.isKey) } - guard let returnControlText else { - return RunnerKeyboardStatus( - visible: true, - returnKey: RunnerKeyboardReturnKey.unknown.rawValue, - returnKeyLabel: nil - ) + let visibleKeys = measuredKeys.filter { visibleFrame.contains(CGPoint(x: $0.frame.midX, y: $0.frame.midY)) } + guard let firstKeyY = visibleKeys.filter(\.isKey).map(\.frame.minY).min() else { + return measuredKeys.contains(where: \.isKey) ? .hidden : .visibleWithUnknownReturn } - let label = returnControlText.trimmingCharacters(in: .whitespacesAndNewlines) - return RunnerKeyboardStatus( - visible: true, - returnKey: RunnerKeyboardReturnKey.kind(of: label).rawValue, - returnKeyLabel: label.isEmpty ? nil : label - ) - } - - /// Builds the answer from every control the read saw on the visible keyboard, so it does not need to - /// read English to find the return key. A control whose wording `kind(of:)` names a kind for is the - /// return key on any keyboard in any language, and its wording is the label. When none maps — a fully - /// localized keyboard — the return key is the control in the slot Apple's keyboards give it: the - /// keyboard's `returnKeySlot`, the space bar's immediate right neighbour where that neighbour is also - /// its row's trailing worded control. - /// - /// The slot is anchored on the space bar rather than on the keyboard's bottom-right corner because - /// the corner is not the return key on every layout: a number, decimal or phone pad has no space bar - /// and puts Delete in that corner, so reporting the corner would tell a caller an OTP field has a - /// return key. The trailing half of the test is what keeps the rule off iPadOS, whose bottom row puts - /// a numbers key and then a hide-keyboard key right of the space bar while its return key ends the row - /// above. Neither case reports a key. - /// - /// `returnKeyLabel` therefore comes only from a control this read identified as the return key. A - /// visible keyboard with no identifiable return control answers `unknown` with no label, which is the - /// honest reading of a pad that has no return key at all, and of a layout this rule does not know. - static func observed( - visible: Bool, - keyboardKeys: [ObservedKeyboardKey] - ) -> RunnerKeyboardStatus { - guard visible else { - return RunnerKeyboardStatus(visible: false, returnKey: nil, returnKeyLabel: nil) - } - 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 + let returnKeys = visibleKeys.compactMap { key -> (RunnerKeyboardReturnKey, String)? in + let kind = RunnerKeyboardReturnKey.kind(forIdentifier: key.identifier) + guard kind != .unknown, key.frame.maxY > firstKeyY else { return nil } + return (kind, key.label.trimmingCharacters(in: .whitespacesAndNewlines)) } - 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 - } + guard returnKeys.count == 1, let (kind, label) = returnKeys.first else { + return .visibleWithUnknownReturn } + return RunnerKeyboardStatus(visible: true, returnKey: kind.rawValue, returnKeyLabel: label.isEmpty ? nil : label) } - /// The worded control in the return key's slot, or `nil` when the keyboard exposes no space bar to - /// anchor the slot on, or when the space bar's right neighbour is not also its row's trailing worded - /// control. One positional test, both halves, and no wording list: see `observed(visible:keyboardKeys:)` - /// for why the anchor is the space bar, and why a neighbour that is not its row's trailing key cannot - /// be the return key. - private static func returnKeySlot(in keys: [ObservedKeyboardKey]) -> ObservedKeyboardKey? { - // The space bar is the widest key on Apple's keyboards by several times any other, so taking the - // widest whitespace-worded control cannot mistake a padding or divider element for it. - guard let spaceBar = keys - .filter({ isSpaceBar($0.text) && !$0.frame.isEmpty }) - .max(by: { $0.frame.width < $1.frame.width }) - else { - return nil - } - let spaceEdge = spaceBar.frame.maxX - let spaceMidY = spaceBar.frame.midY - // Worded, measurable controls in the space bar's row, at or right of its right edge. The tolerance - // absorbs the fractions of a point a layout may round away between keys that sit edge to edge. The - // space bar is never among them: its wording is whitespace, which no return key's wording ever is. - let rightOfSpaceBar = keys.filter { key in - !key.frame.isEmpty - && !(key.text ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - && key.frame.minY <= spaceMidY - && key.frame.maxY >= spaceMidY - && key.frame.minX >= spaceEdge - returnKeySlotTolerance - } - // Both halves of the one rule: the nearest such control, and the last of them, must be the same key. - let ordered = rightOfSpaceBar.sorted { ($0.frame.minX, $0.frame.maxX) < ($1.frame.minX, $1.frame.maxX) } - guard let first = ordered.first, let last = ordered.last, first.frame == last.frame else { - return nil - } - return first + /// A landscape iPhone can report a vertical key plane in portrait display coordinates. + private static func keyboardSpace( + _ frame: CGRect, displayBounds: SnapshotViewport.Box, interfaceOrientation: Int + ) -> SnapshotGeometrySpace { + let bounds = displayBounds.rect + guard SnapshotGeometrySpace.namesQuarterTurn(interfaceOrientation), + bounds.width > bounds.height, + frame.height > frame.width, !bounds.contains(frame), + CGRect(x: 0, y: 0, width: bounds.height, height: bounds.width).contains(frame) + else { return .appOrientation } + return .deviceNative(appFrame: displayBounds, interfaceOrientation: interfaceOrientation) } - - /// Keys sit edge to edge, so the slot's left edge is the space bar's right edge; this absorbs the - /// fractions of a point a keyboard's layout may round away. - private static let returnKeySlotTolerance: CGFloat = 2 } diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift index 59c958226e..03d14d5996 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift @@ -593,72 +593,48 @@ extension RunnerTests { ) } return Response(ok: true, data: DataPayload(message: command.command.rawValue)) - case .keyboardDismiss: - var dismissal: RunnerKeyboardDismissOutcome? + case .keyboardDismiss, .keyboardStatus: + var status: RunnerKeyboardStatus? withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .bothSkipped) { - dismissal = dismissKeyboard(app: activeApp) - } - guard let result = dismissal else { - return Response(ok: false, error: ErrorPayload(message: "keyboardDismiss produced no result")) + status = keyboardStatus(app: activeApp) } - if result.wasVisible && !result.dismissed { - return Response( - ok: false, - error: keyboardDismissRefusal( - dispatchedDismissal: result.dispatchedDismissal, - treeUnreadable: result.treeUnreadable - ) - ) + guard let status else { + return Response(ok: false, error: ErrorPayload( + code: "OBSERVATION_UNAVAILABLE", + message: "Could not determine whether the software keyboard is visible", + hint: "Take a screenshot or try keyboard status again." + )) } - return Response( - ok: true, - data: DataPayload( - message: "keyboardDismiss", - visible: result.visible, - wasVisible: result.wasVisible, - dismissed: result.dismissed, - keyboardDismissMechanism: result.mechanism?.rawValue - ) - ) + if command.command == .keyboardDismiss { + guard !status.visible else { + return Response(ok: false, error: keyboardDismissRefusal()) + } + return Response(ok: true, data: DataPayload( + message: "keyboardDismiss", visible: false, wasVisible: false, dismissed: false + )) + } + return Response(ok: true, data: DataPayload( + message: "keyboardStatus", + visible: status.visible, + keyboardReturnKey: status.returnKey, + keyboardReturnKeyLabel: status.returnKeyLabel + )) case .keyboardReturn: - var press: (wasVisible: Bool, pressed: Bool, visible: Bool, fieldAttempted: Bool)? + var result: DataPayload? withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .preEventSkipped) { - press = pressKeyboardReturn(app: activeApp) - } - guard let result = press else { - return Response(ok: false, error: ErrorPayload(message: "keyboardReturn produced no result")) - } - if !result.pressed { - return Response( - ok: false, - error: result.fieldAttempted ? keyboardReturnFieldAttemptFailure : keyboardReturnRefusal - ) - } - return Response( - ok: true, - data: DataPayload( + let wasVisible = keyboardStatus(app: activeApp)?.visible + guard pressKeyboardReturn(app: activeApp) else { return } + sleepFor(0.2) + result = DataPayload( message: "keyboardReturn", - visible: result.visible, - wasVisible: result.wasVisible + visible: keyboardStatus(app: activeApp)?.visible, + wasVisible: wasVisible ) - ) - case .keyboardStatus: - var status: RunnerKeyboardStatus? - withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .bothSkipped) { - status = keyboardStatus(app: activeApp) } - guard let result = status else { - return Response(ok: false, error: ErrorPayload(message: "keyboardStatus produced no result")) + guard let result else { + return Response(ok: false, error: keyboardReturnRefusal) } - return Response( - ok: true, - data: DataPayload( - message: "keyboardStatus", - visible: result.visible, - keyboardReturnKey: result.returnKey, - keyboardReturnKeyLabel: result.returnKeyLabel - ) - ) + return Response(ok: true, data: result) case .alert: let action = (command.action ?? "get").lowercased() let deadline = alertDeadline ?? Date().addingTimeInterval( @@ -724,7 +700,7 @@ extension RunnerTests { } return Self.reportingSchedule(execution.schedule, in: response) case .gestureViewport: - let frame = try gestureViewportFrame(app: activeApp) + let frame = try gestureViewportFrame(app: activeApp, includesKeyboard: command.includesKeyboard == true) guard !frame.isNull, !frame.isInfinite, !frame.isEmpty else { return Response(ok: false, error: ErrorPayload(code: "COMMAND_FAILED", message: "Active app interaction viewport is unavailable")) } diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift index 8e9f47aea4..a6575092a4 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift @@ -1,59 +1,6 @@ import XCTest import AgentDeviceSnapshotPresentation -private enum KeyboardDismissObservationTiming { - static let timeout: TimeInterval = 2 - // #1542: dismissing the keyboard can trigger the host app's own content-offset - // adjustment (e.g. a ScrollView correcting the inset it grew to keep a focused - // field above the keyboard). That adjustment is a separate, unsynchronized - // animation the keyboard's own `waitForNonExistence` above knows nothing about: - // the keyboard AX element can vanish well before the app settles. The very next - // command is frequently a synthesized, AX-free drag (scroll/gesture — kept - // AX-free so it still works under #1105-family AX degradation), which has no - // XCTest quiescence wait of its own, so it can land mid-animation and net to - // zero. These bounds cap the settle wait this trades in. - // A spring-driven content-offset correction can pass through a near-zero- - // velocity inflection (the top of an overshoot) that two adjacent samples - // alone cannot distinguish from true rest. Requiring 3 consecutive matching - // samples demands ~2 full sample intervals of actual stillness before - // stopping early, so a momentary pause mid-animation cannot look settled. - static let settleTimeout: TimeInterval = 2.0 - static let settleSampleInterval: TimeInterval = 0.15 - static let settleRequiredConsecutiveMatches: Int = 3 -} - -// The mechanism that actually resigned the keyboard, disclosed to the caller -// (#1598) so a response never claims "dismissed" without saying how — a -// safe-area tap has a very different reliability/side-effect profile than -// tapping the keyboard's own Done key, and callers need to know which one -// fired. -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 { - let wasVisible: Bool - let dismissed: Bool - let visible: Bool - let mechanism: RunnerKeyboardDismissMechanism? - /// 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. /// Visible frames include the input assistant and share the nodes' normalized coordinate space. /// A complete scan with no keyboard establishes absence; projected or partial trees never do. @@ -209,310 +156,93 @@ extension RunnerTests { extension RunnerTests { func isKeyboardVisible(app: XCUIApplication) -> Bool { - return visibleKeyboardFrame(app: app) != nil - } - - /// What `keyboard status` answers with: the keyboard's visibility and, when it is up, the return - /// key the focused field offers. It reads the keyboard's own key elements rather than looking a - /// control up by English name, so a localized keyboard (a return key reading `szukaj`) is reported - /// with its own wording instead of a label-less `unknown`. `RunnerKeyboardStatus` decides which - /// observed control is the return key, through the same `kind(of:)` rule `keyboard enter` probes - /// with, so the two commands can never disagree about the wording they can name. - /// - /// The keyboard is another process, so every element read is a round trip. One snapshot of the - /// keyboard carries its visibility, its frame, and every key's wording and frame, so the whole read - /// is one round trip instead of one per key. - func keyboardStatus(app: XCUIApplication) -> RunnerKeyboardStatus { -#if os(iOS) - guard let keyboard = readKeyboard(app: app) else { - return RunnerKeyboardStatus.observed(visible: false, returnControlText: nil) - } - return RunnerKeyboardStatus.observed(visible: true, keyboardKeys: keyboard.keys) -#else - guard isKeyboardVisible(app: app) else { - return RunnerKeyboardStatus.observed(visible: false, returnControlText: nil) - } - return RunnerKeyboardStatus.observed(visible: true, keyboardKeys: []) -#endif + visibleKeyboardFrame(app: app) != nil } + @MainActor + func keyboardStatus(app: XCUIApplication) -> RunnerKeyboardStatus? { #if os(iOS) - /// Every key, then every button, the keyboard snapshot holds, in tree order, with its wording and - /// frame. An element that answers no wording at all is dropped; wording that is only whitespace is - /// kept, because that is how the accessibility tree carries the space bar and the positional rule - /// anchors the return key's slot on it. Keys come before buttons so the first control whose wording - /// names a return kind is the same one a per-type query would reach first. - func observedKeyboardKeys(in keyboard: XCUIElementSnapshot) -> [RunnerKeyboardStatus.ObservedKeyboardKey] { - var keys: [RunnerKeyboardStatus.ObservedKeyboardKey] = [] - var buttons: [RunnerKeyboardStatus.ObservedKeyboardKey] = [] - 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 || !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 + var result: RunnerKeyboardStatus? + let (issues, exception) = holdingRecordedIssues { + let keyboard = app.keyboards.firstMatch + guard keyboard.exists else { + result = .hidden + return + } + guard let snapshot = try? keyboard.snapshot() else { return } + let displaySize: CGSize? + let orientation: Int + if requestLitPanel != nil { + guard let panel = try? requireRequestLitPanelSurface(app: app) else { return } + displaySize = panel.geometry.panelNativeSize + orientation = panel.geometry.orientation + } else { + displaySize = soleDisplayPortraitSize() + orientation = capturedInterfaceOrientation(app: app) + } + let keys = observedKeyboardKeys(in: snapshot) + result = RunnerKeyboardStatus.observed( + keyboardFrame: snapshot.frame, + keys: keys, + nativeDisplaySize: displaySize, + interfaceOrientation: orientation ) - 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)) + for issue in issues { + NSLog("AGENT_DEVICE_RUNNER_KEYBOARD_STATUS_ISSUE=%@", issue.compactDescription) + } + if let exception { NSLog("AGENT_DEVICE_RUNNER_KEYBOARD_STATUS_EXCEPTION=%@", exception) } + return issues.isEmpty && exception == nil ? result : nil #else - return nil + return .hidden #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] + private func observedKeyboardKeys(in keyboard: XCUIElementSnapshot) -> [RunnerKeyboardStatus.ObservedKeyboardKey] { + var keys: [RunnerKeyboardStatus.ObservedKeyboardKey] = [] + var pending = keyboard.children 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 - ) - ) - } + pending.append(contentsOf: node.children) + guard node.elementType == .key || node.elementType == .button else { continue } + keys.append(.init(label: node.label, identifier: node.identifier, frame: node.frame, isKey: node.elementType == .key)) } - guard let keyboard, !keyboard.frame.isEmpty else { return nil } - return RunnerKeyboardStatus.ObservedKeyboard( - frame: keyboard.frame, - keys: observedKeyboardKeys(in: keyboard) + outside - ) + return keys } #endif - func dismissKeyboard(app: XCUIApplication) -> RunnerKeyboardDismissOutcome { - let keyboard = app.keyboards.firstMatch - let wasVisible = isKeyboardVisible(app: app) - guard wasVisible else { - return RunnerKeyboardDismissOutcome( - wasVisible: false, - dismissed: false, - visible: false, - mechanism: nil, - dispatchedDismissal: false - ) - } - -#if os(tvOS) - _ = pressTvRemote(.menu) - sleepFor(0.2) - let tvVisible = isKeyboardVisible(app: app) - return RunnerKeyboardDismissOutcome( - wasVisible: true, - dismissed: !tvVisible, - visible: tvVisible, - mechanism: tvVisible ? nil : .dismissKey, - // On tvOS the Menu press always goes out, so a refusal after it did dispatch and keeps the - // generic code. - dispatchedDismissal: true - ) -#else - let tap = tapKeyboardDismissControl(app: app) - if tap == .tapped { - _ = keyboard.waitForNonExistence(timeout: KeyboardDismissObservationTiming.timeout) - waitForScreenshotStability( - app: app, - timeout: KeyboardDismissObservationTiming.settleTimeout, - sampleInterval: KeyboardDismissObservationTiming.settleSampleInterval, - requiredConsecutiveMatches: KeyboardDismissObservationTiming.settleRequiredConsecutiveMatches - ) - let visible = isKeyboardVisible(app: app) - return RunnerKeyboardDismissOutcome( - wasVisible: true, - dismissed: !visible, - visible: visible, - mechanism: visible ? nil : .dismissKey, - dispatchedDismissal: true - ) - } - - // #1606 review P1 (twice): generic background-tap dismissal is - // deliberately UNSUPPORTED. No geometry or role query can prove a - // coordinate is side-effect-free — a full-screen unlabeled Pressable is - // indistinguishable from an inert backdrop, so a "safe-area" tap can - // navigate or submit while reporting a successful dismiss. The dismiss - // key is the only mechanism the runner can vouch for. - return RunnerKeyboardDismissOutcome( - wasVisible: true, - dismissed: false, - visible: isKeyboardVisible(app: app), - mechanism: nil, - dispatchedDismissal: false, - treeUnreadable: tap == .treeUnreadable - ) -#endif - } - - /// The refusal a visible keyboard that stayed up answers with. The two ways it stays up answer - /// different questions and must not share one classification: finding no dismiss control sent - /// 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, treeUnreadable: Bool = false) -> ErrorPayload { - if dispatchedDismissal { - return ErrorPayload( - code: "UNSUPPORTED_OPERATION", - message: "Unable to dismiss the keyboard: a dismiss mechanism ran and the keyboard stayed visible", - hint: keyboardDismissRefusalHint - ) - } - return ErrorPayload( + func keyboardDismissRefusal() -> ErrorPayload { + ErrorPayload( code: RunnerWireErrorCode.keyboardDismissUnavailable, - 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 + message: "The Apple runner cannot dismiss this keyboard automatically", + hint: "Inspect the screen and press the visible Hide Keyboard key or an app control that ends editing. If the app supports interactive dismissal, use gesture pan to drag a finger down from inside its scrollable content and check the keyboard state again." ) } - private var keyboardDismissRefusalHint: String { - return - "An element whose center sits behind the on-screen keyboard is refused with tap_keyboard_occludes_target; one whose center stays above the keys presses normally. To end editing, tap the app's own Done/Cancel control, or use keyboard enter to press the return key when submission is wanted." - } - - /// The refusal a `keyboard enter` answers with when the control is missing: the keyboard exposes no - /// return-like key, and typing a return found no field to type into. It carries the runner's own code - /// so the host publishes `details.reason` instead of leaving callers to read the prose. The dispatch - /// disclosure stays `unknown` because typing the return can fail after XCTest sent it. var keyboardReturnRefusal: ErrorPayload { - return ErrorPayload( + ErrorPayload( code: RunnerWireErrorCode.keyboardReturnUnavailable, - message: "Unable to press the keyboard return key: the keyboard exposes no return-like key and no text field was available to submit", - hint: "Tap the app's own submit control by its ref, or focus a text field with fill or type before asking keyboard enter to submit it." - ) - } - - /// The refusal for a sole text field that was found and tapped but would not take the return. It is - /// not an absent control, so it has no typed reason; the tap may have landed. - var keyboardReturnFieldAttemptFailure: ErrorPayload { - return ErrorPayload( - code: "UNSUPPORTED_OPERATION", - message: "Unable to press the keyboard return key: the only text field was found, but tapping it and typing a return failed", - hint: "Focus the field with fill or type, or tap the app's own submit control by its ref." - ) - } - - - // AX-free on purpose (screenshot bytes, not the accessibility tree) so it holds - // under the same AX degradation the synthesized gesture lane is built to survive. - // Bounded and self-terminating: returns as soon as `requiredConsecutiveMatches` - // consecutive samples match, so an already-settled screen (the common case) - // pays close to nothing. The stopping decision itself - // (`runnerScreenshotStabilitySettled`) is a pure function of the samples taken - // so far, so it is unit-testable without a real screenshot pipeline; this loop - // is the thin, untestable I/O shell around it. - private func waitForScreenshotStability( - app: XCUIApplication, - timeout: TimeInterval, - sampleInterval: TimeInterval, - requiredConsecutiveMatches: Int - ) { - let deadline = Date().addingTimeInterval(timeout) - var samples: [Data?] = [screenshotFingerprintForStabilityCheck(app: app)] - while Date() < deadline { - sleepFor(sampleInterval) - samples.append(screenshotFingerprintForStabilityCheck(app: app)) - if runnerScreenshotStabilitySettled(samples, requiredConsecutiveMatches: requiredConsecutiveMatches) { - logScreenshotStability(samples: samples, settled: true) - return - } - } - logScreenshotStability(samples: samples, settled: false) - } - - /// Says what the settle actually looked at: samples that are all `nil` means the capture refused to - /// produce a frame, which is a different fact from a screen that never held still, and the two read - /// identically from the outside (#2728). - private func logScreenshotStability(samples: [Data?], settled: Bool) { - NSLog( - "AGENT_DEVICE_RUNNER_KEYBOARD_STABILITY samples=%ld captured=%ld settled=%@", - samples.count, - samples.compactMap { $0 }.count, - settled ? "yes" : "no" + message: "Could not confirm Return was sent to the focused input", + hint: "Check the screen before retrying. Focus the intended input before sending Return, or press the app's submit control explicitly." ) } - private func screenshotFingerprintForStabilityCheck(app: XCUIApplication) -> Data? { - guard let image = captureRunnerFrame(app: app) else { return nil } - return runnerPngData(for: image) - } - - /// `fieldAttempted` is true when the sole-text-field route found a field and tapped it before typing, - /// so a failed press there is a failed attempt rather than a missing control. - func pressKeyboardReturn( - app: XCUIApplication - ) -> (wasVisible: Bool, pressed: Bool, visible: Bool, fieldAttempted: Bool) { + func pressKeyboardReturn(app: XCUIApplication) -> Bool { #if os(tvOS) - return (wasVisible: false, pressed: pressTvRemote(.select), visible: false, fieldAttempted: false) + return pressTvRemote(.select) #elseif os(iOS) - let wasVisible = isKeyboardVisible(app: app) - if tapKeyboardReturnControl(app: app) { - sleepFor(0.2) - return (wasVisible: wasVisible, pressed: true, visible: isKeyboardVisible(app: app), fieldAttempted: false) + // XCTest reports absent focus through an issue. Any issue leaves dispatch uncertain, + // so report failure without invalidating the session the caller needs to observe the app. + let (issues, exception) = holdingRecordedIssues { + app.typeText(XCUIKeyboardKey.return.rawValue) } - - 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), fieldAttempted: false) + if let exception { NSLog("AGENT_DEVICE_RUNNER_KEYBOARD_RETURN_EXCEPTION=%@", exception) } + for issue in issues { + NSLog("AGENT_DEVICE_RUNNER_KEYBOARD_RETURN_ISSUE=%@", issue.compactDescription) } - sleepFor(0.2) - return (wasVisible: wasVisible, pressed: true, visible: isKeyboardVisible(app: app), fieldAttempted: false) + return issues.isEmpty && exception == nil #else - return (wasVisible: false, pressed: false, visible: false, fieldAttempted: false) + return false #endif } @@ -529,153 +259,4 @@ extension RunnerTests { return nil #endif } - - private func pressKeyboardReturn( - on element: XCUIElement, - app: XCUIApplication, - wasVisible: Bool - ) -> (wasVisible: Bool, pressed: Bool, visible: Bool, fieldAttempted: Bool) { -#if os(iOS) - // `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() - app.typeText(XCUIKeyboardKey.return.rawValue) - }) - guard typed else { - return (wasVisible: wasVisible, pressed: false, visible: isKeyboardVisible(app: app), fieldAttempted: true) - } - sleepFor(0.2) - return (wasVisible: wasVisible, pressed: true, visible: isKeyboardVisible(app: app), fieldAttempted: true) -#else - return (wasVisible: wasVisible, pressed: false, visible: false, fieldAttempted: false) -#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", []) { - app.descendants(matching: .any).allElementsBoundByIndex.filter { element in - guard element.exists else { return false } - switch element.elementType { - case .textField, .secureTextField, .searchField, .textView: - return true - default: - return false - } - } - } - return matches.count == 1 ? matches[0] : nil -#else - return nil -#endif - } - - /// 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 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 - .filter { RunnerKeyboardStatus.isNearKeyboard($0.frame, keyboardFrame: surface.frame) } - if near.count == 1, near[0].exists, near[0].isHittable { - near[0].tap() - return .tapped - } - } - return none -#else - return .notFound -#endif - } - - /// The keyboard's own return control, in the order `RunnerKeyboardReturnKey.probeLabels` tries its - /// labels. On iOS, `nil` means no listed label was hittable. On other platforms nothing is queried - /// and `nil` is returned, so callers must not read it as an absent return control. - func findKeyboardReturnControl(app: XCUIApplication) -> XCUIElement? { -#if os(iOS) - for label in RunnerKeyboardReturnKey.probeLabels { - let candidates = [ - app.keyboards.buttons[label], - app.keyboards.keys[label], - ] - if let hittable = candidates.first(where: { $0.exists && $0.isHittable }) { - return hittable - } - } -#endif - return nil - } - - private func tapKeyboardReturnControl(app: XCUIApplication) -> Bool { -#if os(iOS) - guard let control = findKeyboardReturnControl(app: app) else { - return false - } - control.tap() - return true -#else - return false -#endif - } -} - -/// True once the `requiredConsecutiveMatches` most recent samples are all present -/// and byte-identical — i.e. the screen held still across that whole run of -/// polls, not just the last two. A spring-driven content-offset correction can -/// pass through a near-zero-velocity inflection that two adjacent samples alone -/// cannot distinguish from true rest; requiring a longer run of matches demands -/// real elapsed stillness before stopping early. `nil` entries (a screenshot -/// capture that failed) never count toward a match, so a flaky capture cannot -/// look like stability; the caller's bounded loop still terminates on its -/// deadline regardless. -func runnerScreenshotStabilitySettled( - _ samples: [Data?], - requiredConsecutiveMatches: Int -) -> Bool { - guard requiredConsecutiveMatches >= 2, samples.count >= requiredConsecutiveMatches else { - return false - } - let window = samples.suffix(requiredConsecutiveMatches) - guard let first = window.first, let firstData = first else { return false } - return window.allSatisfy { $0 == firstData } } diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift index ae642c1e8a..dac001e918 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift @@ -253,6 +253,7 @@ struct Command: Codable { let delayMs: Int? let textEntryMode: String? let action: String? + let includesKeyboard: Bool? let x: Double? let y: Double? let button: String? @@ -712,16 +713,11 @@ 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/RunnerTests+SynthesizedInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift index 304449a470..9254c5cc85 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift @@ -325,15 +325,14 @@ extension RunnerTests { /// context its record is routed through, so a tree with no window whose app provably fills its /// sole screen plans on that screen, the same route a synthesized tap or scroll takes. @MainActor - func gestureViewportFrame(app: XCUIApplication) throws -> CGRect { + func gestureViewportFrame(app: XCUIApplication, includesKeyboard: Bool = false) throws -> CGRect { #if os(iOS) - guard let context = try synthesizedCoordinateContext(app: app) else { - return frameAvoidingKeyboard(app: app, frame: try readableAppFrame(app: app)) + if let context = try synthesizedCoordinateContext(app: app) { + let frame = context.geometry.windowOnScreen.rect + return includesKeyboard || context.resolvedWindow == nil ? frame : frameAvoidingKeyboard(app: app, frame: frame) } - // The sole-screen route means the windows query just failed, so a keyboard probe would too. - return context.resolvedWindow == nil - ? context.geometry.windowOnScreen.rect - : frameAvoidingKeyboard(app: app, frame: context.geometry.windowOnScreen.rect) + let frame = try readableAppFrame(app: app) + return includesKeyboard ? frame : frameAvoidingKeyboard(app: app, frame: frame) #else return try resolvedTouchReferenceFrame(app: app) #endif diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift index 0454fa3ed9..73e11c0456 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift @@ -62,14 +62,9 @@ final class RunnerTests: XCTestCase { static let backSwipeNoChange = "BACK_SWIPE_NO_CHANGE" static let backSwipeUnverified = "BACK_SWIPE_UNVERIFIED" static let backSwipeNotDispatched = "BACK_SWIPE_NOT_DISPATCHED" - /// A `keyboard dismiss` the visible keyboard would not come down for: it exposes no dismiss key the - /// runner vouches for (#1606). The host reports it under `UNSUPPORTED_OPERATION` and publishes - /// `details.reason`, so a caller never reads the refusal off the message prose. + /// The runner refused automatic dismissal before dispatch. static let keyboardDismissUnavailable = "KEYBOARD_DISMISS_UNAVAILABLE" - /// A `keyboard enter` that found no return key to press and no text entry to submit through, so - /// nothing was submitted. The host reports it under `UNSUPPORTED_OPERATION` and publishes - /// `details.reason`; the disclosure stays `unknown` because typing the return can fail after XCTest - /// sent it. A sole field that was found but would not take the return is not this refusal. + /// Return may have reached the focused input. static let keyboardReturnUnavailable = "KEYBOARD_RETURN_UNAVAILABLE" /// A press of a hardware or Siri Remote control this target cannot perform: the press helper refuses /// before pressing anything, so the host reports `UNSUPPORTED_OPERATION` with `details.reason` and diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerRequestPanelTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerRequestPanelTests.swift index abeebe00b5..fb7256001a 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerRequestPanelTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerRequestPanelTests.swift @@ -51,6 +51,7 @@ private final class LitPanelBookingProbe: NSObject { static weak var applicationFrameRecordingTest: XCTestCase? static var keyboard: XCUIElement? static var keyboardFrame: CGRect? + static var keyboardSnapshot: XCUIElementSnapshot? static var targetFrame = CGRect(x: 190, y: 140, width: 20, height: 20) static var windowDisplayID: UInt = 3 static var includeDarkSelector = true @@ -113,6 +114,10 @@ private final class LitPanelBookingProbe: NSObject { @objc var keyboards: XCUIElementQuery { unsafeBitCast(SurfaceSelectorQuery([Self.keyboard!]), to: XCUIElementQuery.self) } + @objc(snapshotWithError:) + func snapshot() throws -> XCUIElementSnapshot { + try XCTUnwrap(Self.keyboardSnapshot) + } @objc var allElementsBoundByIndex: [XCUIElement] { [Self.window!] } @objc(descendantsMatchingType:) func descendants(matching type: UInt) -> XCUIElementQuery { @@ -593,6 +598,68 @@ extension RunnerTests { try assertions(response) } + @MainActor + func testKeyboardCommandsUseTheDisplayBelowAPlacedWindow() throws { + try assertKeyboardCommandsUseTheDisplayBelowAPlacedWindow(litPanel: true) + } + + @MainActor + func testKeyboardCommandsUseTheSoleDisplayBelowAPlacedWindow() throws { + try XCTSkipUnless(XCUIScreen.screens.count == 1, "the fixture requires a single-display host") + let cached = mainOwned.soleDisplayPortraitSize + defer { mainOwned.soleDisplayPortraitSize = cached } + let restore = try overrideSoleScreenValues([ + "bounds": NSValue(cgRect: CGRect(x: 0, y: 0, width: 1668, height: 2420)), + "scale": NSNumber(value: 2), + ]) + defer { restore() } + try assertKeyboardCommandsUseTheDisplayBelowAPlacedWindow(litPanel: false) + } + + @MainActor + private func assertKeyboardCommandsUseTheDisplayBelowAPlacedWindow(litPanel: Bool) throws { + let placedWindow = CGRect(x: 224, y: 207, width: 386, height: 682) + let keyboardFrame = CGRect(x: 0, y: 925, width: 834, height: 282) + let panelField = litPanel ? #","litPanel":{"displayId":3,"widthPt":834,"heightPt":1210}"# : "" + let originalProbeOrientation = LitPanelBookingProbe.orientation + defer { LitPanelBookingProbe.orientation = originalProbeOrientation } + try withLitPanelBookingProbe(composed: true) { _ in + LitPanelBookingProbe.windowFrame = placedWindow + LitPanelBookingProbe.orientation = RunnerInterfaceOrientation.portrait + LitPanelBookingProbe.keyboardFrame = keyboardFrame + LitPanelBookingProbe.keyboardSnapshot = ElementAttributesFixture(.keyboard, keyboardFrame, children: [ + ElementAttributesFixture(.key, CGRect(x: 300, y: 1000, width: 60, height: 60), label: "A"), + ElementAttributesFixture(.button, CGRect(x: 702, y: 1100, width: 120, height: 60), label: "OK", identifier: "Done"), + ]) + let keyboard = try XCTUnwrap(LitPanelBookingProbe.keyboard) + let selector = NSSelectorFromString("snapshotWithError:") + let method = try XCTUnwrap(class_getInstanceMethod(type(of: keyboard), selector)) + let stub = try XCTUnwrap(class_getInstanceMethod(LitPanelBookingProbe.self, selector)) + let originalSnapshot = method_setImplementation(method, method_getImplementation(stub)) + defer { + method_setImplementation(method, originalSnapshot) + LitPanelBookingProbe.keyboardSnapshot = nil + } + + for name in ["keyboardStatus", "keyboardDismiss"] { + let command = try runnerCommandFixture( + #"{"command":"\#(name)"\#(panelField)}"# + ) + let requestID = setRequestLitPanel(from: command) + defer { endRequestLitPanel(requestID) } + XCTAssertEqual(try onScreenWindowFrame(app: app), placedWindow) + let response = try executeOnMainPrepared(command: command, activeApp: app) + if name == "keyboardStatus" { + XCTAssertEqual(response.data?.visible, true) + XCTAssertEqual(response.data?.keyboardReturnKey, "done") + XCTAssertEqual(response.data?.keyboardReturnKeyLabel, "OK") + } else { + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.keyboardDismissUnavailable) + } + } + } + } + /// Runs `body` with the app's window probed as the only window on lit display 3 at `frame`, /// handing it the count of window-list reads. @MainActor diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardReturnKeyTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardReturnKeyTests.swift index aab8522219..eb7356a839 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardReturnKeyTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardReturnKeyTests.swift @@ -1,503 +1,87 @@ import XCTest +import AgentDeviceSnapshotPresentation #if AGENT_DEVICE_RUNNER_UNIT_TESTS extension RunnerTests { - /// Every Apple return-key type this rule maps: the key's English wording, and the wire value the - /// host publishes for it (design Feature C: `keyboard status` reports `returnKey`). The raw value - /// is the contract, so these assert the pair, not the case alone. `Google`, `Yahoo` and - /// `Emergency Call` are Apple types this rule leaves unmapped on purpose; the test below pins that. - func testKeyboardReturnKeyKindNamesEachReturnKeyType() { - let cases: [(label: String, expected: String)] = [ - ("Go", "go"), - ("Search", "search"), - ("Send", "send"), - ("Next", "next"), - ("Done", "done"), - ("Join", "join"), - ("Route", "route"), - ("Continue", "continue"), - ("Return", "enter"), - ("Enter", "enter"), + func testKeyboardStatusRequiresMeasuredDisplayBounds() { + let keyboard = CGRect(x: 0, y: 925, width: 834, height: 282) + XCTAssertNil(RunnerKeyboardStatus.observed( + keyboardFrame: keyboard, keys: [], nativeDisplaySize: nil, + interfaceOrientation: RunnerInterfaceOrientation.portrait + )) + XCTAssertNil(RunnerKeyboardStatus.observed( + keyboardFrame: keyboard, keys: [], nativeDisplaySize: CGSize(width: 834, height: 1210), + interfaceOrientation: RunnerInterfaceOrientation.unknown + )) + } + + func testKeyboardStatusUsesTheLocalizedAXLabelWithTheObservedReturnIdentifier() { + let display = CGSize(width: 669, height: 951) + let keyboard = CGRect(x: 75, y: 449, width: 801, height: 219) + let keys: [RunnerKeyboardStatus.ObservedKeyboardKey] = [ + .init(label: "A", identifier: "", frame: CGRect(x: 125, y: 501, width: 76, height: 52), isKey: true), + .init(label: "Dyktuj", identifier: "dictation", frame: CGRect(x: 690, y: 609, width: 73, height: 51), isKey: false), + .init(label: "szukaj", identifier: "Search", frame: CGRect(x: 763, y: 609, width: 111, height: 51), isKey: false), ] - for (label, expected) in cases { - XCTAssertEqual(RunnerKeyboardReturnKey.kind(of: label).rawValue, expected, label) - } - } - - /// Keyboards and iOS versions differ in the label's casing and padding; the kind it names does not. - func testKeyboardReturnKeyKindIgnoresCasingAndPadding() { - XCTAssertEqual(RunnerKeyboardReturnKey.kind(of: "done"), .done) - XCTAssertEqual(RunnerKeyboardReturnKey.kind(of: "DONE"), .done) - XCTAssertEqual(RunnerKeyboardReturnKey.kind(of: " Done"), .done) - XCTAssertEqual(RunnerKeyboardReturnKey.kind(of: "\nSend\t"), .send) - } - - /// The three Apple return-key types this rule leaves unmapped on purpose. `Google` and `Yahoo` - /// name a vendor rather than a submit action, and `Emergency Call` places a call: reporting any of - /// them as a submit kind would tell a caller to submit a field whose key does something else. - func testKeyboardReturnKeyKindLeavesBrandedAndEmergencyAppleTypesUnknown() { - for label in ["Google", "Yahoo", "Emergency Call"] { - XCTAssertEqual(RunnerKeyboardReturnKey.kind(of: label), .unknown, label) - } - } - - /// Closest negatives: a label that CONTAINS a return-key word, or is a localized or custom key's - /// wording, is not that key. A prefix or fuzzy rule would report a "Send Message" key as `send`, - /// or a localized "Retour" key as `enter`; both would tell a caller to submit a field whose key - /// does something else. - func testKeyboardReturnKeyKindLeavesAmbiguousLabelsUnknown() { - for label in [ - "Send Message", - "Search Messages", - "Done Sending", - "Next slide", - "Go to Settings", - "Continued", - "Return key", - "Retour", - "完了", - "", - " ", - ] { - XCTAssertEqual(RunnerKeyboardReturnKey.kind(of: label), .unknown, label) - } - } - - /// The two owners of the key's wording stay aligned: every label the press path probes names a - /// kind a status read can report, so a lookup that finds a control is never a status read that - /// answers `unknown`. - func testEveryKeyboardReturnProbeLabelMapsToAReportedKind() { - let expected: [String: RunnerKeyboardReturnKey] = [ - "return": .enter, - "Return": .enter, - "Enter": .enter, - "Go": .go, - "Search": .search, - "Next": .next, - "Done": .done, - "Send": .send, - "Join": .join, - ] - for label in RunnerKeyboardReturnKey.probeLabels { - XCTAssertEqual(RunnerKeyboardReturnKey.kind(of: label), expected[label], label) - } - } - - /// What a `keyboard status` read builds from each observation. The visible keyboard's return - /// control decides both fields: its wording names the kind through the same rule `keyboard enter` - /// probes with, and it is kept as the accessibility tree carries it apart from surrounding - /// whitespace, so a key this read cannot name is still readable. - func testKeyboardStatusReportsTheObservedReturnControl() { - let status = RunnerKeyboardStatus.observed(visible: true, returnControlText: " Search ") - XCTAssertEqual(status, RunnerKeyboardStatus(visible: true, returnKey: "search", returnKeyLabel: "Search")) - } - - /// The kinds `kind(of:)` names but the press list never probes are reported by the read, because - /// the read looks at the keyboard's own keys rather than looking a control up by English name. - func testKeyboardStatusReportsAKindThePressProbeListOmits() { - for (label, kind) in [("Route", "route"), ("Continue", "continue")] { - XCTAssertEqual( - RunnerKeyboardStatus.observed(visible: true, returnControlText: label), - RunnerKeyboardStatus(visible: true, returnKey: kind, returnKeyLabel: label), - label - ) - XCTAssertFalse( - RunnerKeyboardReturnKey.probeLabels.contains(label), - "\(label) must stay out of the press probe list, which the read does not use" - ) - } - } - - /// A hidden keyboard reports no return key at all. That is a different fact from one it could not - /// name, so both fields stay out rather than answering `unknown` for a key nobody can press. The - /// keyboard's keys are ignored: nothing is being submitted to. - func testKeyboardStatusReportsNoReturnKeyWhileTheKeyboardIsHidden() { - XCTAssertEqual( - RunnerKeyboardStatus.observed(visible: false, returnControlText: "Search"), - RunnerKeyboardStatus(visible: false, returnKey: nil, returnKeyLabel: nil) - ) - XCTAssertEqual( - RunnerKeyboardStatus - .observed(visible: false, keyboardKeys: [RunnerKeyboardStatus.ObservedKeyboardKey(text: "Done", frame: CGRect(x: 0, y: 0, width: 40, height: 40))]), - RunnerKeyboardStatus(visible: false, returnKey: nil, returnKeyLabel: nil) - ) - } - - /// The English keyboard, as the accessibility tree carries it: the space bar's wording is a space, - /// and the search field's return key reads `Search` in the slot beside it. The picker names the kind - /// from the key's own wording, so the slot never has to be consulted here. - func testKeyboardStatusPicksTheReturnKeyFromTheKeyboardKeysByWording() { - let keys = observedKeyboardKeysFixture([ - ("Q", 5, 959, 39), ("W", 44, 959, 40), ("shift", 5, 1067, 51), ("delete", 348, 1067, 52), - ("Numbers", 5, 1121, 49), ("Emoji", 54, 1121, 49), (" ", 103, 1121, 197), - ("Search", 301, 1121, 99), ("Padding-Right", 0, 952, 0), - ]) - XCTAssertEqual( - RunnerKeyboardStatus.observed(visible: true, keyboardKeys: keys), - RunnerKeyboardStatus(visible: true, returnKey: "search", returnKeyLabel: "Search") - ) - } - - /// The whole point of reading the keyboard's own keys: a fully localized keyboard names no kind, so - /// the return key is the control in the slot beside the space bar and its wording is reported even - /// though the kind is `unknown`. These are the frames this read measured on a Polish iOS keyboard, - /// where `szukaj` shares the space bar's row immediately right of it, and the letter, shift and - /// delete keys are in higher rows. - func testKeyboardStatusReportsALocalizedReturnKeyWithItsOwnWording() { - let keys = observedKeyboardKeysFixture([ - ("Padding-Left", 0, 952, 0), ("Q", 5, 959, 39), ("P", 360, 959, 40), ("shift", 5, 1067, 51), - ("M", 301, 1067, 40), ("usuń", 348, 1067, 52), ("cyfry", 5, 1121, 49), ("Emoji", 54, 1121, 49), - (" ", 103, 1121, 197), ("szukaj", 301, 1121, 99), - ]) XCTAssertEqual( - RunnerKeyboardStatus.observed(visible: true, keyboardKeys: keys), - RunnerKeyboardStatus(visible: true, returnKey: "unknown", returnKeyLabel: "szukaj") + RunnerKeyboardStatus.observed(keyboardFrame: keyboard, keys: keys, nativeDisplaySize: display, interfaceOrientation: RunnerInterfaceOrientation.landscapeLeft), + RunnerKeyboardStatus(visible: true, returnKey: "search", returnKeyLabel: "szukaj") ) } - /// A number, decimal or phone pad has no return key, and it has no space bar: the frames below are - /// the phone pad this read measured on iOS 26.2, where `Delete` occupies the bottom-trailing corner. - /// That corner is not a return key, and taking it would tell a caller an OTP or phone field has one. - /// Without the space bar there is no slot, so the answer is `unknown` with no label. - func testKeyboardStatusReportsNoLabelForAPadWithNoSpaceBar() { - let keys = observedKeyboardKeysFixture([ - ("1", 5, 881, 132), ("2", 136, 881, 132), ("3", 268, 881, 132), ("4", 5, 935, 132), - ("5", 136, 935, 132), ("6", 268, 935, 132), ("7", 5, 989, 132), ("8", 136, 989, 132), - ("9", 268, 989, 132), ("Shift", 5, 1043, 132), ("0", 136, 1043, 132), ("Delete", 268, 1043, 132), - ]) - XCTAssertEqual( - RunnerKeyboardStatus.observed(visible: true, keyboardKeys: keys), - RunnerKeyboardStatus(visible: true, returnKey: "unknown", returnKeyLabel: nil) - ) - } - - /// The dictation and input-language keys, measured on an iPhone and an iPad layout: all of them sit - /// left of the space bar, so the slot right of it still resolves to the localized return key. - func testKeyboardStatusNeverReportsADictationOrLanguageKeyAsTheReturnKey() { - let localized = observedKeyboardKeysFixture([ - ("Globe", 5, 1121, 49), ("Dictation", 54, 1121, 49), (" ", 103, 1121, 197), - ("szukaj", 301, 1121, 99), - ]) - XCTAssertEqual( - RunnerKeyboardStatus.observed(visible: true, keyboardKeys: localized), - RunnerKeyboardStatus(visible: true, returnKey: "unknown", returnKeyLabel: "szukaj") - ) - } - - /// The iPad full keyboard, at the frames this read measured on iPadOS 26.2: right of the space bar - /// sits a numbers key and then the hide-keyboard key, while the return key ends a higher row. So the - /// space bar's right neighbour is not its row's trailing key, the slot has no candidate, and a - /// localized keyboard whose return wording this read cannot map answers `unknown` with no label - /// rather than reporting the numbers key as a return key. An English iPad keyboard is still named by - /// wording, because its return key reads `search`. - func testKeyboardStatusReportsNoLabelForAnIPadBottomRowThatDoesNotEndWithTheReturnKey() { - let keys = observedKeyboardKeysFixture([ - ("Tab", 6, 905, 81), ("Q", 87, 905, 65), ("delete", 737, 905, 81), - ("Caps Lock", 6, 969, 100.5), ("A", 106.5, 969, 65), ("szukaj", 691.5, 969, 126.5), - ("shift", 6, 1032, 130), ("Z", 136, 1032, 65), ("shift", 720.5, 1032, 97.5), - ("Next keyboard", 6, 1096, 69), ("numbers", 75, 1096, 68.5), ("Dictate", 143.5, 1096, 69), - (" ", 212.5, 1096, 410), ("numbers", 622.5, 1096, 97.5), ("Hide keyboard", 720, 1096, 98), - ]) + func testKeyboardStatusOmitsReturnMetadataForALabelOnlySearchKey() { + let keyboard = CGRect(x: 0, y: 449, width: 393, height: 219) + let keys: [RunnerKeyboardStatus.ObservedKeyboardKey] = [ + .init(label: "A", identifier: "", frame: CGRect(x: 15, y: 501, width: 36, height: 52), isKey: true), + .init(label: "Search", identifier: "", frame: CGRect(x: 282, y: 609, width: 110, height: 51), isKey: false), + ] XCTAssertEqual( - RunnerKeyboardStatus.observed(visible: true, keyboardKeys: keys), + RunnerKeyboardStatus.observed(keyboardFrame: keyboard, keys: keys, + nativeDisplaySize: CGSize(width: 393, height: 852), + interfaceOrientation: RunnerInterfaceOrientation.portrait), RunnerKeyboardStatus(visible: true, returnKey: "unknown", returnKeyLabel: nil) ) } - /// Wording outranks the slot: a key `kind(of:)` names is reported even when the slot holds something - /// else, so a keyboard that localizes some keys and not others is still named by wording. The slot is - /// populated here, which is what makes this a real preference rather than the only candidate. - func testKeyboardStatusPrefersNamedWordingOverTheSlot() { - let keys = observedKeyboardKeysFixture([ - ("Q", 5, 959, 39), ("Done", 50, 1067, 39), (" ", 5, 1121, 197), ("ż", 202, 1121, 198), - ]) - XCTAssertEqual( - RunnerKeyboardStatus.observed(visible: true, keyboardKeys: keys), - RunnerKeyboardStatus(visible: true, returnKey: "done", returnKeyLabel: "Done") - ) - } - - /// 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), + func testKeyboardStatusIgnoresOffscreenKeysBelowAnAccessory() { + let display = CGSize(width: 820, height: 1180) + let bar = CGRect(x: 0, y: 1136, width: 820, height: 44) + let keys: [RunnerKeyboardStatus.ObservedKeyboardKey] = [ + .init(label: "Done", identifier: "Done", frame: CGRect(x: 730, y: 1140, width: 66, height: 36), isKey: false), + .init(label: "A", identifier: "", frame: CGRect(x: 112, y: 1251, width: 65, height: 63), isKey: true), + .init(label: "return", identifier: "Return", frame: CGRect(x: 691, y: 1251, width: 126, height: 63), isKey: false), ] - 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) + RunnerKeyboardStatus.observed(keyboardFrame: bar, keys: keys, nativeDisplaySize: display, interfaceOrientation: RunnerInterfaceOrientation.portrait), + .hidden ) + XCTAssertNil(RunnerKeyboardStatus.observed(keyboardFrame: .zero, keys: keys, nativeDisplaySize: display, interfaceOrientation: RunnerInterfaceOrientation.portrait)) } - /// 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. - func testKeyboardStatusReportsUnknownForAVisibleKeyboardWithNoReadableKey() { - let expected = RunnerKeyboardStatus(visible: true, returnKey: "unknown", returnKeyLabel: nil) - XCTAssertEqual(RunnerKeyboardStatus.observed(visible: true, keyboardKeys: []), expected) + func testKeyboardStatusUsesTheVisibleFrameWhenNoKeysAreExposed() { XCTAssertEqual( RunnerKeyboardStatus.observed( - visible: true, - keyboardKeys: observedKeyboardKeysFixture([("1", 5, 881, 132), ("2", 136, 881, 132)]) + keyboardFrame: CGRect(x: 0, y: 561, width: 393, height: 233), + keys: [], + nativeDisplaySize: CGSize(width: 393, height: 852), + interfaceOrientation: RunnerInterfaceOrientation.portrait ), - expected - ) - XCTAssertEqual( - RunnerKeyboardStatus.observed( - visible: true, - keyboardKeys: observedKeyboardKeysFixture([(" ", 103, 1121, 197)]) - ), - expected - ) - XCTAssertEqual( - RunnerKeyboardStatus.observed( - visible: true, - keyboardKeys: observedKeyboardKeysFixture([(" ", 5, 1121, 197), ("szukaj", 0, 952, 0)]) - ), - expected + RunnerKeyboardStatus(visible: true, returnKey: "unknown", returnKeyLabel: nil) ) } - /// The press path is unchanged by what the read can see: it still looks its own labels up in its - /// own order, and the read never consults that list. - func testKeyboardEnterProbeListStillOwnsItsOrder() { + func testKeyboardStatusDoesNotTreatAnAccessoryOrNumericKeyAsReturn() { + let display = CGSize(width: 393, height: 852) + let keyboard = CGRect(x: 0, y: 531, width: 393, height: 263) + let keys: [RunnerKeyboardStatus.ObservedKeyboardKey] = [ + .init(label: "Done", identifier: "Done", frame: CGRect(x: 300, y: 533, width: 80, height: 25), isKey: false), + .init(label: "1", identifier: "", frame: CGRect(x: 0, y: 561, width: 131, height: 56), isKey: true), + .init(label: "Delete", identifier: "delete", frame: CGRect(x: 262, y: 730, width: 131, height: 54), isKey: true), + ] XCTAssertEqual( - RunnerKeyboardReturnKey.probeLabels, - ["return", "Return", "Enter", "Go", "Search", "Next", "Done", "Send", "Join"] - ) - } - - /// A key whose wording the rule does not recognize keeps its wording, which is the whole point of - /// reporting the label: a localized or a custom key stays readable where the kind is `unknown`. The - /// caller has already established the control is the return key, so any wording on it is the label. - func testKeyboardStatusKeepsAnUnrecognizedLabelVerbatim() { - for label in ["Send Message", "搜索", "完了"] { - let status = RunnerKeyboardStatus.observed(visible: true, returnControlText: label) - XCTAssertEqual(status.returnKey, "unknown", label) - XCTAssertEqual(status.returnKeyLabel, label) - } - } - -#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)])) - ) + RunnerKeyboardStatus.observed(keyboardFrame: keyboard, keys: keys, nativeDisplaySize: display, interfaceOrientation: RunnerInterfaceOrientation.portrait), + RunnerKeyboardStatus(visible: true, returnKey: "unknown", returnKeyLabel: nil) ) - 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. - @MainActor - func testObservedKeyboardKeysReadsKeysThenButtonsFromOneKeyboardSnapshot() { - let frame = CGRect(x: 0, y: 0, width: 40, height: 40) - let keyboard = ElementAttributesFixture(.keyboard, frame, children: [ - ElementAttributesFixture(.other, frame, children: [ - ElementAttributesFixture(.key, frame, label: "q"), - ElementAttributesFixture(.button, frame, label: "shift"), - ElementAttributesFixture(.key, frame, label: ""), - ]), - ElementAttributesFixture(.key, frame, label: " "), - ElementAttributesFixture(.staticText, frame, label: "ignored"), - ElementAttributesFixture(.button, frame, label: "Next:"), - ]) - XCTAssertEqual(observedKeyboardKeys(in: keyboard).map(\.text), ["q", " ", "shift", "Next:"]) - } -#endif - - /// Builds a keyboard's observed controls from the frames this read measured; a zero width is an - /// element with no usable frame, such as the padding entries a keyboard exposes. - private func observedKeyboardKeysFixture( - _ entries: [(text: String, x: CGFloat, y: CGFloat, width: CGFloat)] - ) -> [RunnerKeyboardStatus.ObservedKeyboardKey] { - entries.map { entry in - RunnerKeyboardStatus.ObservedKeyboardKey( - text: entry.text, - frame: CGRect(x: entry.x, y: entry.y, width: entry.width, height: entry.width > 0 ? 54 : 0) - ) - } } } #endif diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardTests.swift index 9ffc22549e..0c55661cfd 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+KeyboardTests.swift @@ -139,53 +139,6 @@ extension RunnerTests { #endif - /// The two ways a visible keyboard stays up answer different questions, so they must not share one - /// code (#1606). Finding no dismiss control sent nothing and is the runner's own refusal; a control - /// that was tapped and left the keys up did dispatch and keeps the generic code. The host reads the - /// first code's literal to publish `details.reason`, so it is pinned here as the wire value. - func testKeyboardDismissRefusalNamesItsOwnCodeOnlyWhenNothingWasDispatched() { - let notDispatched = keyboardDismissRefusal(dispatchedDismissal: false) - XCTAssertEqual(notDispatched.code, "KEYBOARD_DISMISS_UNAVAILABLE") - XCTAssertNotNil(notDispatched.hint) - - let dispatched = keyboardDismissRefusal(dispatchedDismissal: true) - XCTAssertEqual(dispatched.code, "UNSUPPORTED_OPERATION") - XCTAssertNotNil(dispatched.hint) - 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() { - let refusal = keyboardReturnRefusal - XCTAssertEqual(refusal.code, "KEYBOARD_RETURN_UNAVAILABLE") - XCTAssertNotNil(refusal.hint) - } - - /// A sole field that was found and tapped but would not take the return is a failed attempt, not an - /// absent control, so it must not publish the unavailable reason. - func testKeyboardReturnFieldAttemptFailureIsNotTheTypedRefusal() { - let failure = keyboardReturnFieldAttemptFailure - XCTAssertEqual(failure.code, "UNSUPPORTED_OPERATION") - XCTAssertNotEqual(failure.code, keyboardReturnRefusal.code) - } - func testKeyboardBandFactPublishesAbsenceWhenTheCompleteCaptureHasNoKeyboard() { let fact = runnerKeyboardBandFact(exists: false, frame: .zero) XCTAssertEqual(fact, .absent) @@ -261,65 +214,9 @@ extension RunnerTests { } } - func testRunnerScreenshotStabilitySettledNeedsEnoughSamples() { - XCTAssertFalse(runnerScreenshotStabilitySettled([], requiredConsecutiveMatches: 3)) - XCTAssertFalse(runnerScreenshotStabilitySettled([Data([1])], requiredConsecutiveMatches: 3)) - let frame = Data([1, 2, 3]) - XCTAssertFalse( - runnerScreenshotStabilitySettled([frame, frame], requiredConsecutiveMatches: 3) - ) - } - - func testRunnerScreenshotStabilitySettledFalseOnMidWindowMismatch() { - // A momentary pause (two matching samples) followed by resumed movement - // must not read as settled: the 3-sample window still spans the mismatch. - let frame = Data([1, 2, 3]) - let moved = Data([4, 5, 6]) - XCTAssertFalse( - runnerScreenshotStabilitySettled([frame, frame, moved], requiredConsecutiveMatches: 3) - ) - } - - func testRunnerScreenshotStabilitySettledFalseOnFailedCapture() { - // A nil sample (failed screenshot) never counts as a match, even against - // other nils — an unverifiable run must not look "stable". - XCTAssertFalse(runnerScreenshotStabilitySettled([nil, nil, nil], requiredConsecutiveMatches: 3)) - let frame = Data([1, 2, 3]) - XCTAssertFalse( - runnerScreenshotStabilitySettled([frame, frame, nil], requiredConsecutiveMatches: 3) - ) - } - - func testRunnerScreenshotStabilitySettledOnlyLooksAtTheTrailingWindow() { - // An older mismatch before the trailing window must not block settlement - // once the required run of most-recent samples agrees. - let frame = Data([9]) - XCTAssertTrue( - runnerScreenshotStabilitySettled( - [Data([1]), Data([2]), frame, frame, frame], - requiredConsecutiveMatches: 3 - ) - ) - } - - func testRunnerScreenshotStabilitySettledRejectsDegenerateRequirement() { - // Fewer than 2 required matches would make any single sample "settled" — - // guard against a misconfigured caller rather than silently no-op the wait. - XCTAssertFalse( - 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 { + func testKeyboardReturnWithNothingFocusedLeavesTheSoleTextInputAlone() throws { app.launchArguments = [ "--agent-device-text-entry-regression", "--agent-device-text-entry-soft-keyboard", @@ -333,8 +230,10 @@ extension RunnerTests { XCTAssertEqual(textEntryInputCount(), 1) XCTAssertEqual(recordedFailures, 0) - XCTAssertTrue(response.ok, String(describing: response.error)) - XCTAssertEqual(field.value as? String, "", "the field's submit clears it") + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.keyboardReturnUnavailable) + XCTAssertFalse(response.ok) + XCTAssertFalse((field.value as? String ?? "").isEmpty) + XCTAssertFalse(isKeyboardVisible(app: app)) } @MainActor @@ -378,26 +277,26 @@ extension RunnerTests { app.textFields.count + app.secureTextFields.count + app.searchFields.count + app.textViews.count } - // `keyboard dismiss` and `keyboard enter` tap a keyboard control. An app that never stops animating - // made that tap wait for XCTest's idle timeout, past the runner's main-thread watchdog, so the command - // failed with "main thread execution timed out" and the runner refused the next commands. The fixture - // keeps an animation in flight while its field has focus, until its backstop, and records whether - // each control landed while the app was still busy. - static let keyboardBusyBackstop: TimeInterval = 20 - @MainActor - func testKeyboardDismissTapsItsDismissKeyWhileTheAppIsBusy() throws { - try withBusyKeyboardField { - let command = try runnerCommandFixture(#"{"command":"keyboardDismiss","commandId":"dismiss-busy"}"#) - let response = try execute(command: command) - - XCTAssertTrue(response.ok, String(describing: response.error)) - let answer = app.staticTexts["agent-device-keyboard-busy-answer"].label - XCTAssertEqual(answer, "Done while busy") - NSLog("AGENT_DEVICE_KEYBOARD_BUSY command=dismiss response.ok=%@ answer=%@", response.ok ? "true" : "false", answer) + func testKeyboardEnterSendsOneReturnToAFocusedWebViewInput() throws { + app.launchArguments = ["--agent-device-keyboard-webview"] + app.launch() + defer { + invalidateCachedTarget(reason: "unit_test_cleanup") + app.terminate() } + let field = app.webViews.textFields["Web Search"] + XCTAssertTrue(field.waitForFixtureExistence(timeout: appExistenceTimeout)) + field.tap() + let command = try runnerCommandFixture(#"{"command":"keyboardReturn","commandId":"return-webview-input"}"#) + let response = try executeOnMainPrepared(command: command, activeApp: app) + + XCTAssertTrue(response.ok, String(describing: response.error)) + XCTAssertTrue(app.webViews.staticTexts["Return 1"].waitForFixtureExistence(timeout: appExistenceTimeout)) } + static let keyboardBusyBackstop: TimeInterval = 20 + @MainActor func testKeyboardEnterPressesReturnWhileTheAppIsBusy() throws { try withBusyKeyboardField { @@ -405,7 +304,6 @@ extension RunnerTests { let response = try execute(command: command) XCTAssertTrue(response.ok, String(describing: response.error)) - XCTAssertEqual(response.data?.wasVisible, true) XCTAssertEqual(response.data?.visible, false) let answer = app.staticTexts["agent-device-keyboard-busy-answer"].label XCTAssertEqual(answer, "Return while busy") @@ -413,61 +311,62 @@ 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") + func testKeyboardDismissDoesNotPressAnAdjacentAppButton() throws { + try withDoneReturnField(variant: "adjacent-app-button") { answer in + let button = app.buttons["agent-device-adjacent-done"] + XCTAssertTrue(button.isHittable) let response = try execute( - command: try runnerCommandFixture(#"{"command":"keyboardDismiss","commandId":"dismiss-done-return"}"#) + command: try runnerCommandFixture(#"{"command":"keyboardDismiss","commandId":"dismiss-adjacent-app-button"}"#) ) - XCTAssertFalse(response.ok) XCTAssertEqual(response.error?.code, RunnerWireErrorCode.keyboardDismissUnavailable) XCTAssertEqual(answer.label, "Unanswered") XCTAssertTrue(isKeyboardVisible(app: app)) + + button.tap() + XCTAssertEqual(answer.label, "Screen") } } - /// 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") + func testKeyboardDismissDoesNotPressTheAccessoryOrReturnKey() throws { + try withDoneReturnField(variant: "accessory") { answer in + let response = try execute( + command: try runnerCommandFixture(#"{"command":"keyboardDismiss","commandId":"dismiss-done-accessory"}"#) + ) + + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.keyboardDismissUnavailable) + XCTAssertEqual(answer.label, "Unanswered") + XCTAssertTrue(isKeyboardVisible(app: app)) + } } - /// 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") + func testKeyboardStatusReadsTheFocusedReturnInLandscape() throws { + let originalOrientation = XCUIDevice.shared.orientation + defer { XCUIDevice.shared.orientation = originalOrientation } + try withDoneReturnField { _ in + XCUIDevice.shared.orientation = .landscapeLeft + app.textFields["agent-device-keyboard-done-return-input"].tap() + let viewport = try onScreenWindowFrame(app: app) + XCTAssertGreaterThan(viewport.width, viewport.height) + XCTAssertEqual(keyboardStatus(app: app)?.returnKey, "done") + } } @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)) + func testExplicitGestureViewportIncludesTheKeyboard() throws { + try withDoneReturnField { _ in + let window = try onScreenWindowFrame(app: app) + XCTAssertEqual(try gestureViewportFrame(app: app, includesKeyboard: true), window) + XCTAssertLessThan(try gestureViewportFrame(app: app).height, window.height) } } @MainActor - private func withDoneReturnField(accessory: String? = nil, _ body: (XCUIElement) throws -> Void) throws { - app.launchArguments = ["--agent-device-keyboard-done-return"] + (accessory.map { [$0] } ?? []) + private func withDoneReturnField(variant: String? = nil, _ body: (XCUIElement) throws -> Void) throws { + app.launchArguments = ["--agent-device-keyboard-done-return"] + (variant.map { [$0] } ?? []) app.launch() defer { invalidateCachedTarget(reason: "unit_test_cleanup") @@ -480,13 +379,10 @@ extension RunnerTests { mainOwned.processIdentifier = try XCTUnwrap(Self.processIdentifier(of: app)) field.tap() let keyboardDeadline = Date().addingTimeInterval(5) - while !isKeyboardVisible(app: app) && Date() < keyboardDeadline { + while keyboardStatus(app: app)?.visible != true && 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" - ) + XCTAssertEqual(keyboardStatus(app: app)?.visible, true, "The fixture requires a visible software keyboard") let answer = app.staticTexts["agent-device-keyboard-done-return-answer"] XCTAssertEqual(answer.label, "Unanswered") try body(answer) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+ModelsTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+ModelsTests.swift index 2abfd26bb2..981563d98c 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+ModelsTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+ModelsTests.swift @@ -9,8 +9,7 @@ extension RunnerTests { message: "message", hint: "hint", retryableFailure: .targetAppUnavailable, - dismissControls: [DismissControlPayload(label: "Close", identifier: "close", pressBy: .label)], - cause: "tree_unreadable" + dismissControls: [DismissControlPayload(label: "Close", identifier: "close", pressBy: .label)] ) let encoded = try JSONEncoder().encode(payload) let object = try XCTUnwrap(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) diff --git a/apple/runner/README.md b/apple/runner/README.md index 78e4828034..912ece2024 100644 --- a/apple/runner/README.md +++ b/apple/runner/README.md @@ -58,7 +58,7 @@ Protocol and maintenance references: ### Busy keyboard regression tests -Run the two `testKeyboard*WhileTheAppIsBusy` tests with the simulator software keyboard enabled. +Run `testKeyboardEnterPressesReturnWhileTheAppIsBusy` with the simulator software keyboard enabled. Before you boot a throwaway simulator, save the current hardware-keyboard preference: ```sh @@ -78,8 +78,7 @@ fi ``` If the software keyboard does not appear, the tests fail instead of skipping. -The tests assert command success and the fixture's `Done while busy` or `Return while busy` label. -The Return test also asserts the keyboard visibility reported after submission. +The test asserts successful Return, the fixture's `Return while busy` label, and keyboard visibility after submission. ## Snapshot Strategy diff --git a/apple/runner/RUNNER_PROTOCOL.md b/apple/runner/RUNNER_PROTOCOL.md index d4bf0bf86e..da7e50afe8 100644 --- a/apple/runner/RUNNER_PROTOCOL.md +++ b/apple/runner/RUNNER_PROTOCOL.md @@ -294,26 +294,25 @@ Successful and failed responses use the same top-level envelope: "ok": false, "error": { "code": "KEYBOARD_DISMISS_UNAVAILABLE", - "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)" + "message": "The Apple runner cannot dismiss this keyboard automatically" } } ``` -The example is a `keyboard dismiss` the keyboard would not come down for; a refusal that can name a -next step also carries `hint`, omitted here. A keyboard that stayed up answers one of two codes: -`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`. 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 -key and for which no text field could be found; it proves no submission, not that nothing ran, because -typing the return can fail after XCTest sent it. A sole text field that was found and tapped but would -not take the return answers `UNSUPPORTED_OPERATION` with no code, since the control exists and the tap -may have landed. `HARDWARE_CONTROL_UNAVAILABLE` is a press the runner answers that its target cannot +When the software keyboard is visible, `keyboard dismiss` returns `KEYBOARD_DISMISS_UNAVAILABLE`. +The host maps it to `UNSUPPORTED_OPERATION` with `details.reason: "keyboard_dismiss_unavailable"` +and `details.dispatched: "no"`. When the keyboard state is unreadable, `keyboard status` and +`keyboard dismiss` return `OBSERVATION_UNAVAILABLE`. + +When the runner recognizes a visible Return key's accessibility identifier, `keyboard status` +returns its action and available localized label. A visible keyboard with a label-only Return key +returns `unknown` and omits the label. + +When the runner cannot confirm that Return reached the focused input, `keyboard enter` returns +`KEYBOARD_RETURN_UNAVAILABLE`. The host reports `details.dispatched: "unknown"` because the +event may have reached the app. + +`HARDWARE_CONTROL_UNAVAILABLE` is a press the runner answers that its target cannot perform. The runner emits it for the Action Button on an iPhone or iPad model that has none, for a volume press on a simulator, and for a Siri Remote press off tvOS. Runtime admission refuses the last two before the runner is asked, so through the daemon only the Action Button case reaches a caller. diff --git a/contracts/fixtures/runner-requests.json b/contracts/fixtures/runner-requests.json index 115b9a5b16..2e3487fc00 100644 --- a/contracts/fixtures/runner-requests.json +++ b/contracts/fixtures/runner-requests.json @@ -20,6 +20,7 @@ {"name": "ios-simulator.interactions-fill.non-hittable-fallback", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "type", "x": 10, "y": 20, "text": "hello", "textEntryMode": "replace", "allowNonHittableCoordinateFallback": true, "appBundleId": "com.example.app", "commandId": ""}}, {"name": "ios-simulator.interactions-fill.replace", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "type", "x": 10, "y": 20, "text": "hello", "delayMs": 10, "textEntryMode": "replace", "appBundleId": "com.example.app", "commandId": ""}}, {"name": "ios-simulator.interactions-focus.synthesized", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "tap", "x": 10, "y": 20, "synthesized": true, "appBundleId": "com.example.app", "commandId": ""}}, + {"name": "ios-simulator.interactions-gesture-viewport.include-keyboard", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "gestureViewport", "appBundleId": "com.example.app", "includesKeyboard": true, "commandId": ""}}, {"name": "ios-simulator.interactions-gesture-viewport.read", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "gestureViewport", "appBundleId": "com.example.app", "commandId": ""}}, {"name": "ios-simulator.interactions-gesture.multi", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "gesture", "gesturePlan": {"topology": "multi", "intent": "pinch", "durationMs": 250, "viewport": {"x": 0, "y": 0, "width": 390, "height": 844}, "pointers": [{"pointerId": 0, "samples": [{"offsetMs": 0, "point": {"x": 150, "y": 422}}, {"offsetMs": 250, "point": {"x": 100, "y": 422}}]}, {"pointerId": 1, "samples": [{"offsetMs": 0, "point": {"x": 240, "y": 422}}, {"offsetMs": 250, "point": {"x": 290, "y": 422}}]}]}, "appBundleId": "com.example.app", "commandId": ""}}, {"name": "ios-simulator.interactions-gesture.screen-edge", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "gesture", "gesturePlan": {"topology": "single", "intent": "fling", "executionProfile": "endpoint-hold", "durationMs": 100, "viewport": {"x": 0, "y": 0, "width": 390, "height": 844}, "pointers": [{"pointerId": 0, "samples": [{"offsetMs": 0, "point": {"x": 8, "y": 422}}, {"offsetMs": 100, "point": {"x": 331, "y": 422}}]}], "contactOrigin": "screen-edge"}, "appBundleId": "com.example.app", "commandId": ""}}, diff --git a/packages/apple-runner/src/__tests__/runner-contract-dismiss-controls.test.ts b/packages/apple-runner/src/__tests__/runner-contract-dismiss-controls.test.ts index 56f5a72583..121a6388f1 100644 --- a/packages/apple-runner/src/__tests__/runner-contract-dismiss-controls.test.ts +++ b/packages/apple-runner/src/__tests__/runner-contract-dismiss-controls.test.ts @@ -64,24 +64,3 @@ test('only the no-change refusal publishes dismiss controls', () => { 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 27f8d4a7f1..1af83d7504 100644 --- a/packages/apple-runner/src/runner-contract.ts +++ b/packages/apple-runner/src/runner-contract.ts @@ -136,6 +136,7 @@ export type RunnerCommand = { delayMs?: number; textEntryMode?: 'append' | 'replace'; action?: 'get' | 'accept' | 'dismiss'; + includesKeyboard?: boolean; x?: number; y?: number; button?: ClickButton; @@ -296,23 +297,10 @@ export function resolveRunnerStartupSignal( */ export const SCROLL_KEYBOARD_OCCLUDES_SURFACE_RUNNER_CODE = 'SCROLL_KEYBOARD_OCCLUDES_SURFACE'; -/** - * The runner's own code refusing a `keyboard dismiss` whose visible keyboard exposes no dismiss key - * (#1606). Background taps are never attempted, so no geometry can prove a tap outside the keys is - * side-effect-free; the refusal is the runner's decision and it answers before dispatching anything. - * It is the runner's vocabulary, so it is declared here beside the set that keeps it off the wire, - * and consumers read `details.reason`, never the message prose. - */ +/** The Apple runner left the visible keyboard alone. */ export const KEYBOARD_DISMISS_UNAVAILABLE_RUNNER_CODE = 'KEYBOARD_DISMISS_UNAVAILABLE'; -/** - * The runner's own code refusing a `keyboard enter` whose keyboard exposes no return-like key and for - * which no text field could be found to submit through. Unlike the dismiss refusal it cannot prove - * nothing ran: typing the return can fail after XCTest sent it, so the disclosure stays `unknown`. A - * sole field that was found and tapped but would not take the return is not this refusal. It is the - * runner's vocabulary, declared here beside the set that keeps it off the wire, and consumers read - * `details.reason`. - */ +/** A Return attempt on the focused input could not be confirmed. */ export const KEYBOARD_RETURN_UNAVAILABLE_RUNNER_CODE = 'KEYBOARD_RETURN_UNAVAILABLE'; /** @@ -560,7 +548,6 @@ export type RunnerResponsePayload = { message?: unknown; hint?: unknown; dismissControls?: unknown; - cause?: unknown; }; data?: unknown; }; @@ -664,17 +651,10 @@ 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 708df0273c..78d73fbebf 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. 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."; + 'Read the software keyboard state with status (alias get). A visible keyboard can include returnKey and its localized accessibility label. An unreadable Apple keyboard state reports OBSERVATION_UNAVAILABLE. Enter (alias return) sends Return to the focused input. The app may submit, move focus, or insert a newline. On the native iOS runner, dismiss succeeds as a no-op when the software keyboard is hidden. A visible keyboard returns keyboard_dismiss_unavailable with dispatched: no. Press the visible Hide Keyboard key or an app control that ends editing. If the app supports interactive dismissal, use gesture pan to drag a finger down from inside its scrollable content and verify with status. Android dismiss sends its platform dismissal action.'; 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 = diff --git a/packages/contracts/src/backend.ts b/packages/contracts/src/backend.ts index d39bc8e394..d57fff756e 100644 --- a/packages/contracts/src/backend.ts +++ b/packages/contracts/src/backend.ts @@ -100,8 +100,7 @@ export type BackendKeyboardResult = { wasVisible?: boolean; dismissed?: boolean; attempts?: number; - /** iOS only: which mechanism resigned the keyboard (#1598) — 'dismissKey' - * (tapped the keyboard's own Hide/Dismiss/Done key); background-tap dismissal is deliberately unsupported (#1606 review). */ + /** The dismiss mechanism when the serving runtime reports one. */ mechanism?: string; }; diff --git a/packages/contracts/src/gesture-runtime.ts b/packages/contracts/src/gesture-runtime.ts index d0246a6309..6243272115 100644 --- a/packages/contracts/src/gesture-runtime.ts +++ b/packages/contracts/src/gesture-runtime.ts @@ -26,6 +26,7 @@ export type GesturePlanInput = Readonly<{ /** Reading the gesture coordinate frame needs no plan — only the owner's authority. */ export type GestureViewportInput = Readonly<{ + includesKeyboard?: true; options?: Readonly<{ appBundleId?: string }>; execution?: SnapshotRuntimeExecution; }>; @@ -151,7 +152,9 @@ function bindGestureOperations( 'Runtime owner advertised gestureViewport without an interactor implementation', ); } - return await interactor.gestureViewport(); + return input.includesKeyboard + ? await interactor.gestureViewport(true) + : await interactor.gestureViewport(); }, } : {}), diff --git a/packages/contracts/src/interactor-types.ts b/packages/contracts/src/interactor-types.ts index b8fba14f41..515a961501 100644 --- a/packages/contracts/src/interactor-types.ts +++ b/packages/contracts/src/interactor-types.ts @@ -422,7 +422,7 @@ export type Interactor = { ): Promise<{ found: boolean; }>; - gestureViewport?(): Promise; + gestureViewport?(includesKeyboard?: true): Promise; back(mode?: BackMode): Promise; /** * Optional (parity with `actionButton`): opens the springboard, a control not every owner diff --git a/packages/contracts/src/keyboard.ts b/packages/contracts/src/keyboard.ts index 48dae55b92..fe5d1fe27d 100644 --- a/packages/contracts/src/keyboard.ts +++ b/packages/contracts/src/keyboard.ts @@ -1,17 +1,4 @@ -/** - * The return key one platform reports for the focused field, in the vocabulary both platforms' - * readings project into: Apple's `UITextInput.returnKeyType` wording and Android's - * `EditorInfo.imeOptions` action bits each map onto these kinds. - * - * `unknown` means this read could not name the key, not that the keyboard has one: the Apple runner - * answers it when the return key it identified carries wording this vocabulary does not map (its label - * is still reported), or when the keyboard exposes no return key it can identify at all — a number, - * decimal or phone pad has none, and an iPad keyboard puts numbers and hide keys where the rule reads - * the return key. Android answers it when the - * focused editor's `imeOptions` name no action. `none` means the platform established that the field - * offers no action key at all (Android's `IME_ACTION_NONE`); no other platform can establish absence, - * so only Android reports it. - */ +/** A platform reports `unknown` when it cannot identify the action and `none` when it establishes there is no action. */ export const KEYBOARD_RETURN_KEYS = [ 'go', 'search', @@ -63,11 +50,6 @@ export type KeyboardCommandResult = { * string. Both producers read it from a dump or the accessibility tree, and trim it there. */ returnKeyLabel?: string; message?: string; - /** iOS `dismiss` only (#1598): which mechanism actually resigned the - * keyboard — 'dismissKey' (tapped the keyboard's own Hide/Dismiss/Done - * key). Generic background-tap dismissal is deliberately unsupported - * (#1606 review): no query can prove a coordinate is side-effect-free, - * so the runner only ever taps the keyboard's own control. Absent when - * the keyboard was not dismissed. */ + /** The dismiss mechanism when the serving runtime reports one. */ mechanism?: 'dismissKey'; }; diff --git a/packages/contracts/src/scroll-gesture.ts b/packages/contracts/src/scroll-gesture.ts index 04fc049b04..7a7f11fb8f 100644 --- a/packages/contracts/src/scroll-gesture.ts +++ b/packages/contracts/src/scroll-gesture.ts @@ -467,7 +467,7 @@ export const SCROLL_KEYBOARD_OCCLUDES_SURFACE_DETAILS = Object.freeze({ reason: SCROLL_KEYBOARD_OCCLUDES_SURFACE_REASON, hint: 'The on-screen keyboard covers the surface this scroll would swipe, so it cannot reach it. ' + - 'Run `keyboard dismiss` and retry, accepting that it drops focus (re-tap the field to keep typing), or scroll before focusing the field.', + 'End editing with a visible dismissal control, or use `keyboard dismiss` on Android. You can also scroll before focusing the field.', }); export type ScrollKeyboardClip = diff --git a/packages/contracts/src/tap-keyboard-occlusion.ts b/packages/contracts/src/tap-keyboard-occlusion.ts index 4d1bba3561..2bb453578e 100644 --- a/packages/contracts/src/tap-keyboard-occlusion.ts +++ b/packages/contracts/src/tap-keyboard-occlusion.ts @@ -44,11 +44,7 @@ export const TAP_KEYBOARD_OCCLUDES_TARGET_REASON = 'tap_keyboard_occludes_target /** * The hint every owner publishes beside the reason, naming the recovery that actually works. - * `keyboard dismiss` taps the keyboard's own dismiss control and refuses when it exposes none - * (#1598/#1606), so an app control that ends editing, or `keyboard enter` when submitting is the - * goal, come first. Nothing here dismisses the keyboard for the caller: dropping focus commits or - * cancels edit state, which is the caller's decision rather than a side effect of a tap — the same - * stance `scroll-gesture.ts` takes for the surface it refuses to swipe. + * Editing ends through an explicit action from the caller. * * The verdict is read from the tree the command measured against, and no owner re-probes the * keyboard to confirm it: `keyboard status`/`get` answer only what a visible keyboard's return key @@ -60,8 +56,8 @@ export const TAP_KEYBOARD_OCCLUDES_TARGET_DETAILS = Object.freeze({ reason: TAP_KEYBOARD_OCCLUDES_TARGET_REASON, hint: 'The visible keyboard covers this target, so the tap would land on a key instead of on it. ' + - "End editing first: tap the app's own Done/Cancel/close control, or run `keyboard enter` when submitting is what you want " + - '(`keyboard dismiss` works only when the keyboard exposes its own dismiss key). ' + + 'End editing first. Press a visible dismiss key such as Hide Keyboard, or the app control that ends editing. ' + + 'On Android, use `keyboard dismiss`. Use `keyboard enter` when you intend to send Return. ' + 'This reads the snapshot the command measured against, so if the keyboard closed since it was taken, ' + 'run `snapshot -i` and retry.', }); diff --git a/packages/daemon/src/core/gesture-runtime.ts b/packages/daemon/src/core/gesture-runtime.ts index b0d07bb186..35e5d4f6e8 100644 --- a/packages/daemon/src/core/gesture-runtime.ts +++ b/packages/daemon/src/core/gesture-runtime.ts @@ -122,7 +122,16 @@ export async function resolveBoundGestureRuntime( }); if (admitted.type === 'response') return { ok: false, response: admitted.response }; // One bind, with the exactly-typed use the tier selected (ADR 0019 §9). - return { ok: true, gestures: await bindGestureTier(admitted.bind, params.device, plan) }; + const includesKeyboard = + params.input.intent === 'pan' && + (params.input.pointerCount ?? 1) === 1 && + params.input.executionProfile !== 'endpoint-hold' + ? true + : undefined; + return { + ok: true, + gestures: await bindGestureTier(admitted.bind, params.device, plan, includesKeyboard), + }; } /** @@ -137,6 +146,7 @@ async function bindGestureTier( bind: Extract>, { type: 'admitted' }>['bind'], device: DeviceInfo, plan: GestureRuntimePlan, + includesKeyboard?: true, ): Promise { switch (plan.tier) { case 'plan': { @@ -144,7 +154,7 @@ async function bindGestureTier( return { performPlan: async (gesturePlan, context) => await runtime.operations.performGesturePlan(gesturePlanInput(gesturePlan, context)), - ...selectGestureFrame(runtime), + ...selectGestureFrame(runtime, includesKeyboard), ...(runtime.operations.querySelector ? { querySelector: runtime.operations.querySelector } : {}), @@ -207,6 +217,7 @@ function selectGestureFrame( gestureViewport?: GestureRuntimeOperations['gestureViewport']; }>; }>, + includesKeyboard?: true, ): Pick; function selectGestureFrame( runtime: Readonly<{ @@ -215,6 +226,7 @@ function selectGestureFrame( gestureViewport?: GestureRuntimeOperations['gestureViewport']; }>; }>, + includesKeyboard?: true, ): Partial> { const { gestureViewport } = runtime.operations; const selectedCapture = runtime.operations.captureSnapshot @@ -231,7 +243,9 @@ function selectGestureFrame( ...(selected ? { gestureViewport: async (context: DaemonCommandContext) => - await selected.operations.gestureViewport(gestureViewportInput(context)), + await selected.operations.gestureViewport( + gestureViewportInput(context, includesKeyboard), + ), } : {}), }); @@ -246,8 +260,9 @@ function gesturePlanInput(plan: GesturePlan, context: DaemonCommandContext): Ges }; } -function gestureViewportInput(context: DaemonCommandContext) { +function gestureViewportInput(context: DaemonCommandContext, includesKeyboard?: true) { return { + ...(includesKeyboard ? { includesKeyboard } : {}), ...(context.appBundleId === undefined ? {} : { options: { appBundleId: context.appBundleId } }), execution: runtimeExecutionFromContext(context), }; diff --git a/packages/daemon/src/execution/interaction/internal/interaction-gesture-viewport.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-gesture-viewport.test.ts new file mode 100644 index 0000000000..2a376608bb --- /dev/null +++ b/packages/daemon/src/execution/interaction/internal/interaction-gesture-viewport.test.ts @@ -0,0 +1,70 @@ +import { expect, test } from 'vitest'; +import { daemonPlatformServicesFixture } from '../../../__tests__/support/platform-services-fixture.ts'; +import { makeIosSession } from '../../../__tests__/support/session-factories.ts'; +import { makeSessionStore } from '../../../__tests__/support/store-factory.ts'; +import { touchCreateCommandSurface } from '../../../__tests__/support/touch-command-surface-fake.ts'; +import { handleInteractionCommands } from '../index.ts'; +import { gestureRuntimeBindingsFixture } from './__tests__/gesture-runtime-bindings.fixtures.ts'; + +const from = { x: 120, y: 220 }; +const to = { x: 120, y: 320 }; +const pan = { kind: 'pan', origin: from, delta: { x: 0, y: 100 }, durationMs: 500 }; + +test.each([ + { name: 'one-finger pan', command: 'gesture', input: pan, includesKeyboard: true }, + { name: 'two-finger pan', command: 'gesture', input: { ...pan, pointerCount: 2 } }, + { name: 'fling', command: 'gesture', input: { kind: 'fling', direction: 'down', origin: from } }, + { name: 'swipe', command: 'swipe', input: { from, to } }, + { + name: 'Maestro coordinate swipe', + command: 'gesture', + input: pan, + internal: { gestureExecutionProfile: 'endpoint-hold' }, + }, +] as const)('$name requests the appropriate iOS viewport', async (scenario) => { + const sessionName = 'gesture-viewport'; + const sessionStore = makeSessionStore(); + sessionStore.publish( + sessionName, + makeIosSession(sessionName, { appBundleId: 'com.example.app' }), + ); + const { gestureViewport, inspectFacts, bindDevice } = gestureRuntimeBindingsFixture(); + + const response = await handleInteractionCommands({ + createCommandSurface: async (config) => { + const surface = await touchCreateCommandSurface(config); + return { + ...surface, + interactions: { + ...surface.interactions, + gesture: async (options) => { + await config.backend.resolveGestureViewport?.({ session: sessionName }); + return await surface.interactions.gesture(options); + }, + }, + }; + }, + platformServices: daemonPlatformServicesFixture(), + req: { + token: 't', + session: sessionName, + command: scenario.command, + positionals: [], + flags: {}, + input: scenario.input, + ...('internal' in scenario ? { internal: scenario.internal } : {}), + }, + sessionName, + sessionStore, + captureSnapshotForSession: async ({ session }) => session.snapshot!, + contextFromFlags: () => ({}), + inspectFacts, + bindDevice, + }); + + expect(response).toMatchObject({ ok: true }); + expect(gestureViewport).toHaveBeenCalledOnce(); + expect(gestureViewport.mock.calls[0]?.[0].includesKeyboard).toBe( + 'includesKeyboard' in scenario ? scenario.includesKeyboard : undefined, + ); +}); diff --git a/packages/maestro/src/internal/support-matrix.ts b/packages/maestro/src/internal/support-matrix.ts index e2b62a39e6..7e130ab643 100644 --- a/packages/maestro/src/internal/support-matrix.ts +++ b/packages/maestro/src/internal/support-matrix.ts @@ -6,6 +6,7 @@ export const MAESTRO_COMPAT_SUPPORTED_CAPABILITIES = [ ] as const; export const MAESTRO_COMPAT_LIMITATIONS = [ + 'On the native iOS runner, use tapOn on a visible dismissal control. If the app supports drag dismissal, use a swipe that stays above the keyboard.', 'Permissions: every entry is one settings permission call, applied in order with all first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so location: inuse and location: never mean allow and deny there, while location: always and photos: limited are Apple-only and fail. On iOS, which service a runtime changes is simctl privacy’s own verdict: current runtimes refuse a targeted notifications change and leave notifications untouched under all.', 'Runtime: iOS and Android only; launchApp.clearState and standalone clearState support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading - unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported.', 'Expressions: evalScript and condition true: fields (runFlow.when and repeat.while share one evaluator) are evaluated as JavaScript (flow env and prior output leaves are string-typed); a true: field that is a boolean, a maestro.platform comparison, or plain literal text after ${VAR} lookups is decided without JavaScript, with the assertTrue falsy table for literal text. Other fields stay literal or ${VAR} lookup-only — assertTrue supports literals and bare lookups, and other expression-shaped payloads fail loud.', diff --git a/packages/platform-android/src/device-input-state.ts b/packages/platform-android/src/device-input-state.ts index 0682fab75a..34679f032c 100644 --- a/packages/platform-android/src/device-input-state.ts +++ b/packages/platform-android/src/device-input-state.ts @@ -38,12 +38,7 @@ const ANDROID_IME_FLAG_NO_ENTER_ACTION = 0x40000000; const ANDROID_KEYBOARD_DISMISS_MAX_ATTEMPTS = 2; const ANDROID_KEYBOARD_DISMISS_RETRY_DELAY_MS = 120; const ANDROID_KEYCODE_ESCAPE = '111'; -/** - * `details.reason` of a `keyboard dismiss` whose keyboard stayed up. One reason covers both platforms - * because the concept and the recovery are one thing: the safe mechanism this platform has would not - * bring the keyboard down, so press the app's own control. What differs is how far each got, and - * `details.dispatched` says that, never the reason. - */ +/** Reason shared with an Apple runner that refuses automatic dismissal before dispatch. */ const ANDROID_KEYBOARD_DISMISS_UNAVAILABLE_REASON = 'keyboard_dismiss_unavailable'; const ANDROID_KEYBOARD_VISIBILITY_KEYS = [ 'mInputShown', @@ -154,9 +149,7 @@ export async function dismissAndroidKeyboardWithAdb( 'UNSUPPORTED_OPERATION', 'Android keyboard dismiss is unavailable for the current IME without back navigation.', { - // The same reason the Apple runner publishes for a keyboard that stays up: the safe mechanism - // this platform has would not bring it down. `dispatched` is the producer's own verdict and - // differs here — the escape keyevents above went out, so the disclosure cannot be `no`. + // The Escape key events went out. The final state alone cannot prove what they did. reason: ANDROID_KEYBOARD_DISMISS_UNAVAILABLE_REASON, dispatched: 'unknown', attempts, diff --git a/packages/platform-apple/src/__tests__/index-runner-requests.test.ts b/packages/platform-apple/src/__tests__/index-runner-requests.test.ts index 1c34d343b3..c4efb4b9ca 100644 --- a/packages/platform-apple/src/__tests__/index-runner-requests.test.ts +++ b/packages/platform-apple/src/__tests__/index-runner-requests.test.ts @@ -99,6 +99,10 @@ const INTERACTOR_SITES: Record = { (i) => i.fill(10, 20, 'hello', undefined, { allowNonHittableCoordinateFallback: true }), ], 'ios-simulator.interactions-gesture-viewport.read': [IOS_SIMULATOR, (i) => i.gestureViewport!()], + 'ios-simulator.interactions-gesture-viewport.include-keyboard': [ + IOS_SIMULATOR, + (i) => i.gestureViewport!(true), + ], 'ios-simulator.interactions-press-series.tap': [ IOS_SIMULATOR, press({ count: 2, intervalMs: 50 }), diff --git a/packages/platform-apple/src/interactions.test.ts b/packages/platform-apple/src/interactions.test.ts index 22bac817e4..9940d24670 100644 --- a/packages/platform-apple/src/interactions.test.ts +++ b/packages/platform-apple/src/interactions.test.ts @@ -355,6 +355,12 @@ test('iosRunnerOverrides reads and validates the fresh gesture viewport', async command: 'gestureViewport', appBundleId: 'com.example.App', }); + await overrides.gestureViewport(true); + assert.deepEqual(mockRunAppleRunnerCommand.mock.calls[1]?.[1], { + command: 'gestureViewport', + appBundleId: 'com.example.App', + includesKeyboard: true, + }); mockRunAppleRunnerCommand.mockResolvedValue({ x: 0, y: 0, x2: 0, y2: 500 }); await assert.rejects(() => overrides.gestureViewport!(), { code: 'COMMAND_FAILED' }); }); diff --git a/packages/platform-apple/src/interactions.ts b/packages/platform-apple/src/interactions.ts index 1558245f97..1fe1533c12 100644 --- a/packages/platform-apple/src/interactions.ts +++ b/packages/platform-apple/src/interactions.ts @@ -183,10 +183,14 @@ export function iosRunnerOverrides( ); }, performGesture: async (plan) => await performGestureApple(device, ctx, runnerOpts, plan), - gestureViewport: async () => { + gestureViewport: async (includesKeyboard) => { const result = await runAppleRunnerCommand( device, - { command: 'gestureViewport', appBundleId: ctx.appBundleId }, + { + command: 'gestureViewport', + appBundleId: ctx.appBundleId, + ...(includesKeyboard ? { includesKeyboard } : {}), + }, runnerOpts, ); return readGestureViewport(result); diff --git a/scripts/capability-matrix/annotations.ts b/scripts/capability-matrix/annotations.ts index 3e762048d9..c44cc93ca9 100644 --- a/scripts/capability-matrix/annotations.ts +++ b/scripts/capability-matrix/annotations.ts @@ -163,7 +163,7 @@ export const MATRIX_SECTIONS: readonly MatrixSection[] = [ label: 'Keyboard dismiss, enter, and status', commands: ['keyboard'], link: docs('commands', 'keyboard'), - note: "`status` reports the focused field's return key on a visible keyboard. It does not claim the key can be named: only Android can report `none`, and the Apple runner reports `unknown` for a key whose wording names no action it knows.", + note: 'For a visible keyboard, the Apple runner uses a recognized accessibility identifier to report the Return action as `returnKey` and the key\'s localized wording as `returnKeyLabel`. For example, the identifier `Search` gives `returnKey: "search"` even when the label is `"szukaj"`. If the runner cannot identify the action, it reports `unknown`. Only Android can report `none`.', cells: { 'harmonyos-emulator': { text: 'Dismiss and enter; status unsupported', diff --git a/src/commands/schema/cli-help-command-usage.test.ts b/src/commands/schema/cli-help-command-usage.test.ts index 6ff5f833fd..a05380a5f1 100644 --- a/src/commands/schema/cli-help-command-usage.test.ts +++ b/src/commands/schema/cli-help-command-usage.test.ts @@ -79,15 +79,6 @@ test('usageForCommand supports tap alias for press', async () => { assert.doesNotMatch(help ?? '', /agent-device tap/); }); -test('usageForCommand documents keyboard dismissal flow', async () => { - const help = await usageForCommand('keyboard'); - assert.equal(help === null, false); - assert.match(help ?? '', /keyboard \[status\|get\|dismiss\|enter\|return\]/); - assert.match(help ?? '', /taps the keyboard dismiss\/hide key when one is exposed/); - assert.match(help ?? '', /UNSUPPORTED_OPERATION/); - assert.match(help ?? '', /error\.details\.reason keyboard_dismiss_unavailable/); -}); - test('usageForCommand explains focused perf evidence', async () => { const help = await usageForCommand('perf'); assert.equal(help === null, false); @@ -416,21 +407,6 @@ test('keyboard command usage is documented', async () => { const help = await usageForCommand('keyboard'); if (help === null) throw new Error('Expected command help text'); assert.match(help, /keyboard \[status\|get\|dismiss\|enter\|return\]/); - assert.match(help, /Report or act on the device keyboard/); -}); - -// `keyboard status`'s own output vocabulary, so a caller reading help knows what `returnKey` can say -// and which platform can establish that a field offers no key. The complete list, `none` and -// `unknown` included: dropping either from the description must fail here. -test('usageForCommand documents the keyboard return key read', async () => { - const help = await usageForCommand('keyboard'); - assert.equal(help === null, false); - assert.match( - help ?? '', - /`returnKey` is go, search, send, next, done, previous, join, route, continue, enter, none, or unknown/, - ); - assert.match(help ?? '', /`returnKeyLabel` is the wording that return key itself shows/); - assert.match(help ?? '', /only Android can establish/); }); test('orientation command usage is documented', async () => { diff --git a/src/commands/schema/cli-help-topics.test.ts b/src/commands/schema/cli-help-topics.test.ts index c4575dbe96..76ec9883a2 100644 --- a/src/commands/schema/cli-help-topics.test.ts +++ b/src/commands/schema/cli-help-topics.test.ts @@ -229,11 +229,6 @@ test('usageForCommand resolves workflow help topic', async () => { assert.match(help, /targetHittable: false plus a hint -- verify or re-target, not a failure/); assert.match(help, /fill "" clears the field \(replace with nothing\)/); assert.match(help, /retry with --delay-ms before clipboard paste/); - assert.match( - help, - /keyboard dismiss taps its own dismiss key when one exists, else UNSUPPORTED_OPERATION/, - ); - assert.match(help, /prefer type "\\n" to submit/); assert.match( help, /iOS paste-prompt limits and Android IME\/handwriting capture quirks: help debugging/, diff --git a/src/commands/schema/cli-help-workflows.ts b/src/commands/schema/cli-help-workflows.ts index 0c36d11a98..c0cec411e6 100644 --- a/src/commands/schema/cli-help-workflows.ts +++ b/src/commands/schema/cli-help-workflows.ts @@ -52,7 +52,7 @@ Targets: Recovery: Network/typeahead result missing: wait text "Expected result" or wait . A target that should be gone/disappear: use wait absent ; wait exists ... is rejected in favor of the plain selector wait. - Keyboard visible over the next target: when a measured or derived keyboard frame covers an app target's dispatched tap point, the element is refused with tap_keyboard_occludes_target, because the touch would activate a key instead of the target. End editing first -- the app's own Done/Cancel control, or keyboard enter when submission is wanted -- then retry. Missing keyboard nodes never prove absence; a visibility-only probe cannot establish the covered area. An app target whose dispatched tap point stays above the keys passes this keyboard check; a raw coordinate behind the keyboard taps anyway and reports the reason in warning. + Keyboard visible over the next target: a tap point under a measured keyboard frame returns tap_keyboard_occludes_target. Press a visible Hide Keyboard key or the app's dismissal control. In apps that support drag dismissal, use gesture pan from inside the scrollable content. Use keyboard enter only to send Return. Missing keyboard nodes never prove absence. A raw coordinate behind the keys taps anyway and reports a warning. Target covered by other visible UI: refused with target_covered. When the occlusion scan identified the covering element, error.details.coveredBy and the hint name it (role, label, rect) so you know what to dismiss; the cover is diagnosis only -- never target its ref. Dismiss/close it or scroll the target clear, then retry. Sparse or recovered accessibility snapshot: use screenshot as visual truth, leave the bad screen if needed, then retry snapshot -i. Non-hittable success hint: verify with the settled diff or snapshot; retarget by a better ref/selector if the UI did not change. diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 45e52fdd70..58abf5bfb2 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -106,7 +106,7 @@ Text entry: fill replaces; type appends to an already-focused field: fill 'id="field-email"' "qa@example.com"; type "Handle with care" --delay-ms 80 fill "" clears the field (replace with nothing); the empty argument must be present -- fill alone is a missing argument. For dropped iOS text, retry with --delay-ms before clipboard paste (also Limrun iOS). - Element presses behind the keyboard are refused with tap_keyboard_occludes_target. keyboard dismiss taps its own dismiss key when one exists, else UNSUPPORTED_OPERATION (error.details.reason keyboard_dismiss_unavailable). Android: try dismiss before back. iOS: when both fail, never tap static text/headings; prefer type "\\n" to submit. + Keyboard covers the target (tap_keyboard_occludes_target): on iOS, press a visible Hide Keyboard key or app dismissal control. In apps with drag dismissal, use gesture pan. Android: keyboard dismiss. Use keyboard enter to send Return. iOS paste-prompt limits and Android IME/handwriting capture quirks: help debugging. Session ordering: diff --git a/test/integration/ios-simulator-e2e/live-runner.ts b/test/integration/ios-simulator-e2e/live-runner.ts index bb91f3af7d..497b8d2a42 100644 --- a/test/integration/ios-simulator-e2e/live-runner.ts +++ b/test/integration/ios-simulator-e2e/live-runner.ts @@ -339,6 +339,12 @@ async function assertFormInput(context: LiveContext): Promise { assertJsonContains(seededEmail, 'ada@example', 'seeded email should be observable before submit'); await assertWaitSelector(context, 'label="Done" visible=true'); + const keyboardStatus = await runStep(context, 'read the visible software keyboard', [ + 'keyboard', + 'status', + ]); + assert.equal(keyboardStatus.json?.data?.visible, true, JSON.stringify(keyboardStatus.json)); + const keyboardVisiblePath = path.join(context.artifactDir, 'keyboard-visible.png'); await capturePng(context, 'capture visible input keyboard', keyboardVisiblePath); // The email field's return key reads "Done" and submits, so `keyboard dismiss` must refuse it diff --git a/test/integration/provider-scenarios/ios-world.ts b/test/integration/provider-scenarios/ios-world.ts index 9d7ef91025..0982bb24ae 100644 --- a/test/integration/provider-scenarios/ios-world.ts +++ b/test/integration/provider-scenarios/ios-world.ts @@ -75,7 +75,7 @@ export async function createIosSettingsWorld(): Promise { }, result: { pinched: true }, }, - runnerGestureViewport(), + runnerGestureViewport(true), { command: 'ios.runner.gesture', deviceId: PROVIDER_SCENARIO_IOS_SIMULATOR.id, @@ -516,7 +516,7 @@ function generalCellSnapshot(options: { y: number }) { }; } -function runnerGestureViewport() { +function runnerGestureViewport(includesKeyboard?: true) { return { command: 'ios.runner.gestureViewport', deviceId: PROVIDER_SCENARIO_IOS_SIMULATOR.id, @@ -524,6 +524,7 @@ function runnerGestureViewport() { request: { command: 'gestureViewport', appBundleId: 'com.apple.Preferences', + ...(includesKeyboard ? { includesKeyboard } : {}), }, result: { x: IOS_SETTINGS_VIEWPORT.x, diff --git a/website/docs/docs/capabilities.md b/website/docs/docs/capabilities.md index 8177a7c5c6..ce2c99662e 100644 --- a/website/docs/docs/capabilities.md +++ b/website/docs/docs/capabilities.md @@ -125,7 +125,7 @@ What a **Yes** does not claim: - **Tap, press, and fill**: Android types non-ASCII text through the test input method: automatically on emulators, and on physical devices only with `open --test-ime`. - **Type into the focused field**: Revyl enters text only at a point, so it refuses `type`; use `fill` on the field instead. - **Gesture plans and swipes**: Multi-touch plans are part of `gesture` where the target runs them; a plan using an operation the target lacks fails at that step. -- **Keyboard dismiss, enter, and status**: `status` reports the focused field's return key on a visible keyboard. It does not claim the key can be named: only Android can report `none`, and the Apple runner reports `unknown` for a key whose wording names no action it knows. +- **Keyboard dismiss, enter, and status**: For a visible keyboard, the Apple runner uses a recognized accessibility identifier to report the Return action as `returnKey` and the key's localized wording as `returnKeyLabel`. For example, the identifier `Search` gives `returnKey: "search"` even when the label is `"szukaj"`. If the runner cannot identify the action, it reports `unknown`. Only Android can report `none`. - **React Native overlay dismissal**: The command runs wherever tapping runs; it answers `detected: false` on a surface with no React Native overlay. Only iOS and Android apps present dismissable development overlays. ## Apps and devices diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 076d8bc389..15887d1736 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -479,7 +479,7 @@ agent-device alert dismiss - The Apple XCUITest runner (iOS, tvOS, and visionOS simulators and devices) and Limrun iOS use the same English label preferences after finding an alert: `Allow While Using App` outranks `Allow Once`, and equal-ranked choices refuse. `Open`, `Done`, and `Confirm…` accept; `Keep Browsing`, `Deny`, and `Skip` dismiss. On iOS simulators, including Limrun, the XCUITest runner also recognizes the wording of these labels in each of the device's preferred languages, read from the OS's own notification, privacy (including App Tracking Transparency), location, and `Open in …?` launch-confirmation prompt strings, at the rank of the English label they translate. The translations apply to any alert whose labels match them, not only permission prompts; a translation both roles claim stays unknown. If a notification, privacy, or location table cannot be read, the runner drops the permission translations and keeps the English labels; the `Open in …?` table is read apart, so its labels survive that, and the permission translations survive it being unreadable. Physical iOS devices, tvOS, and visionOS always use the English labels. On iOS simulators, including Limrun, `alert get` marks the `Open in …?` launch confirmation with `launchConfirmationPrompt: true`; `open` reads that mark to answer the prompt. Unknown labels refuse even for a lone button; read `alert get`, then choose explicitly with `snapshot -i` and `press @ref`. Ordinary Android dialogs also recognize these labels; Android permission-button ids keep priority. - On the Apple XCUITest runner, `dismiss` activates only a button its decline list recognizes (`Cancel`, `Don't Allow`, `Ask App Not to Track`, and similar English labels), or the close button of a popover whose native marker reads "dismiss popup". It never taps anything else: unknown, reworded, or localized decline copy outside the preferred languages' prompt strings fails with `error.code: ALERT_BUTTON_NOT_FOUND` and `details.dispatched: no`, tapping nothing, rather than guessing at an affirmative ([#3627](https://github.com/callstack/agent-device/issues/3627)). A button choice that finds no button to name answers with that code and `dispatched: no` for `accept` too. To answer a prompt with unrecognized wording, read the labels with `alert get`, then press the button by label through `snapshot` + `press @ref`. The macOS helper's `dismiss` keeps its own rules (the app's cancel-button attribute, its label list, and a last-button fallback). - An unreadable or ambiguous capture after the action fails with `error.details.runnerErrorCode: ALERT_CONFIRMATION_UNAVAILABLE`; an expired runner deadline during action or confirmation after the alert is resolved fails with `ALERT_DEADLINE_EXCEEDED`. Neither proves the alert is gone or that nothing happened. Run `alert get` before acting again. -- iOS runner refusals carry `error.details.reason`: `runner_busy` means the runner ran nothing (`dispatched: no`); a read-only command resends it until shortly before its own timeout, and `details.attempts` counts the sends. A read inside an action, such as the viewport read before a swipe, sends it at most 8 times in total, as `details.attempts` reports, because the action needs the rest of its timeout. When that window closes first, the command still fails with `runner_busy` (`dispatched: no`), so retry the read; `runner_main_thread_timeout` means the action may still land (`dispatched: unknown`); `no_text_input_at_point` and `text_input_probe_unavailable` mean a `fill` refused before dispatching anything (`dispatched: no`) — see Text entry below. A synthesized long press, `scroll`, `swipe` (sent as a planned fling `gesture`), or other planned `gesture` that the event synthesis refuses before its event record is handed to XCTest reports `COMMAND_FAILED` with `synthesized_gesture_not_dispatched` (`dispatched: no`), and so does a planned `gesture` refused while its window or display is resolved (the window cannot be named, or the sole display cannot be measured); one that fails after the record was handed to XCTest (its events may or may not have run) reports `synthesized_gesture_outcome_unknown` (`dispatched: unknown`) and is never repeated through an XCTest fallback, so check the screen with `snapshot` before you retry. Any other refusal, such as a platform without touch input, keeps `UNSUPPORTED_OPERATION`. A long-press step in a press series reports the same reasons; once an earlier step has run, the series is `dispatched: unknown`. `back_swipe_no_change` means the iOS `back` swipe was sent and the screen did not change, and `back_swipe_unverified` means it was sent but may or may not have navigated (both `dispatched: unknown`); `back_swipe_not_dispatched` means it was refused before any touch went down (`dispatched: no`). A `keyboard dismiss` the keyboard would not come down for because it exposes no dismiss key keeps `UNSUPPORTED_OPERATION` and reports `keyboard_dismiss_unavailable` (`dispatched: no`, nothing was tapped); one whose dismiss key was tapped and left the keyboard visible keeps `UNSUPPORTED_OPERATION` with no `reason` and `dispatched: unknown`. A `keyboard enter` that found no return key and no field to submit through keeps `UNSUPPORTED_OPERATION` and reports `keyboard_return_unavailable` (`dispatched: unknown`, because typing the return can fail after XCTest sent it); a sole text field that was found and tapped but would not take the return keeps `UNSUPPORTED_OPERATION` with no `reason`. A press the runner answers that its target cannot perform — today the Action Button on an iPhone or iPad model that has none, since the simulator volume and non-tvOS remote cases are refused before the runner is reached — keeps `UNSUPPORTED_OPERATION` and reports `hardware_control_unavailable` (`dispatched: no`, nothing was pressed). macOS `back` finding no in-app back control reports `in_app_back_control_unavailable` under `COMMAND_FAILED` (`dispatched: no`). See Back above. +- iOS runner refusals carry `error.details.reason`: `runner_busy` means the runner ran nothing (`dispatched: no`); a read-only command resends it until shortly before its own timeout, and `details.attempts` counts the sends. A read inside an action, such as the viewport read before a swipe, sends it at most 8 times in total, as `details.attempts` reports, because the action needs the rest of its timeout. When that window closes first, the command still fails with `runner_busy` (`dispatched: no`), so retry the read; `runner_main_thread_timeout` means the action may still land (`dispatched: unknown`); `no_text_input_at_point` and `text_input_probe_unavailable` mean a `fill` refused before dispatching anything (`dispatched: no`) — see Text entry below. A synthesized long press, `scroll`, `swipe` (sent as a planned fling `gesture`), or other planned `gesture` that the event synthesis refuses before its event record is handed to XCTest reports `COMMAND_FAILED` with `synthesized_gesture_not_dispatched` (`dispatched: no`), and so does a planned `gesture` refused while its window or display is resolved (the window cannot be named, or the sole display cannot be measured); one that fails after the record was handed to XCTest (its events may or may not have run) reports `synthesized_gesture_outcome_unknown` (`dispatched: unknown`) and is never repeated through an XCTest fallback, so check the screen with `snapshot` before you retry. Any other refusal, such as a platform without touch input, keeps `UNSUPPORTED_OPERATION`. A long-press step in a press series reports the same reasons; once an earlier step has run, the series is `dispatched: unknown`. `back_swipe_no_change` means the iOS `back` swipe was sent and the screen did not change, and `back_swipe_unverified` means it was sent but may or may not have navigated (both `dispatched: unknown`); `back_swipe_not_dispatched` means it was refused before any touch went down (`dispatched: no`). On the native iOS runner, a visible keyboard makes `keyboard dismiss` return `keyboard_dismiss_unavailable` with `dispatched: no`. An unreadable keyboard state returns `OBSERVATION_UNAVAILABLE`. If `keyboard enter` returns `keyboard_return_unavailable`, check the screen before retrying because Return may have reached the app. A press the runner answers that its target cannot perform — today the Action Button on an iPhone or iPad model that has none, since the simulator volume and non-tvOS remote cases are refused before the runner is reached — keeps `UNSUPPORTED_OPERATION` and reports `hardware_control_unavailable` (`dispatched: no`, nothing was pressed). macOS `back` finding no in-app back control reports `in_app_back_control_unavailable` under `COMMAND_FAILED` (`dispatched: no`). See Back above. - On the Apple XCUITest runner, an alert search that fails, runs out of time, or finds an app alert, Safari dialog, or dismiss-popup window with no actionable controls fails with `error.code: ALERT_UNRESOLVED` and `details.dispatched: no`. `alert get` reports it at once. `accept`, `dismiss`, and `alert wait` retry it within their windows, like absence, and report it, not a timeout, when the last check remained unresolved. Inspect the prompt with `screenshot`, then `snapshot -i`, and `press @ref` on the visible button. - On the Apple XCUITest runner, `alert get` describes a readable alert even when all its buttons are disabled, and lists those disabled buttons. `alert accept` and `alert dismiss` fail with `ALERT_BUTTON_NOT_FOUND`. - If a sheet or permission prompt is visible but `alert` reports none, `alert` did not recognize it. Run `snapshot -i -s ""`, then `press @ref` on the visible button. Android alert support is snapshot-derived, and not every iOS simulator permission surface is a native alert. @@ -543,7 +543,7 @@ A comma-separated ref plan — `press @e13,@e14` or the same form on `click` — Text-entry errors and what to do: -- `TEXT_INPUT_NOT_FOCUSED` (`type`, iOS `fill`): focus a visible text input and retry. If accessibility does not expose the input, focus it by coordinates. An iOS `fill` whose point lies on more than one input, as on a sheet or popover over a form, taps that point and waits for keyboard focus. It clears and types only into the input there that took keyboard focus from that tap. When none took it, an input there that already had focus is used only if it still has focus and is the only uncovered input there; otherwise the fill returns this code and types nothing. If the input you want already has focus, move focus off it, for example with `keyboard dismiss`, then retry. +- `TEXT_INPUT_NOT_FOCUSED` (`type`, iOS `fill`): focus a visible text input and retry. If accessibility does not expose the input, focus it by coordinates. An iOS `fill` whose point lies on more than one input, as on a sheet or popover over a form, taps that point and waits for keyboard focus. It clears and types only into the input there that took keyboard focus from that tap. When none took it, an input there that already had focus is used only if it still has focus and is the only uncovered input there; otherwise the fill returns this code and types nothing. If the input you want already has focus, end editing using a visible control, then retry. - `NO_TEXT_INPUT_AT_POINT` (iOS `fill` under a degraded XCTest channel — coordinate, ref, selector, and replay fills all aim at a point): the runner identified no text input under that point and refused before dispatching anything (`error.details.reason` is `no_text_input_at_point`, `dispatched: no`), so no field changed. A ref or selector fill aims at the centre of the rect it resolved to, so an outer container or a non-input node can land outside the real field: run `snapshot -i`, pick the input node itself, and aim inside its rect. - `TEXT_INPUT_PROBE_UNAVAILABLE` (iOS `fill` under a degraded XCTest channel — coordinate, ref, selector, and replay fills all aim at a point): the runner's input lookup could not answer, so it refused before dispatching anything (`error.details.reason` is `text_input_probe_unavailable`, `dispatched: no`). This does not mean the point has no input. Retry the fill, or run `snapshot -i` once its capture reads back. A ref or selector fill aims at the centre of its resolved rect. - `TEXT_INPUT_SYNTHESIS_UNAVAILABLE` (iOS `type "\n"` with the software keyboard hidden): show the software keyboard, then retry. @@ -572,6 +572,7 @@ agent-device wait 'id="field-phone" value="00 062 91 77"' - `gesture pinch [x] [y]`, `gesture rotate [x] [y]` (the sign sets direction), `gesture transform x y dx dy scale degrees [durationMs]`, and two-finger `gesture pan` work in Android, iOS, and iPadOS app sessions, on simulators and physical devices. On Apple they use the XCTest runner, so iOS sessions reached through a WebDriver provider refuse them. One-finger `gesture pan` works wherever coordinate drags do. A path that does not fit the viewport fails before injection instead of being clamped. Use `orientation` to rotate the device. - `gesture tap x1 y1 x2 y2 [... x5 y5]` touches 2 to 5 distinct points and holds them for `--hold-ms` (default 50ms, at least 16ms) before lifting. `--count` repeats the same contacts up to 200 times with `--pause-ms` between repetitions; the series must fit in 60000ms, counting about 500ms of overhead per repetition. It works in Android and iOS/iPadOS app sessions; WebDriver providers refuse it unless they declare `tapGesture` support. On iOS the contacts touch down and lift together; on Android they touch down up to 8ms apart and lift 8ms apart in reverse order. Three or more fingers can trigger iOS system gestures such as undo, so verify app state afterwards. Use `press` for one finger. - Cancelled `gesture` and `swipe` requests return `COMMAND_FAILED` with `details.reason=request_canceled` and record no action. Repetition pauses are interruptible. +- On the native iOS runner, one-finger `gesture pan` can cross into the area covered by the keyboard. Use it for an intentional drag where the app supports interactive keyboard dismissal. - App recognizers may not report exactly the requested pan, scale, and rotation. Verify app-level state such as `pan changed yes`, and prefer separate `gesture pan`, `gesture pinch`, or `gesture rotate` commands when exact values matter. See `agent-device help gestures`. ### Scroll @@ -580,7 +581,7 @@ agent-device wait 'id="field-phone" value="00 062 91 77"' - `scroll --until ` repeats passes until the selector is on screen. A vertical search fails with `COMMAND_FAILED` and `reason: scroll_until_no_progress` if repeated captures show no progress in the selected scroll container. If content moved before stopping, the reason is `scroll_until_edge_reached`. If no container is found, it compares the visible tree. It stops after at most 12 gestures by default. For a longer list, use `scroll down --until 'id="row-512"' --max-passes 90` (1–200 gestures). The pass limit does not extend the 90-second request timeout. Large pass budgets can hit that timeout; inspect the current screen and continue with another search if that happens. Add an amount (`scroll down 0.8 --until `) to widen each pass. Use it in `.ad` scripts too, instead of fixed amounts that depend on screen size; see [Replay and E2E testing](/docs/replay-e2e). - Default snapshot text summarizes off-screen interactive content instead of listing refs. `scroll --settle` (and `back --settle`) waits for the UI to go quiet and returns the diff with fresh refs, so you don't need another `snapshot -i`. Settle is best-effort and never fails the action. - On Android, settle ignores an allowlist of system-bar containers and shade/keyguard status headers; other SystemUI overlays remain content. Appium settle also applies package rules for keyboard and system chrome. -- With a keyboard up on iOS or Android, the swipe stays above the keyboard (reported as `keyboardAvoided` and `keyboardMinY`) and the keyboard stays open. If too little room is left, the command refuses with `scroll_keyboard_occludes_surface`; run `keyboard dismiss` first. +- With a keyboard up on iOS or Android, the swipe stays above the keyboard (reported as `keyboardAvoided` and `keyboardMinY`) and the keyboard stays open. If too little room is left, the command refuses with `scroll_keyboard_occludes_surface`; end editing first. On Android, use `keyboard dismiss`. On iOS, use a visible dismissal control. - A directional scroll reports what it observed as `movement`: `moved`, `at-edge` (no change and no more content that way), `unchanged` (no change, no edge signal), or `unobserved` (no reliable comparison). If nothing changed, the swipe ran inside a container, and that container still has hidden content in that direction, it refuses with `scroll_no_progress`; the hint names the usual causes: a focused keyboard, a nested scroller, or a list that needs a raw `swipe`. See `agent-device help scroll`. - `--no-post-gesture-stabilization` is for a caller that verifies the screen by polling it, for example a test runner that re-reads the tree every 100ms. It skips the two checks that follow a gesture: the `movement` check above (`scroll ` only), and the wait that makes the first read after the gesture agree across two captures (see [Assertions](#assertions)). The scroll returns right after its gesture with no `movement` field and no `scroll_no_progress` refusal, and the next read is a plain capture without `postGestureOutcome`. Without your own polling, that read can return a tree the gesture is still moving. `swipe` and `gesture swipe` accept it too; other gestures never stabilize, so the CLI refuses the flag on them and the other routes ignore it. None of the checks run on web and desktop targets. With `--settle`, the settle observation already reports the outcome, so the option only removes the wait before settle's first capture. The per-pass checks of `scroll top`, `scroll bottom`, and `scroll --until` stay. - The opt-out belongs to the caller. Pass `--no-post-gesture-stabilization` on the command, or `postGestureStabilization: false` in the Node client or a batch step. `open` accepts it too: when the open launches an app, it skips the first-screen wait and drops any wait an earlier scroll or swipe left pending (see [Navigation](#navigation)). To apply it to every `scroll`, `swipe`, `gesture swipe`, and `open` command, set `postGestureStabilization` to `false` in your user config, or set `AGENT_DEVICE_POST_GESTURE_STABILIZATION=0`. `./agent-device.json` rejects the key, so a repository cannot turn the check off for whoever runs it, and a recorded `.ad` script does not carry it, so a replay keeps the wait. MCP and AI SDK tools do not offer it; an operator sets the variable or the user config key for the process that serves them. @@ -942,10 +943,9 @@ agent-device keyboard dismiss 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` (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`). +- `keyboard status` (alias `keyboard get`) reports whether the software keyboard is visible. When it can identify a visible Return control, it reports its action as `returnKey` and can include its localized accessibility label as `returnKeyLabel`. A visible keyboard whose Return action cannot be identified reports `unknown`. The native iOS runner uses a recognized Return key accessibility identifier, such as `Search`, to report the action and label. A label alone leaves the action unknown and the label field absent. Only Android can report `none`. The native iOS runner returns `OBSERVATION_UNAVAILABLE` when it cannot establish visibility. +- `keyboard enter` (alias `keyboard return`) sends Return to the focused input. Focus the intended field first. The app can submit, advance focus, or insert a newline. This can work with the software keyboard hidden. +- `keyboard dismiss` dismisses the keyboard on Android. On the native iOS runner it succeeds as a no-op when the software keyboard is hidden. With a visible keyboard it returns `keyboard_dismiss_unavailable` with `dispatched: no`. Press the visible Hide Keyboard key or the app control that ends editing. If the app supports interactive dismissal, use `gesture pan x y 0 dy durationMs` with a positive `dy` to drag down. Choose a start point inside the scrollable content from a fresh screenshot and check the result with `keyboard status`. Appium uses its own dismissal behavior. ## Performance diagnostics diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index b85076275a..e82e224193 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -66,6 +66,8 @@ Each `open ` exports with an explicit `launchApp.appId`, so a flow can sw Deep links, including schemes without `//` such as `tel:` and `mailto:`, export as `openLink`. A standalone `open tel:+15551234567` emits only the link command; `open com.example.app mailto:agent@example.test` emits the app launch followed by the link. +On the native iOS runner, use `tapOn` on a visible dismissal control. If the app supports drag dismissal, use a `swipe` that stays above the keyboard. + Export is strict. It writes Maestro YAML for compatible flow actions such as app launch, taps, long press, text input, keyboard dismiss/enter, back, home, text visibility assertions, coordinate swipes, basic scroll, screenshots, and `.ad` `env` directives. `home` exports as `pressKey: Home`, so flows that visit the home screen and reopen the app can be exported. Agent-only inspection or maintenance actions such as `snapshot`, `get`, `record`, `trace`, `settings`, and unsupported selector shapes fail with the source line and action instead of being silently dropped. Known semantic differences are reported as warnings; for example, `.ad` `fill` exports as `tapOn` plus `inputText`, which may append text in Maestro rather than replacing existing field contents. Native `.ad` `label=` selectors export as Maestro `text:` selectors and warn because Maestro text matching is broader than label-only matching. A strict `wait absent` is reported as unsupported rather than mapped to Maestro's more lenient `notVisible` condition. ## Troubleshooting