From 03de91e526372f56f39fef5792ca2590fcdb68a6 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 01:48:55 +0530 Subject: [PATCH 01/10] feat(lock-screen): lock and unlock the screen on Android and iOS simulators Add `agent-device lock-screen ` and `client.command.lockScreen({ action })`. The action selects one of two new system-button cells, lockScreen or unlockScreen, the way hardware-button selects a key, and the result reports the lock state the owner read back: `{ action: 'lock-screen', state, message }`. Android locks with KEYCODE_SLEEP and unlocks with KEYCODE_WAKEUP then `wm dismiss-keyguard`, each verified by the keyguard state `dumpsys window` reports. A keyguard whose foreground user has a PIN, pattern, or password is refused before anything is sent, with `lock-screen-secure`. The keyguard read moves to keyguard.ts, shared with fold. The iOS runner locks with XCUIDevice's pressLockButton, checked with responds(to:), and unlocks with a swipe up from the bottom edge, after the same button wakes a dark screen; a swipe on a dark screen unlocks SpringBoard but leaves the screen off. Success needs SpringBoard's lock state, and for a lock also the lock screen date view or cover sheet window. The verification window starts after the dispatch returns and every wait is followed by a read. Unlock also needs com.apple.springboard.hasBlankedScreen to report the screen on. A passcode prompt is refused with `lock-screen-secure`. A screen already in the requested state is left alone. Neither command activates the session app or settles. Physical iPhones and iPads, Android TV, tvOS, macOS, and web refuse with UNSUPPORTED_OPERATION. --- ...AgentDeviceRunnerUITests-Bridging-Header.h | 2 + .../RunnerErrorCodes.swift | 2 + .../RunnerSurfacePolicy.swift | 5 +- .../RunnerTests+CommandExecution.swift | 2 + .../RunnerTests+LockScreen.swift | 243 ++++++++++++++++++ .../RunnerTests+Models.swift | 6 +- .../RunnerTests+LockScreenTests.swift | 172 +++++++++++++ .../UnitTests/RunnerTests+ModelsTests.swift | 11 +- apple/runner/RUNNER_PROTOCOL.md | 12 + .../fixtures/runner-command-read-only.json | 12 + contracts/fixtures/runner-requests.json | 2 + contracts/fixtures/runner-surface-policy.json | 2 + .../__tests__/runner-command-traits.test.ts | 2 + .../runner-error-classification.test.ts | 22 ++ .../apple-runner/src/runner-command-traits.ts | 4 + .../apple-runner/src/runner-command-types.ts | 3 + packages/apple-runner/src/runner-contract.ts | 16 ++ packages/client/src/index.ts | 2 + .../command-output/src/cli-output.test.ts | 1 + packages/command-output/src/system/output.ts | 1 + .../src/__tests__/command-result.test.ts | 4 + .../command-registry/src/command-result.ts | 2 + .../src/descriptors/device-operations.ts | 15 ++ packages/command-surface/src/client-port.ts | 2 + .../command-surface/src/system/index.test.ts | 22 ++ packages/command-surface/src/system/index.ts | 2 + .../command-surface/src/system/lock-screen.ts | 60 +++++ .../src/system/output-schemas.ts | 9 + packages/contracts/src/client-system.ts | 5 + packages/contracts/src/device-rotation.ts | 40 ++- packages/contracts/src/facades/client.ts | 1 + packages/contracts/src/facades/device.ts | 6 +- ...ctor-operation-catalog-conformance.test.ts | 2 + packages/contracts/src/interactor-types.ts | 12 + packages/contracts/src/navigation.ts | 12 + .../src/platform-runtime-operations.ts | 7 + .../src/platform-runtime-unavailable.ts | 2 + .../contracts/src/runtime-operation-names.ts | 2 + .../src/system-button-runtime.test.ts | 27 +- .../contracts/src/system-button-runtime.ts | 22 +- .../support/runtime-binding-conformance.ts | 23 ++ .../src/core/runtime-operation-effects.ts | 2 + .../__tests__/system-button-runtime.test.ts | 94 ++++++- .../execution/generic-runtime-execution.ts | 2 +- .../src/execution/system-button-runtime.ts | 125 ++++++--- .../platform-android/src/foldable/pose.ts | 52 ++-- packages/platform-android/src/keyguard.ts | 40 +++ .../platform-android/src/lock-screen.test.ts | 190 ++++++++++++++ packages/platform-android/src/lock-screen.ts | 167 ++++++++++++ packages/platform-android/src/mechanics.ts | 18 ++ packages/platform-android/src/runtime.test.ts | 33 +++ packages/platform-android/src/runtime.ts | 15 ++ .../__tests__/index-runner-requests.test.ts | 2 + .../interactor-runner-provider.test.ts | 2 + packages/platform-apple/src/interactor.ts | 14 + .../platform-apple/src/navigation/runtime.ts | 25 +- packages/platform-apple/src/runner-demand.ts | 2 + packages/platform-apple/src/runtime.test.ts | 29 +++ packages/platform-linux/src/runtime.test.ts | 2 + packages/platform-web/src/runtime.test.ts | 2 + .../provider-revyl/src/facts-runtime.test.ts | 2 + .../__tests__/session-event-action.test.ts | 11 + .../src/session-event-action-presentation.ts | 11 + scripts/capability-matrix/annotations.ts | 7 + scripts/perf/README.md | 1 + scripts/perf/suite.ts | 2 + .../runner-read-only-registry-parity.test.ts | 2 + src/commands/replay/replay-script.fixtures.ts | 1 + src/core/interactors/android.ts | 4 + .../command-coverage/declarations.ts | 33 +++ test/integration/command-coverage/evidence.ts | 10 + .../android-lock-screen.test.ts | 151 +++++++++++ .../apple-platform-output-guard.test.ts | 1 + .../ios-lock-screen.test.ts | 59 +++++ 74 files changed, 1815 insertions(+), 95 deletions(-) create mode 100644 apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LockScreen.swift create mode 100644 apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+LockScreenTests.swift create mode 100644 packages/command-surface/src/system/lock-screen.ts create mode 100644 packages/platform-android/src/keyguard.ts create mode 100644 packages/platform-android/src/lock-screen.test.ts create mode 100644 packages/platform-android/src/lock-screen.ts create mode 100644 test/integration/provider-scenarios/android-lock-screen.test.ts create mode 100644 test/integration/provider-scenarios/ios-lock-screen.test.ts diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h index f448d0ae80..1e06133411 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h @@ -1,3 +1,5 @@ +#import + #import "RunnerObjCExceptionCatcher.h" #import "RunnerAXSnapshotBridge.h" #import "RunnerSimulatorEdgeTouch.h" diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerErrorCodes.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerErrorCodes.swift index ea22211b56..62dbfa2550 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerErrorCodes.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerErrorCodes.swift @@ -29,6 +29,8 @@ extension RunnerTests { static let keyboardDismissUnavailable = "KEYBOARD_DISMISS_UNAVAILABLE" static let keyboardReturnUnavailable = "KEYBOARD_RETURN_UNAVAILABLE" static let hardwareControlUnavailable = "HARDWARE_CONTROL_UNAVAILABLE" + static let lockScreenUnverified = "LOCK_SCREEN_UNVERIFIED" + static let lockScreenSecure = "LOCK_SCREEN_SECURE" static let inAppBackControlUnavailable = "IN_APP_BACK_CONTROL_UNAVAILABLE" static let nativeAuditUnavailable = "NATIVE_AUDIT_UNAVAILABLE" static let nativeAuditBlockedByAlert = "NATIVE_AUDIT_BLOCKED_BY_ALERT" diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSurfacePolicy.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSurfacePolicy.swift index 4663b8f28a..c42d0e5e26 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSurfacePolicy.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSurfacePolicy.swift @@ -11,8 +11,9 @@ extension CommandType { var surfacePolicy: RunnerSurfacePolicy { switch self { case .mouseClick, .remotePress, .desktopScroll, .snapshotBridge, .home, .rotate, - .actionButton, .volumeUp, .volumeDown, .keyboardReturn, .recordStop, .status, .uptime, - .appState, .pasteboardWrite, .activate, .terminate, .targetReset, .shutdown: + .actionButton, .volumeUp, .volumeDown, .lockScreen, .unlockScreen, .keyboardReturn, + .recordStop, .status, .uptime, .appState, .pasteboardWrite, .activate, .terminate, + .targetReset, .shutdown: return .none case .tap, .longPress, .drag, .type, .swipe, .scroll, .findText, .querySelector, .readText, .snapshot, .accessibilityAudit, .backInApp, .gesture, .gestureViewport, .appSwitcher, diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift index 69031ac9f6..eb785cabe0 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift @@ -598,6 +598,8 @@ extension RunnerTests { ) } return Response(ok: true, data: DataPayload(message: command.command.rawValue)) + case .lockScreen, .unlockScreen: + return executeLockScreenCommand(command.command) case .keyboardDismiss, .keyboardStatus: var status: RunnerKeyboardStatus? withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .bothSkipped) { diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LockScreen.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LockScreen.swift new file mode 100644 index 0000000000..a0ed609503 --- /dev/null +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LockScreen.swift @@ -0,0 +1,243 @@ +import Darwin +import XCTest + +/// One read of SpringBoard's lock and screen state. +enum LockScreenStateRead: Equatable { + case locked + /// Unlocked with the screen on: the app in front is on screen. + case unlocked + /// Unlocked, but SpringBoard has blanked the screen, so nothing is on screen until it wakes. + case unlockedScreenOff + case unreadable(String) +} + +/// A SpringBoard notify state that could not be read. +struct LockScreenNotifyError: Error { + let message: String + init(_ message: String) { self.message = message } +} + +/// The device-facing steps of one `lockScreen` or `unlockScreen` transition, injected so the +/// verification rules are testable without a lock screen. +struct LockScreenTransitionSteps { + let readState: () -> LockScreenStateRead + /// Sends the lock button press or the unlock swipe; a response is a refusal before dispatch. + let dispatch: () -> Response? + /// Whether a Lock-Screen-specific surface is on screen. Only `lockScreen` reads it. + let lockScreenSurfaceIsVisible: () -> Bool + /// Whether SpringBoard asks for a passcode. Only `unlockScreen` reads it. + let passcodePromptIsVisible: () -> Bool + let shouldContinue: () -> Bool + let wait: () -> Void + /// Restarts the verification window once the dispatch has returned. + let startVerificationWindow: () -> Void +} + +extension RunnerTests { + private static let springboardLockStateNotification = "com.apple.springboard.lockstate" + private static let springboardBlankedScreenNotification = "com.apple.springboard.hasBlankedScreen" + static let lockScreenVerificationTimeout: TimeInterval = 5 + static let lockScreenPollInterval: TimeInterval = 0.05 + + /// Locks with XCUIDevice's lock button, or unlocks with a swipe up from the bottom edge, and + /// answers only once SpringBoard's lock state reports the requested state. A lock also needs a + /// Lock-Screen-specific surface on screen, and an unlock a screen that is on. A screen already + /// in the requested state is left alone, and a passcode prompt is refused rather than answered. + func executeLockScreenCommand(_ type: CommandType) -> Response { +#if os(iOS) && targetEnvironment(simulator) + var deadline = Date().addingTimeInterval(Self.lockScreenVerificationTimeout) + let lock = type == .lockScreen + return executeLockScreenTransition( + lock: lock, + steps: LockScreenTransitionSteps( + readState: currentLockScreenState, + dispatch: lock ? dispatchLockButton : dispatchUnlock, + lockScreenSurfaceIsVisible: lockScreenSurfaceIsVisible, + passcodePromptIsVisible: passcodePromptIsVisible, + shouldContinue: { Date() < deadline }, + wait: { RunLoop.current.run(until: Date().addingTimeInterval(Self.lockScreenPollInterval)) }, + startVerificationWindow: { + deadline = Date().addingTimeInterval(Self.lockScreenVerificationTimeout) + } + ) + ) +#else + return Response(ok: false, error: ErrorPayload( + code: RunnerWireErrorCode.hardwareControlUnavailable, + message: "\(type.rawValue) is supported only on iPhone and iPad simulators", + hint: "lock-screen locks iPhone and iPad simulators and Android phones and tablets." + )) +#endif + } + + /// The transition rules, independent of the device. The verification window starts only after + /// the dispatch returned, and every wait is followed by a read, so a state SpringBoard reached + /// during the last wait is never reported as a failure. + func executeLockScreenTransition(lock: Bool, steps: LockScreenTransitionSteps) -> Response { + let target: LockScreenStateRead = lock ? .locked : .unlocked + switch steps.readState() { + case target: + return lockScreenReachedResponse(lock: lock, steps: steps) + case .unreadable(let message): + return Response(ok: false, error: ErrorPayload( + code: RunnerWireErrorCode.observationUnavailable, + message: message + )) + default: + break + } + if let refusal = steps.dispatch() { return refusal } + steps.startVerificationWindow() + while true { + switch steps.readState() { + case target: + return lockScreenReachedResponse(lock: lock, steps: steps) + case .unreadable(let message): + return lockScreenUnverifiedResponse(message) + case .locked where !lock: + if steps.passcodePromptIsVisible() { return passcodeRefusal() } + default: + break + } + guard steps.shouldContinue() else { break } + steps.wait() + } + return lockScreenUnverifiedResponse( + lock + ? "XCTest pressed the simulator lock button, but SpringBoard still reports the screen unlocked" + : "The unlock swipe was sent, but SpringBoard still reports the screen locked" + ) + } + + /// SpringBoard reports the requested state. An unlock needs nothing more. A lock also needs a + /// Lock-Screen-specific surface, and the lock state must hold while that surface is awaited. + private func lockScreenReachedResponse(lock: Bool, steps: LockScreenTransitionSteps) -> Response { + guard lock else { return Response(ok: true, data: DataPayload(message: "unlockScreen")) } + while true { + switch steps.readState() { + case .locked: + if steps.lockScreenSurfaceIsVisible() { + return Response(ok: true, data: DataPayload(message: "lockScreen")) + } + case .unlocked, .unlockedScreenOff: + return lockScreenUnverifiedResponse( + "SpringBoard reported the screen unlocked again while the lock screen was awaited" + ) + case .unreadable(let message): + return lockScreenUnverifiedResponse(message) + } + guard steps.shouldContinue() else { break } + steps.wait() + } + return lockScreenUnverifiedResponse( + "SpringBoard reports the screen locked, but no lock screen surface is on screen" + ) + } + + private func lockScreenUnverifiedResponse(_ message: String) -> Response { + Response(ok: false, error: ErrorPayload( + code: RunnerWireErrorCode.lockScreenUnverified, + message: message, + hint: "Take a screenshot to see the screen, then retry lock-screen." + )) + } + + private func passcodeRefusal() -> Response { + Response(ok: false, error: ErrorPayload( + code: RunnerWireErrorCode.lockScreenSecure, + message: "The simulator asks for a passcode, which lock-screen unlock does not enter", + hint: "Enter the passcode by hand, or turn it off in Settings > Face ID & Passcode, then retry." + )) + } + +#if os(iOS) && targetEnvironment(simulator) + /// `pressLockButton` is a private XCUIDevice selector, the one WebDriverAgent's lock uses. A + /// runtime without it is refused before anything is sent. + private func dispatchLockButton() -> Response? { + let device = XCUIDevice.shared + let selector = NSSelectorFromString("pressLockButton") + guard device.responds(to: selector) else { + return Response(ok: false, error: ErrorPayload( + code: RunnerWireErrorCode.hardwareControlUnavailable, + message: "This XCTest runtime exposes no simulator lock button", + hint: "lock-screen lock needs the XCUIDevice lock button that Xcode's simulator runtimes provide." + )) + } + device.perform(selector) + return nil + } + + /// Wakes a blanked screen with the lock button, then swipes up from the bottom edge, as a person + /// dismisses the lock screen. A swipe on a blanked screen unlocks SpringBoard but leaves the + /// screen off. The swipe lands on whatever was in front before the lock, unlike a Home press, + /// which lands on the Home Screen. + private func dispatchUnlock() -> Response? { + if screenIsBlanked() { + if let refusal = dispatchLockButton() { return refusal } + let wakeDeadline = Date().addingTimeInterval(Self.lockScreenVerificationTimeout) + while screenIsBlanked() && Date() < wakeDeadline { + RunLoop.current.run(until: Date().addingTimeInterval(Self.lockScreenPollInterval)) + } + } + guard currentLockScreenState() == .locked else { return nil } + let start = springboard.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.99)) + let end = springboard.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.4)) + start.press(forDuration: 0.05, thenDragTo: end, withVelocity: .fast, thenHoldForDuration: 0) + return nil + } + + /// The lock screen's date view, or SpringBoard's cover sheet window. The cover sheet also hosts + /// Notification Center, so it counts only together with the locked state the caller read. + private func lockScreenSurfaceIsVisible() -> Bool { + let dateView = springboard.descendants(matching: .any) + .matching(identifier: "lockscreen-date-view") + .firstMatch + let coverSheet = springboard.windows.matching(identifier: "SBCoverSheetWindow").firstMatch + return (dateView.exists && !dateView.frame.isEmpty) + || (coverSheet.exists && !coverSheet.frame.isEmpty) + } + + /// The numeric keypad or the secure text field SpringBoard shows when the lock needs a passcode. + /// A keypad key's label starts with its digit and may carry its letters after a space. + private func passcodePromptIsVisible() -> Bool { + let keypadKeys = springboard.buttons.matching( + NSPredicate(format: "label MATCHES %@", "^[0-9]( .*)?$") + ) + return keypadKeys.count >= 10 || springboard.secureTextFields.firstMatch.exists + } + + func currentLockScreenState() -> LockScreenStateRead { + switch springboardNotifyState(Self.springboardLockStateNotification) { + case .failure(let error): return .unreadable(error.message) + case .success(let locked) where locked != 0: return .locked + case .success: break + } + switch springboardNotifyState(Self.springboardBlankedScreenNotification) { + case .failure(let error): return .unreadable(error.message) + case .success(let blanked): return blanked != 0 ? .unlockedScreenOff : .unlocked + } + } + + private func screenIsBlanked() -> Bool { + if case .success(let blanked) = springboardNotifyState(Self.springboardBlankedScreenNotification) { + return blanked != 0 + } + return false + } + + private func springboardNotifyState(_ name: String) -> Result { + var token: Int32 = 0 + let registerStatus = notify_register_check(name, &token) + guard registerStatus == NOTIFY_STATUS_OK else { + return .failure(LockScreenNotifyError("Unable to register for \(name) (notify status \(registerStatus))")) + } + defer { notify_cancel(token) } + var state: UInt64 = 0 + let readStatus = notify_get_state(token, &state) + guard readStatus == NOTIFY_STATUS_OK else { + return .failure(LockScreenNotifyError("Unable to read \(name) (notify status \(readStatus))")) + } + return .success(state) + } +#endif +} diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift index 2e25226ab0..e41025bb45 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift @@ -25,6 +25,8 @@ enum CommandType: String, Codable, CaseIterable { case actionButton case volumeUp case volumeDown + case lockScreen + case unlockScreen case keyboardDismiss case keyboardReturn case keyboardStatus @@ -333,7 +335,9 @@ extension Command { case .pasteboardWrite: return .deviceState - case .actionButton, .volumeUp, .volumeDown: + // The lock screen belongs to the system: activating the session app first would dismiss the + // lock screen `lockScreen` shows, or bring forward the app `unlockScreen` must leave in place. + case .actionButton, .volumeUp, .volumeDown, .lockScreen, .unlockScreen: return .presentedSurfaceMutation case .querySelector: diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+LockScreenTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+LockScreenTests.swift new file mode 100644 index 0000000000..e9b458d976 --- /dev/null +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+LockScreenTests.swift @@ -0,0 +1,172 @@ +import XCTest + +#if AGENT_DEVICE_RUNNER_UNIT_TESTS +/// Scripted device steps for one lock-screen transition: successive state reads (the last one +/// repeats), a deadline that allows `waitsAllowed` waits, and a log of what ran in which order. +private final class LockScreenScript { + var reads: [LockScreenStateRead] + var surfaceReads: [Bool] + var passcodePrompt = false + var waitsAllowed: Int + var dispatchRefusal: Response? + private(set) var log: [String] = [] + + init(reads: [LockScreenStateRead], surfaceReads: [Bool] = [true], waitsAllowed: Int = 0) { + self.reads = reads + self.surfaceReads = surfaceReads + self.waitsAllowed = waitsAllowed + } + + var dispatches: Int { log.filter { $0 == "dispatch" }.count } + var waits: Int { log.filter { $0 == "wait" }.count } + + var steps: LockScreenTransitionSteps { + LockScreenTransitionSteps( + readState: { + self.log.append("read") + return self.reads.count > 1 ? self.reads.removeFirst() : self.reads[0] + }, + dispatch: { + self.log.append("dispatch") + return self.dispatchRefusal + }, + lockScreenSurfaceIsVisible: { + self.log.append("surface") + return self.surfaceReads.count > 1 ? self.surfaceReads.removeFirst() : self.surfaceReads[0] + }, + passcodePromptIsVisible: { + self.log.append("passcode") + return self.passcodePrompt + }, + shouldContinue: { self.waits < self.waitsAllowed }, + wait: { self.log.append("wait") }, + startVerificationWindow: { self.log.append("window") } + ) + } +} + +extension RunnerTests { + func testLockScreenLeavesAnAlreadyLockedScreenAlone() { + let script = LockScreenScript(reads: [.locked]) + let response = executeLockScreenTransition(lock: true, steps: script.steps) + XCTAssertTrue(response.ok) + XCTAssertEqual(script.dispatches, 0) + } + + func testUnlockScreenLeavesAnAlreadyUnlockedScreenAlone() { + let script = LockScreenScript(reads: [.unlocked]) + let response = executeLockScreenTransition(lock: false, steps: script.steps) + XCTAssertTrue(response.ok) + XCTAssertEqual(script.dispatches, 0) + } + + /// The window opens only once the dispatch returned, and a dispatch that used up the whole window + /// is still followed by a read rather than a timeout. + func testLockScreenReadsAfterADispatchThatOutlastedTheWindow() { + let script = LockScreenScript(reads: [.unlocked, .locked], waitsAllowed: 0) + let response = executeLockScreenTransition(lock: true, steps: script.steps) + XCTAssertTrue(response.ok, response.error?.message ?? "") + XCTAssertEqual(Array(script.log.prefix(4)), ["read", "dispatch", "window", "read"]) + } + + func testLockScreenReadsAgainAfterTheLastWait() { + let script = LockScreenScript(reads: [.unlocked, .unlocked, .locked], waitsAllowed: 1) + let response = executeLockScreenTransition(lock: true, steps: script.steps) + XCTAssertTrue(response.ok, response.error?.message ?? "") + XCTAssertEqual(script.waits, 1) + } + + func testUnlockScreenReportsUnverifiedWhenTheScreenStaysLocked() { + let script = LockScreenScript(reads: [.locked], waitsAllowed: 2) + let response = executeLockScreenTransition(lock: false, steps: script.steps) + XCTAssertFalse(response.ok) + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.lockScreenUnverified) + XCTAssertEqual(script.dispatches, 1) + XCTAssertEqual(script.waits, 2) + XCTAssertEqual(script.log.last, "passcode", "the last wait is followed by a read") + } + + func testUnlockScreenRefusesAPasscodePromptWithoutWaitingOutTheWindow() { + let script = LockScreenScript(reads: [.locked], waitsAllowed: 5) + script.passcodePrompt = true + let response = executeLockScreenTransition(lock: false, steps: script.steps) + XCTAssertFalse(response.ok) + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.lockScreenSecure) + XCTAssertEqual(script.waits, 0) + } + + /// A screen SpringBoard reports unlocked but blanked shows nothing, so unlock still dispatches. + func testUnlockScreenWakesAnUnlockedScreenThatIsOff() { + let script = LockScreenScript(reads: [.unlockedScreenOff, .unlocked]) + let response = executeLockScreenTransition(lock: false, steps: script.steps) + XCTAssertTrue(response.ok, response.error?.message ?? "") + XCTAssertEqual(script.dispatches, 1) + } + + func testUnlockScreenRefusesAScreenThatStaysOff() { + let script = LockScreenScript(reads: [.locked, .unlockedScreenOff], waitsAllowed: 2) + script.passcodePrompt = true + let response = executeLockScreenTransition(lock: false, steps: script.steps) + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.lockScreenUnverified) + XCTAssertEqual(script.log.filter { $0 == "passcode" }.count, 0, "an unlocked screen asks for no passcode") + } + + func testLockScreenNeverAsksForAPasscodePrompt() { + let script = LockScreenScript(reads: [.unlocked], waitsAllowed: 1) + script.passcodePrompt = true + let response = executeLockScreenTransition(lock: true, steps: script.steps) + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.lockScreenUnverified) + XCTAssertFalse(script.log.contains("passcode")) + } + + func testLockScreenPropagatesADispatchRefusalWithoutPolling() { + let script = LockScreenScript(reads: [.unlocked], waitsAllowed: 5) + script.dispatchRefusal = Response(ok: false, error: ErrorPayload( + code: RunnerWireErrorCode.hardwareControlUnavailable, + message: "no lock button" + )) + let response = executeLockScreenTransition(lock: true, steps: script.steps) + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.hardwareControlUnavailable) + XCTAssertEqual(script.log, ["read", "dispatch"]) + } + + func testLockScreenRefusesAnUnreadableStateBeforeDispatch() { + let script = LockScreenScript(reads: [.unreadable("notify failed")]) + let response = executeLockScreenTransition(lock: true, steps: script.steps) + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.observationUnavailable) + XCTAssertEqual(script.dispatches, 0) + } + + func testLockScreenReportsAnUnreadableStateAfterDispatchAsUnverified() { + let script = LockScreenScript(reads: [.unlocked, .unreadable("notify failed")], waitsAllowed: 5) + let response = executeLockScreenTransition(lock: true, steps: script.steps) + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.lockScreenUnverified) + XCTAssertEqual(script.dispatches, 1) + } + + func testLockScreenWaitsForTheLockScreenSurface() { + let script = LockScreenScript(reads: [.unlocked, .locked], surfaceReads: [false, true], waitsAllowed: 1) + let response = executeLockScreenTransition(lock: true, steps: script.steps) + XCTAssertTrue(response.ok, response.error?.message ?? "") + XCTAssertEqual(script.waits, 1) + } + + func testLockScreenRefusesALockStateWithNoLockScreenSurface() { + let script = LockScreenScript(reads: [.locked], surfaceReads: [false], waitsAllowed: 2) + let response = executeLockScreenTransition(lock: true, steps: script.steps) + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.lockScreenUnverified) + XCTAssertEqual(script.dispatches, 0) + } + + func testLockScreenRefusesAScreenThatUnlocksWhileTheSurfaceIsAwaited() { + let script = LockScreenScript( + reads: [.unlocked, .locked, .locked, .unlocked], + surfaceReads: [false], + waitsAllowed: 5 + ) + let response = executeLockScreenTransition(lock: true, steps: script.steps) + XCTAssertEqual(response.error?.code, RunnerWireErrorCode.lockScreenUnverified) + XCTAssertEqual(script.waits, 1) + } +} +#endif diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+ModelsTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+ModelsTests.swift index aaf4b3b3a5..12f24ac119 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+ModelsTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+ModelsTests.swift @@ -248,9 +248,10 @@ extension RunnerTests { /// Commands that did not exist at the merge-base, so no classification of its is compared with /// theirs. `appState` arrived with #2929, `pasteboardWrite` with the runner-written simulator /// clipboard, `snapshotBridge` with the runner-served Simulator AX bridge, `keyboardStatus` with - /// the return key in `keyboard status`. + /// the return key in `keyboard status`, `lockScreen` and `unlockScreen` with `lock-screen`. private static let commandsNewerThanTheMergeBase: Set = [ .appState, .pasteboardWrite, .volumeUp, .volumeDown, .snapshotBridge, .keyboardStatus, .accessibilityAudit, + .lockScreen, .unlockScreen, ] /// The commands production never runs through the prepared path's body: `executeOnMain` answers @@ -339,6 +340,14 @@ extension RunnerTests { .volumeDown, expectation(interaction: false, retry: false, launch: .presentedSurface, converts: true, retains: true, isReadOnly: false) ), + ( + .lockScreen, + expectation(interaction: false, retry: false, launch: .presentedSurface, converts: true, retains: true, isReadOnly: false) + ), + ( + .unlockScreen, + expectation(interaction: false, retry: false, launch: .presentedSurface, converts: true, retains: true, isReadOnly: false) + ), (.keyboardDismiss, expectation(interaction: true, retry: false, launch: .mayLaunch, converts: true, retains: true, isReadOnly: false)), (.keyboardReturn, expectation(interaction: true, retry: false, launch: .mayLaunch, converts: true, retains: true, isReadOnly: false)), ( diff --git a/apple/runner/RUNNER_PROTOCOL.md b/apple/runner/RUNNER_PROTOCOL.md index 93c705c544..703ffccf10 100644 --- a/apple/runner/RUNNER_PROTOCOL.md +++ b/apple/runner/RUNNER_PROTOCOL.md @@ -321,6 +321,18 @@ last two press nothing. The host maps each to the code its command already refus (the first two to `UNSUPPORTED_OPERATION`, the macOS back refusal to the `COMMAND_FAILED` a code-less reply produced) and publishes its `details.reason`. +`lockScreen` and `unlockScreen` answer only once SpringBoard's `com.apple.springboard.lockstate` +reports the requested state; a lock also waits for the lock screen's date view or cover sheet +window, and an unlock for `com.apple.springboard.hasBlankedScreen` to report the screen on. A swipe +on a dark screen unlocks SpringBoard but leaves the screen off, so `unlockScreen` wakes a dark +screen with the lock button before it swipes. The verification window starts after the lock button press or the unlock swipe returns, +and the runner reads the state once more after its last wait. `LOCK_SCREEN_UNVERIFIED` means the +state did not change in time, and `LOCK_SCREEN_SECURE` means the unlock swipe raised a passcode +prompt, which the runner leaves unanswered. Either can follow a dispatch, so the host reports +`details.dispatched: "unknown"` with `details.reason` `lock-screen-unverified` or +`lock-screen-secure`. A runtime without XCUIDevice's lock button answers +`HARDWARE_CONTROL_UNAVAILABLE` before pressing anything. + `data` is command-specific. Common fields include snapshot nodes, text lookup results, gesture timing, visibility metadata, and screenshot or recording output details. Capture-plan snapshots carry `snapshotViewport`, the acquisition's declared viewport evidence. diff --git a/contracts/fixtures/runner-command-read-only.json b/contracts/fixtures/runner-command-read-only.json index cf7124dfec..10e183fdc8 100644 --- a/contracts/fixtures/runner-command-read-only.json +++ b/contracts/fixtures/runner-command-read-only.json @@ -89,6 +89,12 @@ }, "readOnly": true }, + { + "command": { + "command": "lockScreen" + }, + "readOnly": false + }, { "command": { "command": "longPress" @@ -203,6 +209,12 @@ }, "readOnly": false }, + { + "command": { + "command": "unlockScreen" + }, + "readOnly": false + }, { "command": { "command": "volumeDown" diff --git a/contracts/fixtures/runner-requests.json b/contracts/fixtures/runner-requests.json index c94294fb32..703af4791f 100644 --- a/contracts/fixtures/runner-requests.json +++ b/contracts/fixtures/runner-requests.json @@ -51,10 +51,12 @@ {"name": "ios-simulator.interactor-keyboard-dismiss.dismiss", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "keyboardDismiss", "appBundleId": "com.example.app", "commandId": ""}}, {"name": "ios-simulator.interactor-keyboard-enter.return", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "keyboardReturn", "appBundleId": "com.example.app", "commandId": ""}}, {"name": "ios-simulator.interactor-keyboard-status.read", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "keyboardStatus", "appBundleId": "com.example.app", "commandId": ""}}, + {"name": "ios-simulator.interactor-lock-screen.lock", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "lockScreen", "appBundleId": "com.example.app", "commandId": ""}}, {"name": "ios-simulator.interactor-read-text.point", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "readText", "x": 10, "y": 20, "appBundleId": "com.example.app", "commandId": ""}}, {"name": "ios-simulator.interactor-set-orientation.rotate", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "rotate", "orientation": "landscape-left", "appBundleId": "com.example.app", "commandId": ""}}, {"name": "ios-simulator.interactor-snapshot.every-option", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "snapshot", "appBundleId": "com.example.app", "interactiveOnly": true, "preferredBackend": "tree", "customActions": true, "depth": 3, "scope": "Go", "raw": true, "commandId": ""}}, {"name": "ios-simulator.interactor-snapshot.observe-only", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "snapshot", "appBundleId": "com.example.app", "observeOnly": true, "commandId": ""}}, + {"name": "ios-simulator.interactor-unlock-screen.unlock", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "unlockScreen", "appBundleId": "com.example.app", "commandId": ""}}, {"name": "ios-simulator.interactor-volume-down.press", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "volumeDown", "appBundleId": "com.example.app", "commandId": ""}}, {"name": "ios-simulator.interactor-volume-up.press", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "volumeUp", "appBundleId": "com.example.app", "commandId": ""}}, {"name": "ios-simulator.interactor-write-clipboard.text", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "pasteboardWrite", "text": "one-time code 246810", "commandId": ""}}, diff --git a/contracts/fixtures/runner-surface-policy.json b/contracts/fixtures/runner-surface-policy.json index 05e892e459..fee9d466a7 100644 --- a/contracts/fixtures/runner-surface-policy.json +++ b/contracts/fixtures/runner-surface-policy.json @@ -23,6 +23,8 @@ "actionButton": "none", "volumeUp": "none", "volumeDown": "none", + "lockScreen": "none", + "unlockScreen": "none", "keyboardDismiss": "app-windows", "keyboardReturn": "none", "keyboardStatus": "app-windows", diff --git a/packages/apple-runner/src/__tests__/runner-command-traits.test.ts b/packages/apple-runner/src/__tests__/runner-command-traits.test.ts index 4d89646d90..95683f80bd 100644 --- a/packages/apple-runner/src/__tests__/runner-command-traits.test.ts +++ b/packages/apple-runner/src/__tests__/runner-command-traits.test.ts @@ -71,6 +71,7 @@ test('runner command trait table pins lifecycle-sensitive command groups', () => 'home', 'keyboardDismiss', 'keyboardReturn', + 'lockScreen', 'mouseClick', 'pasteboardWrite', 'recordStart', @@ -79,6 +80,7 @@ test('runner command trait table pins lifecycle-sensitive command groups', () => 'rotate', 'shutdown', 'type', + 'unlockScreen', 'volumeDown', 'volumeUp', ], diff --git a/packages/apple-runner/src/__tests__/runner-error-classification.test.ts b/packages/apple-runner/src/__tests__/runner-error-classification.test.ts index d9d4ddf313..f5cce8ccbd 100644 --- a/packages/apple-runner/src/__tests__/runner-error-classification.test.ts +++ b/packages/apple-runner/src/__tests__/runner-error-classification.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; +import { LOCK_SCREEN_REASONS } from '@agent-device/contracts/device'; import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; import { COMMAND_ALREADY_FINISHED_RUNNER_CODE, @@ -216,6 +217,27 @@ test('the hardware-control refusal keeps UNSUPPORTED_OPERATION and says nothing assert.equal(untyped.details?.reason, undefined); }); +// The two lock-screen outcomes the runner reports after its dispatch publish the reasons the +// Android owner raises for the same outcomes, so a caller branches on one vocabulary. +test('the lock-screen runner outcomes publish the shared lock-screen reasons', () => { + assert.deepEqual(classifyRunnerReportedError('LOCK_SCREEN_UNVERIFIED'), { + code: 'COMMAND_FAILED', + details: { + runnerErrorCode: 'LOCK_SCREEN_UNVERIFIED', + reason: LOCK_SCREEN_REASONS.stateUnverified.reason, + dispatched: 'unknown', + }, + }); + assert.deepEqual(classifyRunnerReportedError('LOCK_SCREEN_SECURE'), { + code: 'UNSUPPORTED_OPERATION', + details: { + runnerErrorCode: 'LOCK_SCREEN_SECURE', + reason: LOCK_SCREEN_REASONS.secureLock.reason, + dispatched: 'unknown', + }, + }); +}); + test('the keyboard-return refusal keeps UNSUPPORTED_OPERATION and reports an unknown dispatch', () => { const refusal = classifyRunnerReportedError('KEYBOARD_RETURN_UNAVAILABLE'); assert.equal(refusal.code, 'UNSUPPORTED_OPERATION'); diff --git a/packages/apple-runner/src/runner-command-traits.ts b/packages/apple-runner/src/runner-command-traits.ts index f31ea78da5..e37614bb83 100644 --- a/packages/apple-runner/src/runner-command-traits.ts +++ b/packages/apple-runner/src/runner-command-traits.ts @@ -92,6 +92,8 @@ export const RUNNER_COMMAND_TRAITS = { actionButton: DEFAULT_TRAITS, volumeUp: DEFAULT_TRAITS, volumeDown: DEFAULT_TRAITS, + lockScreen: DEFAULT_TRAITS, + unlockScreen: DEFAULT_TRAITS, keyboardDismiss: DEFAULT_TRAITS, keyboardReturn: DEFAULT_TRAITS, keyboardStatus: READ_ONLY_TRAITS, @@ -137,6 +139,8 @@ const RUNNER_COMMAND_SURFACE_POLICY = { actionButton: 'none', volumeUp: 'none', volumeDown: 'none', + lockScreen: 'none', + unlockScreen: 'none', keyboardDismiss: 'app-windows', keyboardReturn: 'none', keyboardStatus: 'app-windows', diff --git a/packages/apple-runner/src/runner-command-types.ts b/packages/apple-runner/src/runner-command-types.ts index fe2b3578d4..0fda811aa3 100644 --- a/packages/apple-runner/src/runner-command-types.ts +++ b/packages/apple-runner/src/runner-command-types.ts @@ -43,6 +43,9 @@ export type RunnerCommand = { | 'actionButton' | 'volumeUp' | 'volumeDown' + // Shows or dismisses the lock screen, and answers only once SpringBoard reports that state. + | 'lockScreen' + | 'unlockScreen' | 'keyboardDismiss' | 'keyboardReturn' // Reads the software keyboard and the focused field's return key. A read: it reports what is on diff --git a/packages/apple-runner/src/runner-contract.ts b/packages/apple-runner/src/runner-contract.ts index 8802c59bf0..efc98bdd6a 100644 --- a/packages/apple-runner/src/runner-contract.ts +++ b/packages/apple-runner/src/runner-contract.ts @@ -308,6 +308,22 @@ export const RUNNER_ERROR_CODES = { reason: RUNNER_ERROR_REASONS.hardwareControlUnavailable.reason, diagnosticOnly: { wireCode: 'UNSUPPORTED_OPERATION' }, }, + // The two `lock-screen` outcomes the iOS runner reports after its dispatch, so either may have + // changed the screen. The reasons are the spellings LOCK_SCREEN_REASONS declares in + // contracts/device-rotation.ts, which the Android owner raises too; a literal keeps that module + // out of this one's eager closure, as KEYBOARD_DISMISS_UNAVAILABLE does for its reason. + // SpringBoard still reports the previous lock state after the lock button or the unlock swipe. + LOCK_SCREEN_UNVERIFIED: { + dispatched: 'unknown', + reason: 'lock-screen-unverified', + diagnosticOnly: {}, + }, + // The unlock swipe raised a passcode prompt. The runner typed nothing, so the screen stays locked. + LOCK_SCREEN_SECURE: { + dispatched: 'unknown', + reason: 'lock-screen-secure', + diagnosticOnly: { wireCode: 'UNSUPPORTED_OPERATION' }, + }, // macOS `back` where the app's tree exposes no in-app back control. That refusal answered with no // code at all before, which left the caller reading prose, and the host read the reply as // `COMMAND_FAILED`. There is no wire-code override on purpose: the `UNSUPPORTED_OPERATION` family is diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 3690984da2..61ec4d37fc 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -220,6 +220,8 @@ export function createAgentDeviceClient( await executeCommand>('tv-remote', options), hardwareButton: async (options) => await executeCommand>('hardware-button', options), + lockScreen: async (options) => + await executeCommand>('lock-screen', options), telephony: async (options) => await executeCommand>('telephony', options), reactNative: async (options) => await executeCommand('react-native', options), diff --git a/packages/command-output/src/cli-output.test.ts b/packages/command-output/src/cli-output.test.ts index 3ad12792de..1a5be42fb1 100644 --- a/packages/command-output/src/cli-output.test.ts +++ b/packages/command-output/src/cli-output.test.ts @@ -58,6 +58,7 @@ const FORMATTER_COMMANDS = [ 'install-from-source', 'is', 'keyboard', + 'lock-screen', 'logs', 'longpress', 'metro', diff --git a/packages/command-output/src/system/output.ts b/packages/command-output/src/system/output.ts index b91c4f2941..36ad3f8e41 100644 --- a/packages/command-output/src/system/output.ts +++ b/packages/command-output/src/system/output.ts @@ -72,6 +72,7 @@ export const systemCliOutputFormatters = withSettleCapableNotes({ clipboard: resultOutput(clipboardCliOutput), 'tv-remote': messageOutput, 'hardware-button': messageOutput, + 'lock-screen': messageOutput, telephony: messageOutput, } satisfies Partial>); diff --git a/packages/command-registry/src/__tests__/command-result.test.ts b/packages/command-registry/src/__tests__/command-result.test.ts index facc4ad617..ed1e4b8f44 100644 --- a/packages/command-registry/src/__tests__/command-result.test.ts +++ b/packages/command-registry/src/__tests__/command-result.test.ts @@ -15,6 +15,7 @@ import type { AppSwitcherCommandResult, BackCommandResult, HomeCommandResult, + LockScreenCommandResult, OrientationCommandResult, ShakeCommandResult, TvRemoteCommandResult, @@ -65,6 +66,7 @@ test('seeded CommandResult entries resolve to their existing contract result typ const tvRemote: Equal, TvRemoteCommandResult> = true; const telephony: Equal, TelephonyCommandResult> = true; const shake: Equal, ShakeCommandResult> = true; + const lockScreen: Equal, LockScreenCommandResult> = true; const wait: Equal, WaitCommandResult> = true; const prepare: Equal, PrepareCommandResult> = true; const push: Equal, PushCommandResult> = true; @@ -98,6 +100,7 @@ test('seeded CommandResult entries resolve to their existing contract result typ tvRemote, telephony, shake, + lockScreen, wait, prepare, push, @@ -144,6 +147,7 @@ test('CommandResultMap is seeded only from already-existing contract result type | 'tv-remote' | 'telephony' | 'shake' + | 'lock-screen' | 'wait' | 'scroll' | 'prepare' diff --git a/packages/command-registry/src/command-result.ts b/packages/command-registry/src/command-result.ts index e9d7cd3d12..2adb13b167 100644 --- a/packages/command-registry/src/command-result.ts +++ b/packages/command-registry/src/command-result.ts @@ -18,6 +18,7 @@ import type { FoldCommandResult, HardwareButtonCommandResult, HomeCommandResult, + LockScreenCommandResult, OrientationCommandResult, ShakeCommandResult, TvRemoteCommandResult, @@ -80,6 +81,7 @@ export interface CommandResultMap { home: HomeCommandResult; hover: HoverCommandResponseData; keyboard: KeyboardCommandResult; + 'lock-screen': LockScreenCommandResult; longpress: LongPressCommandResponseData; orientation: OrientationCommandResult; prepare: PrepareCommandResult; diff --git a/packages/command-registry/src/descriptors/device-operations.ts b/packages/command-registry/src/descriptors/device-operations.ts index 6c0a9d7425..79c7994a82 100644 --- a/packages/command-registry/src/descriptors/device-operations.ts +++ b/packages/command-registry/src/descriptors/device-operations.ts @@ -39,6 +39,7 @@ import { hardwareButtonRuntimePlanUses, homeRuntimeUse, hoverRuntimeUses, + lockScreenRuntimePlanUses, longPressRuntimeUses, orientationRuntimePlanUses, pressRuntimeUses, @@ -629,6 +630,20 @@ export const DEVICE_OPERATION_COMMAND_DESCRIPTORS = { ...GENERIC_MUTATING_COMMAND_TRAITS, platformExecution: { kind: 'device-runtime', uses: hardwareButtonRuntimePlanUses }, }, + { + name: 'lock-screen', + ...(ownerFilesEnabled + ? { ownerFiles: ['packages/command-surface/src/system/lock-screen.ts'] as const } + : {}), + catalog: { group: 'public', key: 'lockScreen' }, + frameworkTier: 'extended', + // The first positional selects the lockScreen or unlockScreen cell, the way hardware-button + // selects a key; admission binds exactly that one fact. No post-action observation is + // declared: settling would re-capture, and so re-foreground, the session app over the lock + // screen this command shows. + ...GENERIC_MUTATING_COMMAND_TRAITS, + platformExecution: { kind: 'device-runtime', uses: lockScreenRuntimePlanUses }, + }, { name: 'install-from-source', deviceClaimPolicy: 'none', diff --git a/packages/command-surface/src/client-port.ts b/packages/command-surface/src/client-port.ts index d072a476c9..b46c8a1c61 100644 --- a/packages/command-surface/src/client-port.ts +++ b/packages/command-surface/src/client-port.ts @@ -89,6 +89,7 @@ import type { TransformGestureOptions, TvRemoteCommandOptions, HardwareButtonCommandOptions, + LockScreenCommandOptions, TypeTextOptions, ViewportCommandOptions, WaitCommandOptions, @@ -122,6 +123,7 @@ export type AgentDeviceCommandClient = { hardwareButton: ( options: HardwareButtonCommandOptions, ) => Promise>; + lockScreen: (options: LockScreenCommandOptions) => Promise>; telephony: (options: TelephonyCommandOptions) => Promise>; wait: (options: WaitCommandOptions) => Promise>; alert: (options?: AlertCommandOptions) => Promise; diff --git a/packages/command-surface/src/system/index.test.ts b/packages/command-surface/src/system/index.test.ts index 62939691e3..b679029682 100644 --- a/packages/command-surface/src/system/index.test.ts +++ b/packages/command-surface/src/system/index.test.ts @@ -5,6 +5,7 @@ import type { BackCommandOptions, FoldCommandOptions, HomeCommandOptions, + LockScreenCommandOptions, OrientationCommandOptions, ShakeCommandOptions, TelephonyCommandOptions, @@ -20,6 +21,7 @@ import { clipboardCliReader, clipboardDaemonWriter } from './clipboard.ts'; import { foldCliReader, foldDaemonWriter } from './fold.ts'; import { hardwareButtonCliReader, hardwareButtonDaemonWriter } from './hardware-button.ts'; import { keyboardCliReader, keyboardDaemonWriter } from './keyboard.ts'; +import { lockScreenCliReader, lockScreenDaemonWriter } from './lock-screen.ts'; import { orientationCliReader, orientationDaemonWriter } from './orientation.ts'; import { telephonyCliReader, telephonyDaemonWriter } from './telephony.ts'; import { tvRemoteCliReader, tvRemoteDaemonWriter } from './tv-remote.ts'; @@ -64,6 +66,9 @@ describe('system command interface', () => { expectTypeOf().toEqualTypeOf< (options: TvRemoteCommandOptions) => Promise> >(); + expectTypeOf().toEqualTypeOf< + (options: LockScreenCommandOptions) => Promise> + >(); }); const parameterless = ['appstate', 'home', 'app-switcher', 'action-button', 'shake'] as const; @@ -301,6 +306,23 @@ describe('system command interface', () => { hardwareButtonDaemonWriter({ button: 'sleep' } as Record).positionals, ).toEqual(['sleep']); }); + + test('lock-screen reader and writer take exactly one lock or unlock action', () => { + expect(lockScreenCliReader(['lock'], flags({ platform: 'android' }))).toEqual({ + platform: 'android', + action: 'lock', + }); + expect(lockScreenCliReader(['Unlock'], flags())).toEqual({ action: 'unlock' }); + expect( + lockScreenDaemonWriter({ action: 'unlock' } as Record).positionals, + ).toEqual(['unlock']); + for (const positionals of [[], ['lock', 'unlock'], ['locked'], ['sleep']]) { + expectInvalidArgs( + () => lockScreenCliReader(positionals, flags()), + 'lock-screen requires exactly one action', + ); + } + }); }); test('fold keyframes survive CLI and daemon projection without a preset', () => { diff --git a/packages/command-surface/src/system/index.ts b/packages/command-surface/src/system/index.ts index c12bba50df..7709e2239d 100644 --- a/packages/command-surface/src/system/index.ts +++ b/packages/command-surface/src/system/index.ts @@ -7,6 +7,7 @@ import { foldCommandFacet } from './fold.ts'; import { hardwareButtonCommandFacet } from './hardware-button.ts'; import { homeCommandFacet } from './home.ts'; import { keyboardCommandFacet } from './keyboard.ts'; +import { lockScreenCommandFacet } from './lock-screen.ts'; import { orientationCommandFacet } from './orientation.ts'; import { shakeCommandFacet } from './shake.ts'; import { telephonyCommandFacet } from './telephony.ts'; @@ -33,6 +34,7 @@ export const systemCommandFamily = defineCommandFamilyFromFacets({ clipboardCommandFacet, tvRemoteCommandFacet, hardwareButtonCommandFacet, + lockScreenCommandFacet, telephonyCommandFacet, ], }); diff --git a/packages/command-surface/src/system/lock-screen.ts b/packages/command-surface/src/system/lock-screen.ts new file mode 100644 index 0000000000..62695333b8 --- /dev/null +++ b/packages/command-surface/src/system/lock-screen.ts @@ -0,0 +1,60 @@ +import { + LOCK_SCREEN_ACTIONS, + LOCK_SCREEN_USAGE, + parseLockScreenPositionals, +} from '@agent-device/contracts/device'; +import type { CommandSchemaOverride } from '@agent-device/command-registry/command-schema'; +import { commonInputFromFlags, direct, requiredDaemonString } from '../cli-grammar/common.ts'; +import type { CliReader, DaemonWriter } from '../cli-grammar/types.ts'; +import { enumField, requiredField } from '../command-input.ts'; +import { defineCommandFacet } from '../family/types.ts'; +import { defineFieldCommandMetadata } from '../field-command-contract.ts'; + +const LOCK_SCREEN_COMMAND_NAME = 'lock-screen'; + +const lockScreenCommandDescription = + 'Lock or unlock the device screen. lock shows the lock screen and leaves a locked screen alone; unlock dismisses it back to the app that was in front. Each returns once the device reports that lock state. Android locks with KEYCODE_SLEEP and unlocks with KEYCODE_WAKEUP then wm dismiss-keyguard, verified by the keyguard state dumpsys window reports; unlock always sends the wake event, which leaves a screen that is on unchanged. iPhone and iPad simulators lock through the XCUITest lock button, verified by the SpringBoard lock state and a lock screen surface, and unlock with a swipe up from the bottom edge after the lock button wakes a dark screen; unlock also needs the screen on. A PIN, pattern, password, or passcode lock is never unlocked: unlock refuses with reason lock-screen-secure and types nothing. The session app is not activated, so verify with screenshot; an app-scoped command such as snapshot can bring the app back to the front on iOS. Every other target refuses this command, including physical iPhones and iPads and Android TV.'; + +const lockScreenCommandMetadata = defineFieldCommandMetadata( + LOCK_SCREEN_COMMAND_NAME, + lockScreenCommandDescription, + { + action: requiredField( + enumField( + LOCK_SCREEN_ACTIONS, + 'lock shows the lock screen; unlock dismisses a lock screen that asks for no credential.', + ), + ), + }, +); + +const lockScreenCliSchema = { + usageOverride: `lock-screen ${LOCK_SCREEN_USAGE}`, + positionalArgs: ['action'], +} as const satisfies CommandSchemaOverride; + +export const lockScreenCliReader: CliReader = (positionals, flags) => ({ + ...commonInputFromFlags(flags), + // One shared helper answers arity and parse for the CLI reader and the daemon resolver alike. + action: parseLockScreenPositionals(positionals), +}); + +export const lockScreenDaemonWriter: DaemonWriter = direct(LOCK_SCREEN_COMMAND_NAME, (input) => [ + requiredDaemonString(input.action, 'lock-screen requires action'), +]); + +export const lockScreenCommandFacet = defineCommandFacet({ + name: LOCK_SCREEN_COMMAND_NAME, + effect: 'write', + text: { + summary: 'Lock or unlock the device screen', + searchHint: 'lockscreen screenlock', + cliDetail: + 'Android phones and tablets, and iPhone and iPad simulators. unlock never enters a PIN, pattern, password, or passcode; it refuses such a lock.', + }, + metadata: lockScreenCommandMetadata, + run: (client, input) => client.command.lockScreen(input), + cliSchema: lockScreenCliSchema, + cliReader: lockScreenCliReader, + daemonWriter: lockScreenDaemonWriter, +}); diff --git a/packages/command-surface/src/system/output-schemas.ts b/packages/command-surface/src/system/output-schemas.ts index 70608dfaa5..1a6c86a9ea 100644 --- a/packages/command-surface/src/system/output-schemas.ts +++ b/packages/command-surface/src/system/output-schemas.ts @@ -102,6 +102,14 @@ export const SYSTEM_COMMAND_OUTPUT_SCHEMAS = { }, ['action', 'button', 'message'], ), + 'lock-screen': objectSchema( + { + action: constSchema('lock-screen'), + state: enumSchema(['locked', 'unlocked']), + message: stringSchema(), + }, + ['action', 'state', 'message'], + ), // packages/contracts/src/telephony-input.ts — discriminated union on `action`. telephony: { type: 'object', @@ -220,6 +228,7 @@ export const SYSTEM_COMMAND_OUTPUT_SCHEMAS = { | 'shake' | 'tv-remote' | 'hardware-button' + | 'lock-screen' | 'telephony' | 'clipboard' | 'appstate' diff --git a/packages/contracts/src/client-system.ts b/packages/contracts/src/client-system.ts index 119788f37f..df2353c0c0 100644 --- a/packages/contracts/src/client-system.ts +++ b/packages/contracts/src/client-system.ts @@ -7,6 +7,7 @@ import type { DeviceCommandBaseOptions } from './client-connection.ts'; import type { SettleCommandOptions } from './client-gesture.ts'; import type { HardwareButtonName, + LockScreenAction, OrientationRequest, SetFoldPoseInput, } from './device-rotation.ts'; @@ -113,6 +114,10 @@ export type HardwareButtonCommandOptions = DeviceCommandBaseOptions & { button: HardwareButtonName; }; +export type LockScreenCommandOptions = DeviceCommandBaseOptions & { + action: LockScreenAction; +}; + export type TelephonyCommandOptions = DeviceCommandBaseOptions & TelephonyEventInput; export type KeyboardCommandOptions = DeviceCommandBaseOptions & { diff --git a/packages/contracts/src/device-rotation.ts b/packages/contracts/src/device-rotation.ts index ae7bdc93ca..9d88296906 100644 --- a/packages/contracts/src/device-rotation.ts +++ b/packages/contracts/src/device-rotation.ts @@ -1,4 +1,4 @@ -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; /** Single source of truth for the discriminator the Apple owner sets and the MCP schema advertises. */ export const FOLD_SCREEN_COORDINATE_SPACE = 'native-panel' as const; @@ -214,6 +214,44 @@ export function parseHardwareButtonPositionals(positionals: readonly string[]): return parseHardwareButton(positionals[0]); } +// ---- Lock screen ----------------------------------------------------------------------------- +// Lives beside the rotation vocabulary for the reason the hardware-button names do: every entry +// that parses one command positional already evaluates this module, and a module of its own would +// join their eager closures (scripts/__tests__/eager-closure-budgets.ts). + +/** + * The `lock-screen` actions, in command order. Each selects one system-button cell, the way + * `keyboard ` selects a keyboard-family cell. + */ +export const LOCK_SCREEN_ACTIONS = ['lock', 'unlock'] as const; +export type LockScreenAction = (typeof LOCK_SCREEN_ACTIONS)[number]; + +/** The CLI synopsis tail naming the accepted actions. */ +export const LOCK_SCREEN_USAGE = `<${LOCK_SCREEN_ACTIONS.join('|')}>`; + +/** + * Owns the whole `lock-screen` positional contract: exactly one action, matched exactly. The CLI + * reader and the daemon resolver both call this, so an unknown action refuses with `INVALID_ARGS` + * before any device dispatch. + */ +export function parseLockScreenPositionals(positionals: readonly string[]): LockScreenAction { + const normalized = positionals.length === 1 ? positionals[0]!.toLowerCase() : undefined; + const action = LOCK_SCREEN_ACTIONS.find((candidate) => candidate === normalized); + if (action) return action; + throw new AppError( + 'INVALID_ARGS', + `lock-screen requires exactly one action: ${LOCK_SCREEN_ACTIONS.join(', ')}.`, + ); +} + +/** The `lock-screen` reasons that both the Android and the Apple owner raise. */ +export const LOCK_SCREEN_REASONS = { + // The lock needs a PIN, pattern, password, or passcode, so unlock typed nothing and left it locked. + secureLock: { reason: 'lock-screen-secure' }, + // The lock or unlock was sent, but the device still reports the previous lock state. + stateUnverified: { reason: 'lock-screen-unverified' }, +} as const satisfies ReasonTable<'lock-screen'>; + // ---- Hinge pose ------------------------------------------------------------------------------ // Lives beside the rotation vocabulary because every entry that reads one device pose already // evaluates this module; a module of its own would join the eager closure of entries that can diff --git a/packages/contracts/src/facades/client.ts b/packages/contracts/src/facades/client.ts index a71a2b4589..55b60afddb 100644 --- a/packages/contracts/src/facades/client.ts +++ b/packages/contracts/src/facades/client.ts @@ -128,6 +128,7 @@ export type { FoldCommandOptions, DoctorCommandOptions, HardwareButtonCommandOptions, + LockScreenCommandOptions, HomeCommandOptions, KeyboardCommandOptions, OrientationCommandOptions, diff --git a/packages/contracts/src/facades/device.ts b/packages/contracts/src/facades/device.ts index 4671393079..d7d554d292 100644 --- a/packages/contracts/src/facades/device.ts +++ b/packages/contracts/src/facades/device.ts @@ -54,8 +54,12 @@ export { HARDWARE_BUTTON_NAME_LABELS, HARDWARE_BUTTON_USAGE, parseHardwareButtonPositionals, + LOCK_SCREEN_ACTIONS, + LOCK_SCREEN_REASONS, + LOCK_SCREEN_USAGE, + parseLockScreenPositionals, } from '../device-rotation.ts'; -export type { HardwareButton, HardwareButtonName } from '../device-rotation.ts'; +export type { HardwareButton, HardwareButtonName, LockScreenAction } from '../device-rotation.ts'; export { TELEPHONY_ACTIONS, TELEPHONY_CALL_ACTIONS, diff --git a/packages/contracts/src/interactor-operation-catalog-conformance.test.ts b/packages/contracts/src/interactor-operation-catalog-conformance.test.ts index 63ba4641be..986bd3044c 100644 --- a/packages/contracts/src/interactor-operation-catalog-conformance.test.ts +++ b/packages/contracts/src/interactor-operation-catalog-conformance.test.ts @@ -37,6 +37,8 @@ const EXPECTATIONS: { appSwitcher: { method: 'appSwitcher', input: {} }, actionButton: { method: 'actionButton', input: {} }, shake: { method: 'shake', input: {} }, + lockScreen: { method: 'lockScreen', input: {} }, + unlockScreen: { method: 'unlockScreen', input: {} }, volumeUp: { method: 'volumeUp', input: {} }, volumeDown: { method: 'volumeDown', input: {} }, power: { method: 'power', input: {} }, diff --git a/packages/contracts/src/interactor-types.ts b/packages/contracts/src/interactor-types.ts index 54ca147443..87c1a69e5e 100644 --- a/packages/contracts/src/interactor-types.ts +++ b/packages/contracts/src/interactor-types.ts @@ -457,6 +457,18 @@ export type Interactor = { * resolving an absent member as a successful no-op. */ shake?(): Promise; + /** + * Optional (parity with `shake`): shows the lock screen and returns once the device reports it + * locked; a device already locked returns without a dispatch. An owner without a lock control + * leaves it undefined, and its fact refuses `lock-screen lock` before binding. + */ + lockScreen?(): Promise; + /** + * Optional (parity with `lockScreen`): dismisses the lock screen back to whatever was in front + * and returns once the device reports it unlocked. It never enters a credential: a lock that + * asks for a PIN, pattern, password, or passcode is refused with `lock-screen-secure`. + */ + unlockScreen?(): Promise; /** * Optional (parity with `home`): presses the physical volume-up key once, a control phone * owners with a volume button carry. An owner without it leaves it undefined; its fact refuses diff --git a/packages/contracts/src/navigation.ts b/packages/contracts/src/navigation.ts index d9ccf96542..9426c32841 100644 --- a/packages/contracts/src/navigation.ts +++ b/packages/contracts/src/navigation.ts @@ -112,3 +112,15 @@ export type HardwareButtonCommandResult = { button: HardwareButtonName; message: string; }; + +/** + * `lock-screen` — `{ action: 'lock-screen', state, message }`. + * + * `state` is the lock state the device reported after the command, read back rather than assumed + * from the dispatch. A request that found the screen already in that state reports it too. + */ +export type LockScreenCommandResult = { + action: 'lock-screen'; + state: 'locked' | 'unlocked'; + message: string; +}; diff --git a/packages/contracts/src/platform-runtime-operations.ts b/packages/contracts/src/platform-runtime-operations.ts index 38d3f86d43..06aab799e1 100644 --- a/packages/contracts/src/platform-runtime-operations.ts +++ b/packages/contracts/src/platform-runtime-operations.ts @@ -131,6 +131,13 @@ export const keyboardEnterUse = defineUse({ required: ['keyboardEnter'] }); export const appSwitcherRuntimeUse = defineUse({ required: ['appSwitcher'] }); export const actionButtonRuntimeUse = defineUse({ required: ['actionButton'] }); export const shakeRuntimeUse = defineUse({ required: ['shake'] }); +// `lock-screen`'s cells: the parsed action names exactly one of them, as a hardware-button name does. +export const lockScreenRuntimeUse = defineUse({ required: ['lockScreen'] }); +export const unlockScreenRuntimeUse = defineUse({ required: ['unlockScreen'] }); +export const lockScreenRuntimePlanUses = Object.freeze([ + lockScreenRuntimeUse, + unlockScreenRuntimeUse, +] as const); // `hardware-button`'s cells (ADR 0019 §9): the daemon admits and binds exactly the one the parsed // positional names, never all of them (#3848). export const volumeUpRuntimeUse = defineUse({ required: ['volumeUp'] }); diff --git a/packages/contracts/src/platform-runtime-unavailable.ts b/packages/contracts/src/platform-runtime-unavailable.ts index 052a26dbcd..c8dddb3fa8 100644 --- a/packages/contracts/src/platform-runtime-unavailable.ts +++ b/packages/contracts/src/platform-runtime-unavailable.ts @@ -241,6 +241,8 @@ export function createUnavailablePlatformRuntimeFacts( appSwitcher: frozen.systemButton, actionButton: frozen.systemButton, shake: frozen.systemButton, + lockScreen: frozen.systemButton, + unlockScreen: frozen.systemButton, volumeUp: frozen.systemButton, volumeDown: frozen.systemButton, power: frozen.systemButton, diff --git a/packages/contracts/src/runtime-operation-names.ts b/packages/contracts/src/runtime-operation-names.ts index c90a33e3ed..47b10c6212 100644 --- a/packages/contracts/src/runtime-operation-names.ts +++ b/packages/contracts/src/runtime-operation-names.ts @@ -49,6 +49,7 @@ export const RUNTIME_OPERATION_NAMES = [ 'keyboardEnter', 'keyboardStatus', 'listApps', + 'lockScreen', 'longPressPoint', 'materializeAppSource', 'mediaFastForward', @@ -100,6 +101,7 @@ export const RUNTIME_OPERATION_NAMES = [ 'typeText', 'uninstallApp', 'unlockOrientation', + 'unlockScreen', 'volumeDown', 'volumeUp', 'wake', diff --git a/packages/contracts/src/system-button-runtime.test.ts b/packages/contracts/src/system-button-runtime.test.ts index 536cc5a2e0..8f925ad3f0 100644 --- a/packages/contracts/src/system-button-runtime.test.ts +++ b/packages/contracts/src/system-button-runtime.test.ts @@ -1,7 +1,12 @@ import { expect, test, vi } from 'vitest'; import type { Interactor } from './interactor-types.ts'; import { localInteractorSource } from './interactor-operation-binding.ts'; -import { HARDWARE_BUTTON_NAMES, parseHardwareButtonPositionals } from './device-rotation.ts'; +import { + HARDWARE_BUTTON_NAMES, + LOCK_SCREEN_ACTIONS, + parseHardwareButtonPositionals, + parseLockScreenPositionals, +} from './device-rotation.ts'; import { SYSTEM_BUTTONS, SYSTEM_BUTTON_LABELS, @@ -28,6 +33,8 @@ test('an omitted button reports the family denial, a named one its own cell', () appSwitcher: unsupported, actionButton: unsupported, shake: unsupported, + lockScreen: unsupported, + unlockScreen: unsupported, volumeUp: unsupported, volumeDown: unsupported, power: unsupported, @@ -169,3 +176,21 @@ test('the shared Android hardware-button rule admits phones and refuses TV and s }), ); }); + +// `lock-screen` takes exactly one action, matched exactly, and an unknown one refuses before any +// device dispatch. +test('the lock-screen positional helper enforces arity and the exact action', () => { + expect(LOCK_SCREEN_ACTIONS.map((action) => parseLockScreenPositionals([action]))).toEqual([ + 'lock', + 'unlock', + ]); + expect(parseLockScreenPositionals(['UNLOCK'])).toBe('unlock'); + for (const positionals of [[], ['lock', 'unlock'], ['locked'], [''], ['sleep']] as const) { + expect(() => parseLockScreenPositionals(positionals)).toThrowError( + expect.objectContaining({ + code: 'INVALID_ARGS', + message: 'lock-screen requires exactly one action: lock, unlock.', + }), + ); + } +}); diff --git a/packages/contracts/src/system-button-runtime.ts b/packages/contracts/src/system-button-runtime.ts index 985e371040..384ff44ad3 100644 --- a/packages/contracts/src/system-button-runtime.ts +++ b/packages/contracts/src/system-button-runtime.ts @@ -13,7 +13,9 @@ import type { SnapshotRuntimeExecution } from './snapshot-runtime.ts'; * the rest are the phone hardware keys the `hardware-button` command names — volume, power, * mute, the explicit sleep/wake events, and the media keys. `shake` is the one cell that is a * device motion rather than a key: it shares the family's shape, one argumentless dispatch that - * returns nothing. What varies between them is which + * returns nothing. `lockScreen` and `unlockScreen` are the two cells `lock-screen` selects; each + * returns only once the device reports the requested lock state, and throws otherwise. What + * varies between them is which * owners carry the control, and that is the fact table's job, not a per-button module's: a * button joins this list and its owners state a cell. */ @@ -22,6 +24,8 @@ export const SYSTEM_BUTTONS = [ 'appSwitcher', 'actionButton', 'shake', + 'lockScreen', + 'unlockScreen', 'volumeUp', 'volumeDown', 'power', @@ -46,6 +50,8 @@ export const SYSTEM_BUTTON_LABELS = { appSwitcher: 'app-switcher', actionButton: 'action-button', shake: 'shake', + lockScreen: 'lock-screen lock', + unlockScreen: 'lock-screen unlock', volumeUp: 'volume-up', volumeDown: 'volume-down', power: 'power', @@ -156,7 +162,9 @@ const ANDROID_HARDWARE_BUTTON_CELLS = SYSTEM_BUTTONS.filter( button !== 'home' && button !== 'appSwitcher' && button !== 'actionButton' && - button !== 'shake', + button !== 'shake' && + button !== 'lockScreen' && + button !== 'unlockScreen', ) satisfies readonly HardwareButton[]; type HardwareCellsCoverCommandVocabulary = @@ -236,6 +244,16 @@ export const SYSTEM_BUTTON_INTERACTOR_OPERATIONS = [ label: SYSTEM_BUTTON_LABELS.shake, bind: (signal, resolve) => bindSystemButton('shake', signal, resolve), }, + { + operation: 'lockScreen', + label: SYSTEM_BUTTON_LABELS.lockScreen, + bind: (signal, resolve) => bindSystemButton('lockScreen', signal, resolve), + }, + { + operation: 'unlockScreen', + label: SYSTEM_BUTTON_LABELS.unlockScreen, + bind: (signal, resolve) => bindSystemButton('unlockScreen', signal, resolve), + }, { operation: 'volumeUp', label: SYSTEM_BUTTON_LABELS.volumeUp, diff --git a/packages/daemon/src/__tests__/support/runtime-binding-conformance.ts b/packages/daemon/src/__tests__/support/runtime-binding-conformance.ts index 31c472ab15..13a31248b6 100644 --- a/packages/daemon/src/__tests__/support/runtime-binding-conformance.ts +++ b/packages/daemon/src/__tests__/support/runtime-binding-conformance.ts @@ -200,6 +200,29 @@ export const conformedRuntimeBindings = { ), }, ...hardwareButtonConformedBindings(), + // Each `lock-screen` action is its own admission cell on the one `lock-screen` descriptor. + 'lock-screen': { + plan: { refused: 'lockScreen', admitted: [] }, + resolve: async (device, bindings) => + refusable( + await resolveBoundSystemButtonRuntime('lock-screen', { + device, + positionals: ['lock'], + ...bindings, + }), + ), + }, + 'lock-screen unlock': { + plan: { refused: 'unlockScreen', admitted: [], command: 'lock-screen' }, + resolve: async (device, bindings) => + refusable( + await resolveBoundSystemButtonRuntime('lock-screen', { + device, + positionals: ['unlock'], + ...bindings, + }), + ), + }, 'tv-remote': { resolve: async (device, bindings) => refusable(await resolveBoundTvRemoteRuntime({ device, positionals: ['down'], ...bindings })), diff --git a/packages/daemon/src/core/runtime-operation-effects.ts b/packages/daemon/src/core/runtime-operation-effects.ts index 8d6805bb2f..12ea647a7b 100644 --- a/packages/daemon/src/core/runtime-operation-effects.ts +++ b/packages/daemon/src/core/runtime-operation-effects.ts @@ -56,6 +56,7 @@ export const RUNTIME_OPERATION_EFFECTS: Readonly< keyboardEnter: 'mutates', keyboardStatus: 'repeatable', listApps: 'repeatable', + lockScreen: 'mutates', longPressPoint: 'mutates', materializeAppSource: 'repeatable', mediaFastForward: 'mutates', @@ -107,6 +108,7 @@ export const RUNTIME_OPERATION_EFFECTS: Readonly< typeText: 'mutates', uninstallApp: 'mutates', unlockOrientation: 'mutates', + unlockScreen: 'mutates', volumeDown: 'mutates', volumeUp: 'mutates', wake: 'mutates', diff --git a/packages/daemon/src/execution/__tests__/system-button-runtime.test.ts b/packages/daemon/src/execution/__tests__/system-button-runtime.test.ts index 5ec8fcd9f2..d4343d7bfe 100644 --- a/packages/daemon/src/execution/__tests__/system-button-runtime.test.ts +++ b/packages/daemon/src/execution/__tests__/system-button-runtime.test.ts @@ -14,6 +14,7 @@ import { actionButtonRuntimeUse, appSwitcherRuntimeUse, homeRuntimeUse, + lockScreenRuntimeUse, mediaFastForwardRuntimeUse, mediaNextRuntimeUse, mediaPlayPauseRuntimeUse, @@ -23,6 +24,7 @@ import { shakeRuntimeUse, powerRuntimeUse, sleepRuntimeUse, + unlockScreenRuntimeUse, volumeDownRuntimeUse, volumeUpRuntimeUse, wakeRuntimeUse, @@ -47,6 +49,7 @@ import type { GenericPlatformExecutionParams } from '../../core/generic-leaf-exe import { isSystemButtonRouteCommand, resolveBoundHardwareButtonRuntime, + resolveBoundLockScreenRuntime, resolveBoundSystemButtonRuntime, type SystemButtonCommand, } from '../system-button-runtime.ts'; @@ -121,14 +124,16 @@ const EXPECTED: Record< test('the registry names exactly the commands the press route serves', () => { // The denominator is the route's own predicate over the registry: the argumentless - // rows plus the positional-selected `hardware-button`, so a press command joining (or - // leaving) the route without a row here or in the route set fails. + // rows plus the positional-selected `hardware-button` and `lock-screen`, so a press command + // joining (or leaving) the route without a row here or in the route set fails. const routeCommands = commandDescriptors .map((descriptor) => descriptor.name) .filter(isSystemButtonRouteCommand); - expect([...routeCommands].sort()).toEqual([...Object.keys(EXPECTED), 'hardware-button'].sort()); - // The conformance family stays the argumentless presses; hardware-button carries its own - // plan rows in the conformance table. + expect([...routeCommands].sort()).toEqual( + [...Object.keys(EXPECTED), 'hardware-button', 'lock-screen'].sort(), + ); + // The conformance family stays the argumentless presses; the positional-selected commands + // carry their own plan rows in the conformance table. expect([...systemButtonCommands].sort()).toEqual(Object.keys(EXPECTED).sort()); }); @@ -332,3 +337,82 @@ test('hardware-button refuses an unknown or missing button before inspecting any expect(harness.inspectFacts).not.toHaveBeenCalled(); expect(harness.press).not.toHaveBeenCalled(); }); + +// lock-screen selects the lockScreen or unlockScreen cell from its action and reports the state +// the owner verified. The use is stated per action here, not read back from the row table. +test.each([ + ['lock', lockScreenRuntimeUse, 'lockScreen', 'locked', 'Locked the screen'], + ['unlock', unlockScreenRuntimeUse, 'unlockScreen', 'unlocked', 'Unlocked the screen'], +] as const)( + 'lock-screen %s binds its cell and reports the verified state', + async (action, use, cell, state, message) => { + const harness = runtimeHarness(cell, available, androidPhone); + + const resolved = await resolveBoundSystemButtonRuntime('lock-screen', { + platformServices: daemonPlatformServicesFixture(), + device: androidPhone, + positionals: [action], + inspectFacts: harness.inspectFacts, + bindDevice: harness.bindDevice, + }); + + expect(resolved.ok).toBe(true); + if (!resolved.ok) return; + expect(harness.bindDevice).toHaveBeenCalledWith(androidPhone, use); + const session = makeSession('system-button-runtime', { device: androidPhone }); + expect( + await resolved.execute({ + session, + sessionName: session.name, + logPath: '/tmp/daemon.log', + command: 'lock-screen', + request: { + command: 'lock-screen', + positionals: [action], + token: 't', + session: session.name, + }, + positionals: [action], + out: undefined, + dispatchContext: {}, + }), + ).toEqual({ action: 'lock-screen', state, message }); + expect(harness.press).toHaveBeenCalledTimes(1); + }, +); + +test('lock-screen refuses an unknown or missing action before inspecting any device', async () => { + const harness = runtimeHarness('lockScreen'); + for (const positionals of [[], ['sleep'], ['lock', 'unlock']] as const) { + await expect( + resolveBoundLockScreenRuntime({ + platformServices: daemonPlatformServicesFixture(), + device: iosSimulator, + positionals, + inspectFacts: harness.inspectFacts, + bindDevice: harness.bindDevice, + }), + ).rejects.toMatchObject({ code: 'INVALID_ARGS' }); + } + expect(harness.inspectFacts).not.toHaveBeenCalled(); + expect(harness.press).not.toHaveBeenCalled(); +}); + +test('lock-screen rejects an unavailable exact-owner fact before binding', async () => { + const harness = runtimeHarness('unlockScreen', unavailable, macOsDevice); + const resolved = await resolveBoundSystemButtonRuntime('lock-screen', { + platformServices: daemonPlatformServicesFixture(), + device: macOsDevice, + positionals: ['unlock'], + inspectFacts: harness.inspectFacts, + bindDevice: harness.bindDevice, + }); + expect(resolved.ok).toBe(false); + if (resolved.ok) return; + expect(resolved.response).toMatchObject({ + ok: false, + error: { code: 'UNSUPPORTED_OPERATION', details: { reason: 'unsupported-platform-leaf' } }, + }); + expect(harness.bindDevice).not.toHaveBeenCalled(); + expect(harness.press).not.toHaveBeenCalled(); +}); diff --git a/packages/daemon/src/execution/generic-runtime-execution.ts b/packages/daemon/src/execution/generic-runtime-execution.ts index 361334b9ee..66760696b9 100644 --- a/packages/daemon/src/execution/generic-runtime-execution.ts +++ b/packages/daemon/src/execution/generic-runtime-execution.ts @@ -48,7 +48,7 @@ export async function resolveGenericRuntimeExecution( if (isSystemButtonRouteCommand(params.req.command)) { return await resolveBoundSystemButtonRuntime(params.req.command, { device: params.session.device, - // Only `hardware-button` reads these; the resolver owns the arity refusal for a miss. + // Only `hardware-button` and `lock-screen` read these; their resolvers own the arity refusal. positionals: params.req.positionals, inspectFacts: params.inspectFacts, platformServices: params.platformServices, diff --git a/packages/daemon/src/execution/system-button-runtime.ts b/packages/daemon/src/execution/system-button-runtime.ts index 3ebe9b8b3d..2d371b6856 100644 --- a/packages/daemon/src/execution/system-button-runtime.ts +++ b/packages/daemon/src/execution/system-button-runtime.ts @@ -2,6 +2,7 @@ import { actionButtonRuntimeUse, appSwitcherRuntimeUse, homeRuntimeUse, + lockScreenRuntimeUse, mediaFastForwardRuntimeUse, mediaNextRuntimeUse, mediaPlayPauseRuntimeUse, @@ -11,6 +12,7 @@ import { powerRuntimeUse, shakeRuntimeUse, sleepRuntimeUse, + unlockScreenRuntimeUse, volumeDownRuntimeUse, volumeUpRuntimeUse, wakeRuntimeUse, @@ -23,8 +25,11 @@ import type { BoundDeviceRuntime, RuntimeUse } from '@agent-device/contracts/pla import { HARDWARE_BUTTON_NAME_LABELS, parseHardwareButtonPositionals, + parseLockScreenPositionals, type HardwareButton, + type LockScreenAction, } from '@agent-device/contracts/device'; +import type { LockScreenCommandResult } from '@agent-device/contracts/navigation'; import type { SystemButton, SystemButtonInput, @@ -70,18 +75,20 @@ export type SystemButtonCommand = keyof typeof SYSTEM_BUTTON_COMMANDS; /** * Every generic-route command the shared press route below serves: the argumentless rows above - * plus the positional-selected `hardware-button`, whose first positional names the cell (#3848). - * The dispatcher's one guard covers the whole family, so another row grows this module's - * table only — never the dispatcher's switch. + * plus the positional-selected `hardware-button` and `lock-screen`, whose first positional names + * the cell (#3848). The dispatcher's one guard covers the whole family, so another row grows this + * module's table only — never the dispatcher's switch. */ -export type SystemButtonRouteCommand = SystemButtonCommand | 'hardware-button'; +export type SystemButtonRouteCommand = SystemButtonCommand | 'hardware-button' | 'lock-screen'; export function isSystemButtonCommand(command: string): command is SystemButtonCommand { return Object.hasOwn(SYSTEM_BUTTON_COMMANDS, command); } export function isSystemButtonRouteCommand(command: string): command is SystemButtonRouteCommand { - return command === 'hardware-button' || isSystemButtonCommand(command); + return ( + command === 'hardware-button' || command === 'lock-screen' || isSystemButtonCommand(command) + ); } /** @@ -116,6 +123,18 @@ const HARDWARE_BUTTON_COMMAND_ROWS = { }, } as const satisfies Record>; +/** + * The `lock-screen` command's positional-selected rows. Each cell returns only once the owner read + * the requested lock state back, so `state` reports that reading rather than the dispatch. + */ +const LOCK_SCREEN_COMMAND_ROWS = { + lock: { use: lockScreenRuntimeUse, state: 'locked', message: 'Locked the screen' }, + unlock: { use: unlockScreenRuntimeUse, state: 'unlocked', message: 'Unlocked the screen' }, +} as const satisfies Record< + LockScreenAction, + Readonly<{ use: SystemButtonUse; state: LockScreenCommandResult['state']; message: string }> +>; + /** The neutral intent one press carries, projected from a resolved command context. */ function systemButtonInput(context: DaemonCommandContext): SystemButtonInput { return { @@ -134,35 +153,48 @@ export async function resolveBoundSystemButtonRuntime( command: SystemButtonRouteCommand, params: { device: DeviceInfo; - /** Only `hardware-button` reads positionals; the argumentless presses ignore them. */ + /** + * Only `hardware-button` and `lock-screen` read positionals; the argumentless presses ignore + * them. + */ positionals?: readonly string[]; } & RuntimeAdmissionBindings, ): Promise { - if (command === 'hardware-button') { - return await resolveBoundHardwareButtonRuntime({ - device: params.device, - // The hardware resolver owns the positional default and the arity refusal; the delegate - // forwards the request's optional positionals untouched. - positionals: params.positionals, - inspectFacts: params.inspectFacts, - platformServices: params.platformServices, - bindDevice: params.bindDevice, - }); - } + // The positional resolvers own the arity refusal, so the request's optional positionals are + // forwarded untouched. + if (command === 'hardware-button') return await resolveBoundHardwareButtonRuntime(params); + if (command === 'lock-screen') return await resolveBoundLockScreenRuntime(params); const row: SystemButtonCommandRow = SYSTEM_BUTTON_COMMANDS[command]; + return await pressBoundSystemButton(command, row.use, params, () => ({ + action: command, + ...successText(row.message), + })); +} + +/** + * Admits and binds the one cell `use` names, then presses it and answers with `respond()`. The + * exact owner's fact is inspected before the dispatcher runs, so an owner without the control is + * refused rather than discovered mid-execution. + */ +async function pressBoundSystemButton( + command: SystemButtonRouteCommand, + use: SystemButtonUse, + params: { device: DeviceInfo } & RuntimeAdmissionBindings, + respond: () => Record, +): Promise { return await resolveBoundGenericRuntime( { command, device: params.device, - use: row.use, + use, inspectFacts: params.inspectFacts, platformServices: params.platformServices, bindDevice: params.bindDevice, }, async (runtime: BoundDeviceRuntime, context) => { - const [button] = row.use.required; + const [button] = use.required; await runtime.operations[button](systemButtonInput(context)); - return { action: command, ...successText(row.message) }; + return respond(); }, ); } @@ -184,26 +216,37 @@ export async function resolveBoundHardwareButtonRuntime( // refuses with INVALID_ARGS before any device dispatch. const button = parseHardwareButtonPositionals(params.positionals ?? []); const row = HARDWARE_BUTTON_COMMAND_ROWS[button]; - // Widen to the family use so one call site serves every row. - const use: SystemButtonUse = row.use; - return await resolveBoundGenericRuntime( - { - command: 'hardware-button', - device: params.device, - use, - inspectFacts: params.inspectFacts, - platformServices: params.platformServices, - bindDevice: params.bindDevice, - }, - async (runtime: BoundDeviceRuntime, context) => { - const [operation] = row.use.required; - await runtime.operations[operation](systemButtonInput(context)); - const name = row.label; - return { - action: 'hardware-button', - button: name, - ...successText(`Pressed hardware button ${name}`), - }; - }, + return await pressBoundSystemButton('hardware-button', row.use, params, () => ({ + action: 'hardware-button', + button: row.label, + ...successText(`Pressed hardware button ${row.label}`), + })); +} + +/** + * The one place `lock-screen` reaches a device. The action picks the lockScreen or unlockScreen + * cell, and admission inspects the exact owner's fact for it before the dispatcher runs. The owner + * returns only once the device reports the requested lock state, and throws a typed reason + * otherwise, so the result names that state. + */ +export async function resolveBoundLockScreenRuntime( + params: { + device: DeviceInfo; + /** Absent means no positional; the arity refusal below is what answers for it. */ + positionals?: readonly string[]; + } & RuntimeAdmissionBindings, +): Promise { + // Shared with the CLI reader: an unknown or missing action refuses with INVALID_ARGS before + // any owner is inspected or bound. + const row = LOCK_SCREEN_COMMAND_ROWS[parseLockScreenPositionals(params.positionals ?? [])]; + return await pressBoundSystemButton( + 'lock-screen', + row.use, + params, + (): LockScreenCommandResult => ({ + action: 'lock-screen', + state: row.state, + message: row.message, + }), ); } diff --git a/packages/platform-android/src/foldable/pose.ts b/packages/platform-android/src/foldable/pose.ts index 20b6081be1..a21543bf7f 100644 --- a/packages/platform-android/src/foldable/pose.ts +++ b/packages/platform-android/src/foldable/pose.ts @@ -6,10 +6,8 @@ import { sleep } from '@agent-device/host-kit/retry'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; -import { runAndroidShell } from '../adb.ts'; import { runEmulatorConsole } from '../emulator-console.ts'; -import { androidAdbResultError } from '../adb-failure.ts'; -import type { AndroidAdbExecutorResult } from '../adb-transport.ts'; +import { readAndroidKeyguardShowing, runCheckedAndroidShell } from '../keyguard.ts'; /** * The emulator console's posture ids (`adb emu posture `) and the device state Android @@ -83,7 +81,8 @@ export async function setAndroidFoldPose( // Only a fold to the cover display raises the keyguard, and a keyguard already showing is not // the fold's to clear: only one that `closed` raises is dismissed. - const lockedBefore = pose === 'closed' && (await isKeyguardShowing(device, signal)); + const lockedBefore = + pose === 'closed' && (await readAndroidKeyguardShowing(device, signal)) === true; await sendEmulatorPosture(device, pose, posture.id, signal); emitDiagnostic({ level: 'info', @@ -155,7 +154,11 @@ async function readDeviceStates( device: DeviceInfo, signal: AbortSignal | undefined, ): Promise> { - const { stdout } = await shell(device, ['cmd', 'device_state', 'print-states'], signal); + const { stdout } = await runCheckedAndroidShell( + device, + ['cmd', 'device_state', 'print-states'], + signal, + ); const states = new Map(); for (const match of stdout.matchAll(/identifier=(\d+), name='([A-Z_]+)'/g)) { states.set(match[2]!, match[1]!); @@ -245,7 +248,11 @@ async function readDeviceState( device: DeviceInfo, signal: AbortSignal | undefined, ): Promise { - const { stdout } = await shell(device, ['cmd', 'device_state', 'print-state'], signal); + const { stdout } = await runCheckedAndroidShell( + device, + ['cmd', 'device_state', 'print-state'], + signal, + ); return /\d+/.exec(stdout)?.[0]; } @@ -266,10 +273,10 @@ async function dismissFoldLockScreen( let dismissed = false; for (let attempt = 1; attempt <= ANDROID_FOLD_SETTLE_ATTEMPTS; attempt += 1) { await sleep(ANDROID_FOLD_SETTLE_POLL_MS, signal); - if (await isKeyguardShowing(device, signal)) { + if ((await readAndroidKeyguardShowing(device, signal)) === true) { clearReads = 0; dismissed = true; - await shell(device, ['wm', 'dismiss-keyguard'], signal); + await runCheckedAndroidShell(device, ['wm', 'dismiss-keyguard'], signal); } else { clearReads += 1; if (clearReads >= LOCK_SCREEN_CLEAR_READS) break; @@ -291,14 +298,6 @@ async function dismissFoldLockScreen( } } -async function isKeyguardShowing( - device: DeviceInfo, - signal: AbortSignal | undefined, -): Promise { - const { stdout } = await shell(device, ['dumpsys', 'window'], signal); - return stdout.includes('isKeyguardShowing=true'); -} - /** The hinge sensor the guest reads, as the console reports it: `hinge-angle0 = `. */ async function readHingeAngle( device: DeviceInfo, @@ -316,24 +315,3 @@ async function readHingeAngle( } return Number(match[1]); } - -/** - * An executor may hand back a failed result instead of throwing (the managed scoped transport - * does), so every read checks the exit code itself before trusting stdout: a failed - * `print-states` must be an adb failure, never an empty state list read as a phone. - */ -async function shell( - device: DeviceInfo, - words: readonly string[], - signal: AbortSignal | undefined, -): Promise { - const result = await runAndroidShell(device, words, { signal, allowFailure: true }); - if (result.exitCode !== 0) { - throw androidAdbResultError( - `adb shell ${words.join(' ')} exited with code ${result.exitCode}`, - result, - { deviceId: device.id }, - ); - } - return result; -} diff --git a/packages/platform-android/src/keyguard.ts b/packages/platform-android/src/keyguard.ts new file mode 100644 index 0000000000..66479224e8 --- /dev/null +++ b/packages/platform-android/src/keyguard.ts @@ -0,0 +1,40 @@ +import type { DeviceInfo } from '@agent-device/kernel/device'; + +import { runAndroidShell } from './adb.ts'; +import { androidAdbResultError } from './adb-failure.ts'; +import type { AndroidAdbExecutorResult } from './adb-transport.ts'; + +/** + * Whether the keyguard is up, as `dumpsys window` reports it, or `undefined` when the dump carries + * no `isKeyguardShowing=` line. `fold` reads it to clear a lock screen the cover display raised, + * and `lock-screen` to verify a lock or unlock. + */ +export async function readAndroidKeyguardShowing( + device: DeviceInfo, + signal: AbortSignal | undefined, +): Promise { + const { stdout } = await runCheckedAndroidShell(device, ['dumpsys', 'window'], signal); + const state = /isKeyguardShowing=(true|false)/.exec(stdout)?.[1]; + return state === undefined ? undefined : state === 'true'; +} + +/** + * An executor may hand back a failed result instead of throwing (the managed scoped transport + * does), so every read checks the exit code itself before trusting stdout: a failed dump must be + * an adb failure, never an empty dump read as an unlocked screen or a missing state. + */ +export async function runCheckedAndroidShell( + device: DeviceInfo, + words: readonly string[], + signal: AbortSignal | undefined, +): Promise { + const result = await runAndroidShell(device, words, { signal, allowFailure: true }); + if (result.exitCode !== 0) { + throw androidAdbResultError( + `adb shell ${words.join(' ')} exited with code ${result.exitCode}`, + result, + { deviceId: device.id }, + ); + } + return result; +} diff --git a/packages/platform-android/src/lock-screen.test.ts b/packages/platform-android/src/lock-screen.test.ts new file mode 100644 index 0000000000..1ab28727fb --- /dev/null +++ b/packages/platform-android/src/lock-screen.test.ts @@ -0,0 +1,190 @@ +import { afterEach, beforeEach, expect, test, vi } from 'vitest'; + +vi.mock('./adb.ts', () => ({ runAndroidShell: vi.fn() })); +vi.mock('./input-actions.ts', () => ({ pressAndroidHardwareButton: vi.fn(async () => {}) })); +vi.mock('./permission-grant-state.ts', () => ({ readAndroidCurrentUserId: vi.fn(async () => 0) })); +vi.mock('@agent-device/host-kit/retry', async (importOriginal) => { + const actual = await importOriginal(); + // Each poll advances the faked clock the Deadline reads, so the window ends after its polls. + return { + ...actual, + sleep: vi.fn(async (ms: number) => { + vi.setSystemTime(Date.now() + ms); + }), + }; +}); + +import { runAndroidShell } from './adb.ts'; +import { pressAndroidHardwareButton } from './input-actions.ts'; +import { lockAndroidScreen, unlockAndroidScreen } from './lock-screen.ts'; +import { readAndroidCurrentUserId } from './permission-grant-state.ts'; +import { ANDROID_EMULATOR } from './runtime.fixtures.ts'; + +const mockShell = vi.mocked(runAndroidShell); +const SETTINGS_FOCUS_ONLY = 'mCurrentFocus=Window{42 u0 com.android.settings/.Settings}\n'; +const mockPress = vi.mocked(pressAndroidHardwareButton); +const mockCurrentUser = vi.mocked(readAndroidCurrentUserId); + +/** `dumpsys lock_settings` as Android 16 prints it, one block per user. */ +function lockSettingsDump(users: Record): string { + const blocks = Object.entries(users).map( + ([id, type]) => + ` User ${id}\n LSKF-based SP protector ID: 0000000000000000\n Quality: 0\n CredentialType: ${type}\n SeparateChallenge: false\n`, + ); + return `Current lock settings service state:\n\nUser State:\n${blocks.join('')}\nStorage:\n`; +} + +/** + * One device answered by command: `keyguardReads` are the successive `isKeyguardShowing` values + * (the last repeats), `credentials` the lock_settings blocks per user. + */ +function stubDevice(options: { keyguardReads: boolean[]; credentials?: Record }) { + const reads = [...options.keyguardReads]; + mockShell.mockImplementation(async (_device, words) => { + const command = words.join(' '); + const answer = (stdout: string) => ({ stdout, stderr: '', exitCode: 0 }); + if (command === 'dumpsys window') { + const showing = reads.length > 1 ? reads.shift()! : reads[0]!; + return answer(` isKeyguardShowing=${showing}\n`); + } + if (command === 'dumpsys lock_settings') { + return answer(lockSettingsDump(options.credentials ?? { 0: 'NONE' })); + } + if (command === 'wm dismiss-keyguard') return answer(''); + throw new Error(`unexpected shell command: ${command}`); + }); +} + +function shellCommands(): string[] { + return mockShell.mock.calls.map(([, words]) => words.join(' ')); +} + +function keyguardReads(): number { + return shellCommands().filter((command) => command === 'dumpsys window').length; +} + +beforeEach(() => { + vi.useFakeTimers(); + mockShell.mockReset(); + mockPress.mockClear(); + mockCurrentUser.mockReset(); + mockCurrentUser.mockResolvedValue(0); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +test('lock leaves a keyguard that is already showing alone', async () => { + stubDevice({ keyguardReads: [true] }); + await lockAndroidScreen(ANDROID_EMULATOR, undefined); + expect(mockPress).not.toHaveBeenCalled(); + expect(shellCommands()).toEqual(['dumpsys window']); +}); + +test('lock sends KEYCODE_SLEEP and returns once the keyguard shows', async () => { + stubDevice({ keyguardReads: [false, false, true] }); + await lockAndroidScreen(ANDROID_EMULATOR, undefined); + expect(mockPress.mock.calls.map(([, button]) => button)).toEqual(['sleep']); + expect(keyguardReads()).toBe(3); +}); + +test('lock reads the keyguard once more after the last poll before it reports unverified', async () => { + stubDevice({ keyguardReads: [false] }); + await expect(lockAndroidScreen(ANDROID_EMULATOR, undefined)).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'lock-screen-unverified', dispatched: 'unknown' }, + }); + // One read before the key event, one right after it, then one after each of the 20 polls that + // fit in the 5 s window. + expect(keyguardReads()).toBe(22); +}); + +test('unlock wakes an unlocked screen and dismisses nothing', async () => { + stubDevice({ keyguardReads: [false] }); + await unlockAndroidScreen(ANDROID_EMULATOR, undefined); + expect(mockPress.mock.calls.map(([, button]) => button)).toEqual(['wake']); + expect(shellCommands()).toEqual(['dumpsys window']); +}); + +test('unlock wakes the screen, dismisses a swipe keyguard until it is gone', async () => { + stubDevice({ keyguardReads: [true, true, false] }); + await unlockAndroidScreen(ANDROID_EMULATOR, undefined); + expect(mockPress.mock.calls.map(([, button]) => button)).toEqual(['wake']); + // The poll that still finds the keyguard sends the dismissal again before the next read. + expect(shellCommands()).toEqual([ + 'dumpsys window', + 'dumpsys lock_settings', + 'wm dismiss-keyguard', + 'dumpsys window', + 'wm dismiss-keyguard', + 'dumpsys window', + ]); +}); + +test('unlock refuses a keyguard that asks for a credential before sending anything', async () => { + stubDevice({ keyguardReads: [true], credentials: { 0: 'PIN' } }); + await expect(unlockAndroidScreen(ANDROID_EMULATOR, undefined)).rejects.toMatchObject({ + code: 'UNSUPPORTED_OPERATION', + details: { reason: 'lock-screen-secure', credentialType: 'pin', dispatched: 'no' }, + }); + expect(mockPress).not.toHaveBeenCalled(); + expect(shellCommands()).not.toContain('wm dismiss-keyguard'); +}); + +test('unlock reads the credential of the foreground user', async () => { + mockCurrentUser.mockResolvedValue(10); + stubDevice({ keyguardReads: [true], credentials: { 0: 'NONE', 10: 'PASSWORD' } }); + await expect(unlockAndroidScreen(ANDROID_EMULATOR, undefined)).rejects.toMatchObject({ + details: { reason: 'lock-screen-secure', credentialType: 'password' }, + }); +}); + +test('unlock reads the numeric none of older builds as no credential', async () => { + stubDevice({ keyguardReads: [true, false], credentials: { 0: '-1' } }); + await unlockAndroidScreen(ANDROID_EMULATOR, undefined); + expect(shellCommands()).toContain('wm dismiss-keyguard'); +}); + +test('unlock refuses when the foreground user or its credential type cannot be read', async () => { + mockCurrentUser.mockResolvedValue(undefined); + stubDevice({ keyguardReads: [true] }); + await expect(unlockAndroidScreen(ANDROID_EMULATOR, undefined)).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'lock-screen-state-unreadable', dispatched: 'no' }, + }); + + mockCurrentUser.mockResolvedValue(7); + stubDevice({ keyguardReads: [true], credentials: { 0: 'NONE' } }); + await expect(unlockAndroidScreen(ANDROID_EMULATOR, undefined)).rejects.toMatchObject({ + details: { reason: 'lock-screen-state-unreadable' }, + }); + expect(mockPress).not.toHaveBeenCalled(); +}); + +test('unlock reports unverified when the keyguard stays up after the dismissal', async () => { + stubDevice({ keyguardReads: [true] }); + await expect(unlockAndroidScreen(ANDROID_EMULATOR, undefined)).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'lock-screen-unverified' }, + }); +}); + +test('a dump with no keyguard state refuses before anything is sent', async () => { + mockShell.mockResolvedValue({ stdout: SETTINGS_FOCUS_ONLY, stderr: '', exitCode: 0 }); + for (const run of [lockAndroidScreen, unlockAndroidScreen]) { + await expect(run(ANDROID_EMULATOR, undefined)).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'lock-screen-state-unreadable', dispatched: 'no' }, + }); + } + expect(mockPress).not.toHaveBeenCalled(); +}); + +test('a failed keyguard read is an adb failure, not an unlocked screen', async () => { + mockShell.mockResolvedValue({ stdout: '', stderr: 'error: closed', exitCode: 1 }); + await expect(lockAndroidScreen(ANDROID_EMULATOR, undefined)).rejects.toMatchObject({ + message: expect.stringContaining('dumpsys window'), + }); + expect(mockPress).not.toHaveBeenCalled(); +}); diff --git a/packages/platform-android/src/lock-screen.ts b/packages/platform-android/src/lock-screen.ts new file mode 100644 index 0000000000..c009e22777 --- /dev/null +++ b/packages/platform-android/src/lock-screen.ts @@ -0,0 +1,167 @@ +import { LOCK_SCREEN_REASONS } from '@agent-device/contracts/device'; +import { Deadline, sleep } from '@agent-device/host-kit/retry'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; + +import { pressAndroidHardwareButton } from './input-actions.ts'; +import { readAndroidKeyguardShowing, runCheckedAndroidShell } from './keyguard.ts'; +import { readAndroidCurrentUserId } from './permission-grant-state.ts'; + +/** The Android-only `lock-screen` reasons; the shared ones are in LOCK_SCREEN_REASONS. */ +const ANDROID_LOCK_SCREEN_REASONS = { + // dumpsys reported no keyguard state, or no lock type for the foreground user, so nothing was sent. + stateUnreadable: { reason: 'lock-screen-state-unreadable' }, +} as const satisfies ReasonTable<'lock-screen'>; + +/** How long the keyguard has to reach the requested state after the key event or dismissal. */ +const LOCK_STATE_WINDOW_MS = 5_000; +const LOCK_STATE_POLL_MS = 250; + +const SECURE_LOCK_HINT = + 'unlock never enters a credential. Unlock the device by hand, or remove its screen lock in Settings > Security, then retry.'; +const STATE_UNREADABLE_HINT = + 'Check adb shell dumpsys window, adb shell dumpsys lock_settings, and adb shell am get-current-user; if the device is still booting, retry once it reports a user.'; +const LOCK_UNVERIFIED_HINT = + 'Android raised no keyguard after KEYCODE_SLEEP. A device whose screen lock is set to None has no lock screen to show.'; +const UNLOCK_UNVERIFIED_HINT = + 'The keyguard stayed up after wm dismiss-keyguard. Take a screenshot to see what covers the screen.'; + +/** + * Shows the keyguard with KEYCODE_SLEEP and returns once `dumpsys window` reports it. A keyguard + * already up is left alone. + */ +export async function lockAndroidScreen( + device: DeviceInfo, + signal: AbortSignal | undefined, +): Promise { + if (await readKeyguardBeforeDispatch(device, signal)) return; + await pressAndroidHardwareButton(device, 'sleep'); + await awaitKeyguardState(device, true, signal); +} + +/** + * Wakes the screen with KEYCODE_WAKEUP and dismisses the keyguard with `wm dismiss-keyguard`, so + * the app that was in front before the lock is in front again. A keyguard that asks for a + * credential is refused before anything is sent: nothing here types a PIN, pattern, or password. + */ +export async function unlockAndroidScreen( + device: DeviceInfo, + signal: AbortSignal | undefined, +): Promise { + const showing = await readKeyguardBeforeDispatch(device, signal); + if (showing) await refuseSecureLock(device, signal); + // The wake event never toggles, so a screen that is already on stays on. + await pressAndroidHardwareButton(device, 'wake'); + if (!showing) return; + const dismiss = async () => { + await runCheckedAndroidShell(device, ['wm', 'dismiss-keyguard'], signal); + }; + await dismiss(); + // A dismissal that lands while the screen is still waking can be dropped, so each poll that + // still finds the keyguard sends it again; a secure keyguard was refused above. + await awaitKeyguardState(device, false, signal, dismiss); +} + +/** The keyguard state before anything is sent; a dump without one refuses instead of guessing. */ +async function readKeyguardBeforeDispatch( + device: DeviceInfo, + signal: AbortSignal | undefined, +): Promise { + const showing = await readAndroidKeyguardShowing(device, signal); + if (showing === undefined) throw stateUnreadable(device, 'the keyguard state'); + return showing; +} + +/** + * Polls until the keyguard reaches `showing`. The window starts after the dispatch returned, and + * every wait is followed by a read, so a state the device reached during the last wait is seen. + * `retry` runs after each wait that follows a read in the wrong state. + */ +async function awaitKeyguardState( + device: DeviceInfo, + showing: boolean, + signal: AbortSignal | undefined, + retry?: () => Promise, +): Promise { + const deadline = Deadline.fromTimeoutMs(LOCK_STATE_WINDOW_MS); + while ((await readAndroidKeyguardShowing(device, signal)) !== showing) { + if (deadline.isExpired()) { + throw new AppError( + 'COMMAND_FAILED', + `${device.name} still reports the keyguard ${showing ? 'hidden' : 'showing'}`, + { + deviceId: device.id, + reason: LOCK_SCREEN_REASONS.stateUnverified.reason, + dispatched: 'unknown', + hint: showing ? LOCK_UNVERIFIED_HINT : UNLOCK_UNVERIFIED_HINT, + }, + ); + } + await sleep(LOCK_STATE_POLL_MS, signal); + await retry?.(); + } +} + +async function refuseSecureLock( + device: DeviceInfo, + signal: AbortSignal | undefined, +): Promise { + const credential = await readCredentialType(device, signal); + if (credential === 'none') return; + if (credential === undefined) { + throw stateUnreadable(device, 'the screen lock type of the foreground user'); + } + throw new AppError( + 'UNSUPPORTED_OPERATION', + `The screen lock of ${device.name} asks for a credential (${credential}), which lock-screen unlock does not enter`, + { + deviceId: device.id, + reason: LOCK_SCREEN_REASONS.secureLock.reason, + credentialType: credential, + dispatched: 'no', + hint: SECURE_LOCK_HINT, + }, + ); +} + +function stateUnreadable(device: DeviceInfo, what: string): AppError { + return new AppError('COMMAND_FAILED', `Unable to read ${what} of ${device.name}`, { + deviceId: device.id, + reason: ANDROID_LOCK_SCREEN_REASONS.stateUnreadable.reason, + dispatched: 'no', + hint: STATE_UNREADABLE_HINT, + }); +} + +/** + * The foreground user's credential type from `dumpsys lock_settings`, lower-cased (`none`, `pin`, + * `pattern`, `password`), or `undefined` when the user or its `CredentialType:` line is missing. + * Builds that print the type as a number report it unchanged, except -1, which is none. + */ +async function readCredentialType( + device: DeviceInfo, + signal: AbortSignal | undefined, +): Promise { + const userId = await readAndroidCurrentUserId(device); + if (userId === undefined) return undefined; + const { stdout } = await runCheckedAndroidShell(device, ['dumpsys', 'lock_settings'], signal); + const type = credentialTypeForUser(stdout, userId); + if (type === undefined) return undefined; + return type === '-1' ? 'none' : type.toLowerCase(); +} + +/** The `CredentialType:` value inside the `User ` block of a `dumpsys lock_settings` dump. */ +function credentialTypeForUser(dump: string, userId: number): string | undefined { + let inUser = false; + for (const line of dump.split('\n')) { + const user = /^\s*User (\d+)\s*$/.exec(line); + if (user) { + inUser = Number(user[1]) === userId; + continue; + } + if (!inUser) continue; + const type = /^\s*CredentialType:\s*(\S+)/.exec(line); + if (type) return type[1]; + } + return undefined; +} diff --git a/packages/platform-android/src/mechanics.ts b/packages/platform-android/src/mechanics.ts index 98fb3f758d..6ff992e397 100644 --- a/packages/platform-android/src/mechanics.ts +++ b/packages/platform-android/src/mechanics.ts @@ -402,3 +402,21 @@ export async function shakeAndroidEmulator( const { shakeAndroidEmulator: shake } = await import('./shake/console-shake.ts'); await shake(device, signal); } + +/** Deferred to keep this entry's eager closure within scripts/__tests__/eager-closure-budgets.test.ts. */ +export async function lockAndroidScreen( + device: DeviceInfo, + signal: AbortSignal | undefined, +): Promise { + const { lockAndroidScreen: lock } = await import('./lock-screen.ts'); + await lock(device, signal); +} + +/** Deferred like {@link lockAndroidScreen}. */ +export async function unlockAndroidScreen( + device: DeviceInfo, + signal: AbortSignal | undefined, +): Promise { + const { unlockAndroidScreen: unlock } = await import('./lock-screen.ts'); + await unlock(device, signal); +} diff --git a/packages/platform-android/src/runtime.test.ts b/packages/platform-android/src/runtime.test.ts index 6b9b5f98c7..c998040b9b 100644 --- a/packages/platform-android/src/runtime.test.ts +++ b/packages/platform-android/src/runtime.test.ts @@ -245,6 +245,39 @@ test('Android admits the hardware-button facts on phones and tablets and refuses } }); +test('Android admits the lock-screen facts on phones and tablets and refuses a TV target', async () => { + const cells = ['lockScreen', 'unlockScreen'] as const; + for (const runtimeDevice of [ + ANDROID_EMULATOR, + { ...ANDROID_EMULATOR, kind: 'device' as const }, + UNKNOWN_KIND_DEVICE, + ]) { + const binding = await bindOrdinary( + createAndroidPlatformRuntime(androidNavigationHost()), + runtimeDevice, + ); + for (const operation of cells) { + expect(binding.facts.operations[operation]).toEqual({ available: true }); + expect(binding.operations[operation]).toBeTypeOf('function'); + } + } + + const refusals = [ + [{ ...ANDROID_EMULATOR, target: 'tv' as const }, 'unsupported-platform-leaf'], + [{ ...ANDROID_EMULATOR, kind: 'simulator' as const }, 'unsupported-device-kind'], + ] as const; + for (const [runtimeDevice, reason] of refusals) { + const binding = await bindOrdinary( + createAndroidPlatformRuntime(androidNavigationHost()), + runtimeDevice, + ); + for (const operation of cells) { + expect(binding.facts.operations[operation]).toMatchObject({ available: false, reason }); + expect(binding.operations[operation]).toBeUndefined(); + } + } +}); + test('admits Android tv-remote only for a real TV target', async () => { const tvDevice = { ...ANDROID_EMULATOR, kind: 'emulator' as const, target: 'tv' as const }; const binding = await bindOrdinary( diff --git a/packages/platform-android/src/runtime.ts b/packages/platform-android/src/runtime.ts index 1cbaca0de4..7fb351b461 100644 --- a/packages/platform-android/src/runtime.ts +++ b/packages/platform-android/src/runtime.ts @@ -120,6 +120,19 @@ function androidShakeFact(device: DeviceInfo): RuntimeOperationFact { if (device.kind !== 'emulator') return shakeKindUnavailable; return device.target === 'tv' ? shakeTvUnavailable : available; } +const lockScreenKindUnavailable = unavailableFact( + PLATFORM_RUNTIME_REASONS.unsupportedDeviceKind.reason, + 'lock-screen is supported on Android emulators and physical devices.', +); +/** An Android TV image shows no keyguard, so there is no lock state to verify. */ +const lockScreenTvUnavailable = unavailableFact( + PLATFORM_RUNTIME_REASONS.unsupportedPlatformLeaf.reason, + 'lock-screen is supported on Android phones and tablets only.', +); +function androidLockScreenFact(device: DeviceInfo): RuntimeOperationFact { + if (device.kind === 'simulator') return lockScreenKindUnavailable; + return device.target === 'tv' ? lockScreenTvUnavailable : available; +} const headlessUnavailable = unavailableFact( PLATFORM_RUNTIME_REASONS.unsupportedDeviceKind.reason, 'Headless boot is supported only for Android emulators.', @@ -375,6 +388,8 @@ export function createAndroidPlatformRuntime(host: PlatformRuntimeHost): Platfor home: androidTouchFact(device), appSwitcher: androidTouchFact(device), shake: androidShakeFact(device), + lockScreen: androidLockScreenFact(device), + unlockScreen: androidLockScreenFact(device), ...androidHardwareButtonFacts(device), }), ...androidFoldableFacts(device), 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 e5dc2d336b..bbd326cd7d 100644 --- a/packages/platform-apple/src/__tests__/index-runner-requests.test.ts +++ b/packages/platform-apple/src/__tests__/index-runner-requests.test.ts @@ -190,6 +190,8 @@ const INTERACTOR_SITES: Record = { 'ios-simulator.interactor-app-switcher.open': [IOS_SIMULATOR, (i) => i.appSwitcher!()], 'ios-simulator.interactor-action-button.press': [IOS_SIMULATOR, (i) => i.actionButton!()], 'ios-simulator.interactor-volume-up.press': [IOS_SIMULATOR, (i) => i.volumeUp!()], + 'ios-simulator.interactor-lock-screen.lock': [IOS_SIMULATOR, (i) => i.lockScreen!()], + 'ios-simulator.interactor-unlock-screen.unlock': [IOS_SIMULATOR, (i) => i.unlockScreen!()], 'ios-simulator.interactor-volume-down.press': [IOS_SIMULATOR, (i) => i.volumeDown!()], 'tvos.interactor-tv-remote.hold': [TVOS_SIMULATOR, (i) => i.tvRemote!('select', 500)], 'ios-simulator.interactor-keyboard-dismiss.dismiss': [IOS_SIMULATOR, (i) => i.keyboardDismiss!()], diff --git a/packages/platform-apple/src/__tests__/interactor-runner-provider.test.ts b/packages/platform-apple/src/__tests__/interactor-runner-provider.test.ts index c1aa877ff9..83b45a42a7 100644 --- a/packages/platform-apple/src/__tests__/interactor-runner-provider.test.ts +++ b/packages/platform-apple/src/__tests__/interactor-runner-provider.test.ts @@ -81,6 +81,8 @@ const RUNNER_TRANSPORT_METHODS: Record< actionButton: { invoke: (i) => i.actionButton!(), runnerCommand: 'actionButton' }, volumeUp: { invoke: (i) => i.volumeUp!(), runnerCommand: 'volumeUp' }, volumeDown: { invoke: (i) => i.volumeDown!(), runnerCommand: 'volumeDown' }, + lockScreen: { invoke: (i) => i.lockScreen!(), runnerCommand: 'lockScreen' }, + unlockScreen: { invoke: (i) => i.unlockScreen!(), runnerCommand: 'unlockScreen' }, tvRemote: { invoke: (i) => i.tvRemote!('select'), runnerCommand: 'remotePress' }, keyboardDismiss: { invoke: (i) => i.keyboardDismiss!(), runnerCommand: 'keyboardDismiss' }, keyboardEnter: { invoke: (i) => i.keyboardEnter!(), runnerCommand: 'keyboardReturn' }, diff --git a/packages/platform-apple/src/interactor.ts b/packages/platform-apple/src/interactor.ts index 1a6fc51624..1a5d6de34b 100644 --- a/packages/platform-apple/src/interactor.ts +++ b/packages/platform-apple/src/interactor.ts @@ -193,6 +193,20 @@ export function createAppleInteractor( ); }, shake: () => shakeIosSimulator(device, runnerOpts.signal), + lockScreen: async () => { + await runAppleRunnerCommand( + device, + { command: 'lockScreen', appBundleId: runnerContext.appBundleId }, + runnerOpts, + ); + }, + unlockScreen: async () => { + await runAppleRunnerCommand( + device, + { command: 'unlockScreen', appBundleId: runnerContext.appBundleId }, + runnerOpts, + ); + }, // Volume presses reach the runner only on physical iPhone/iPad; the facts refuse every other // kind, and Apple exposes no power press at all, so no `power` member exists here. volumeUp: async () => { diff --git a/packages/platform-apple/src/navigation/runtime.ts b/packages/platform-apple/src/navigation/runtime.ts index 340d642c1b..77babd0aa3 100644 --- a/packages/platform-apple/src/navigation/runtime.ts +++ b/packages/platform-apple/src/navigation/runtime.ts @@ -208,6 +208,25 @@ function appleShakeFact(device: DeviceInfo): RuntimeOperationFact { return device.kind === 'simulator' ? available : shakeKindUnavailable; } +const lockScreenKindUnavailable = Object.freeze({ + available: false, + reason: PLATFORM_RUNTIME_REASONS.unsupportedDeviceKind.reason, + hint: 'lock-screen is supported on iPhone and iPad simulators only.', +} as const); +const lockScreenOsUnavailable = Object.freeze({ + available: false, + reason: PLATFORM_RUNTIME_REASONS.unsupportedPlatformLeaf.reason, + hint: 'lock-screen is supported on iPhone and iPad simulators and Android phones and tablets only.', +} as const); +/** + * The runner locks through XCUIDevice's private lock button and verifies SpringBoard's lock + * state. Only the iPhone and iPad simulator leaf is admitted: no physical device run backs it. + */ +function appleLockScreenFact(device: DeviceInfo): RuntimeOperationFact { + if (!isHandheldAppleDevice(device)) return lockScreenOsUnavailable; + return device.kind === 'simulator' ? available : lockScreenKindUnavailable; +} + const volumeButtonOsUnavailable = Object.freeze({ available: false, reason: PLATFORM_RUNTIME_REASONS.unsupportedPlatformLeaf.reason, @@ -231,8 +250,8 @@ function appleVolumeButtonFact(device: DeviceInfo): RuntimeOperationFact { } /** - * The navigation cells: back, home, app-switcher, action-button, shake, orientation, tv-remote, and - * keyboard status/dismiss/enter. + * The navigation cells: back, home, app-switcher, action-button, shake, lock-screen, orientation, + * tv-remote, and keyboard status/dismiss/enter. */ export function appleNavigationFacts(device: DeviceInfo) { return Object.freeze({ @@ -243,6 +262,8 @@ export function appleNavigationFacts(device: DeviceInfo) { appSwitcher: appleSpringboardFact(device, appSwitcherKindUnavailable), actionButton: appleActionButtonFact(device), shake: appleShakeFact(device), + lockScreen: appleLockScreenFact(device), + unlockScreen: appleLockScreenFact(device), // Power is the family denial: Apple exposes no public power/lock button press to XCUITest, // on any kind or OS, so no cell overrides it. volumeUp: appleVolumeButtonFact(device), diff --git a/packages/platform-apple/src/runner-demand.ts b/packages/platform-apple/src/runner-demand.ts index 44f7aee9b6..3f0655eca5 100644 --- a/packages/platform-apple/src/runner-demand.ts +++ b/packages/platform-apple/src/runner-demand.ts @@ -102,6 +102,8 @@ const APPLE_SIMULATOR_OPERATION_HOSTS: Readonly< setOrientation: 'runner', appSwitcher: 'runner', actionButton: 'runner', + lockScreen: 'runner', + unlockScreen: 'runner', tvRemote: 'runner', keyboardDismiss: 'runner', keyboardEnter: 'runner', diff --git a/packages/platform-apple/src/runtime.test.ts b/packages/platform-apple/src/runtime.test.ts index 24909ce1e7..1527a40159 100644 --- a/packages/platform-apple/src/runtime.test.ts +++ b/packages/platform-apple/src/runtime.test.ts @@ -399,6 +399,35 @@ test.each([ }, ); +// The runner locks through XCUIDevice's simulator-only lock button, so the iPhone and iPad +// simulator leaf is the only one admitted. A physical iPhone or iPad hears the kind refusal; every +// other OS hears the leaf refusal, whichever kind it runs as. +test.each([ + ...Object.entries(leavesWithoutWatch).map( + ([name, device]) => + [name, device, name === 'ios' || name === 'ipados' ? 'available' : 'leaf'] as const, + ), + ['ios physical device', appleDevice({ kind: 'device' }), 'kind'] as const, + ['ipados physical device', appleDevice({ kind: 'device', appleOs: 'ipados' }), 'kind'] as const, +])('classifies the lock-screen facts for the %s leaf', async (_name, device, verdict) => { + const binding = await createApplePlatformRuntime(platformRuntimeHostFixture()).bind({ + device, + intent: { kind: 'ordinary' }, + scope: { + signal: new AbortController().signal, + diagnostics: { emit: () => {} }, + progress: { report: () => {} }, + }, + }); + for (const operation of ['lockScreen', 'unlockScreen'] as const) { + expectOperationAvailability(binding, operation, verdict === 'available'); + if (verdict === 'available') continue; + expect(binding.facts.operations[operation]).toMatchObject({ + reason: verdict === 'kind' ? 'unsupported-device-kind' : 'unsupported-platform-leaf', + }); + } +}); + test.each(Object.entries(leavesWithoutWatch))( 'classifies the fold fact for the %s leaf', async (_name, device) => { diff --git a/packages/platform-linux/src/runtime.test.ts b/packages/platform-linux/src/runtime.test.ts index 2b9a041bc2..84d9767692 100644 --- a/packages/platform-linux/src/runtime.test.ts +++ b/packages/platform-linux/src/runtime.test.ts @@ -222,6 +222,8 @@ function expectLinuxNavigationAndKeyboardFacts( // and neither does it have the phone volume and power keys hardware-button presses (#3848). 'actionButton', 'shake', + 'lockScreen', + 'unlockScreen', 'volumeUp', 'volumeDown', 'power', diff --git a/packages/platform-web/src/runtime.test.ts b/packages/platform-web/src/runtime.test.ts index 3ed9bd1ea0..527700afca 100644 --- a/packages/platform-web/src/runtime.test.ts +++ b/packages/platform-web/src/runtime.test.ts @@ -216,6 +216,8 @@ test('clipboard, the app switcher, app events, settings and alerts carry no web // phone volume and power keys the hardware-button command presses (#3848). 'actionButton', 'shake', + 'lockScreen', + 'unlockScreen', 'volumeUp', 'volumeDown', 'power', diff --git a/packages/provider-revyl/src/facts-runtime.test.ts b/packages/provider-revyl/src/facts-runtime.test.ts index 36dcee226a..bba1fc356f 100644 --- a/packages/provider-revyl/src/facts-runtime.test.ts +++ b/packages/provider-revyl/src/facts-runtime.test.ts @@ -77,6 +77,7 @@ const EXPECTED_CELLS = { keyboardEnter: 'mode', keyboardStatus: 'mode', listApps: 'mode', + lockScreen: 'mode', materializeAppSource: 'available', mediaFastForward: 'mode', mediaNext: 'mode', @@ -121,6 +122,7 @@ const EXPECTED_CELLS = { typeText: 'mode', uninstallApp: 'mode', unlockOrientation: 'mode', + unlockScreen: 'mode', volumeDown: 'mode', volumeUp: 'mode', wake: 'mode', diff --git a/packages/session-journal/src/__tests__/session-event-action.test.ts b/packages/session-journal/src/__tests__/session-event-action.test.ts index d1bbd700af..db9758a0db 100644 --- a/packages/session-journal/src/__tests__/session-event-action.test.ts +++ b/packages/session-journal/src/__tests__/session-event-action.test.ts @@ -333,6 +333,17 @@ test('record and trace events expose only bounded artifact basenames', () => { }); }); +test('lock-screen action events name the verified lock state', () => { + const lock = action('lock-screen', { action: 'lock-screen', state: 'locked' }); + assert.equal(buildActionSummary(lock), 'Locked the screen'); + assert.equal( + buildActionSummary(action('lock-screen', { action: 'lock-screen', state: 'unlocked' })), + 'Unlocked the screen', + ); + assert.equal(buildActionSummary(action('lock-screen', {})), 'Changed the lock screen'); + assert.deepEqual(buildActionDetails(lock), { command: 'lock-screen', state: 'locked' }); +}); + test('telephony action events name the simulated event and carry neither number nor text', () => { const sms = action( 'telephony', diff --git a/packages/session-journal/src/session-event-action-presentation.ts b/packages/session-journal/src/session-event-action-presentation.ts index 145d59718b..cdd3bf33d1 100644 --- a/packages/session-journal/src/session-event-action-presentation.ts +++ b/packages/session-journal/src/session-event-action-presentation.ts @@ -23,6 +23,7 @@ import type { DaemonRequest } from '@agent-device/kernel/contracts'; const SCROLL_DIRECTIONS = ['up', 'down', 'left', 'right'] as const; const SCROLL_EDGES = ['top', 'bottom'] as const; +const LOCK_SCREEN_STATES = ['locked', 'unlocked'] as const; export function buildInstallActionSummary(action: SessionAction): string { const verb = action.command === PUBLIC_COMMANDS.reinstall ? 'Reinstalled' : 'Installed'; @@ -51,6 +52,8 @@ export function buildStructuredActionSummary(action: SessionAction): string | un return buildBackActionSummary(result); case PUBLIC_COMMANDS.hardwareButton: return buildHardwareButtonActionSummary(result); + case PUBLIC_COMMANDS.lockScreen: + return buildLockScreenActionSummary(result); case PUBLIC_COMMANDS.orientation: return buildOrientationActionSummary(result); case PUBLIC_COMMANDS.fold: @@ -122,6 +125,8 @@ export function buildStructuredActionDetails(action: SessionAction): Record): stri return button === undefined ? 'Pressed hardware button' : `Pressed hardware button ${button}`; } +function buildLockScreenActionSummary(result: Record): string { + const state = readEnum(result.state, LOCK_SCREEN_STATES); + if (state === undefined) return 'Changed the lock screen'; + return state === 'locked' ? 'Locked the screen' : 'Unlocked the screen'; +} + function buildTvRemoteActionSummary(result: Record): string { const button = isTvRemoteButton(result.button) ? result.button : undefined; return button ? `Pressed TV remote ${button}` : 'Used TV remote'; diff --git a/scripts/capability-matrix/annotations.ts b/scripts/capability-matrix/annotations.ts index 554899a3b7..dec9d911cd 100644 --- a/scripts/capability-matrix/annotations.ts +++ b/scripts/capability-matrix/annotations.ts @@ -491,6 +491,13 @@ export const MATRIX_SECTIONS: readonly MatrixSection[] = [ commands: ['shake'], link: docs('commands', 'navigation'), }, + { + id: 'lock-screen', + label: 'Lock screen', + commands: ['lock-screen'], + link: docs('commands', 'navigation'), + note: 'Unlock refuses a lock that asks for a PIN, pattern, password, or passcode.', + }, { id: 'fold', label: 'Foldable pose', diff --git a/scripts/perf/README.md b/scripts/perf/README.md index 6c6d912013..0d1f172ece 100644 --- a/scripts/perf/README.md +++ b/scripts/perf/README.md @@ -60,6 +60,7 @@ Some shared steps use other screen coordinates or waits on Android. The `on.andr | `push` | Not timed: the fixture has no notification authorization. | lifecycle (adb broadcast) | | `telephony` | Not timed: the simulator refuses calls and SMS. | lifecycle (`telephony sms`) | | `shake` | Not timed: the fixture handles no shake. | Same reason. | +| `lock-screen` | Not timed: a locked screen covers the fixture for every step after it. | Same reason. | | `snapshot` | home-reads: `snapshot-forced-tree` | heavy-feed: `snapshot-raw-one-shot` | | `audio` | Not timed: hosted runners grant no macOS audio permission. | Not timed: the Linux runner has no ScreenCaptureKit. | | `fold` | Not timed: iPhone Duo only. | Not timed: foldable emulators only. | diff --git a/scripts/perf/suite.ts b/scripts/perf/suite.ts index 83d3805dbe..10418a2b41 100644 --- a/scripts/perf/suite.ts +++ b/scripts/perf/suite.ts @@ -450,6 +450,7 @@ export const SUITE_EXCLUSIONS: Record = { actionButton: { command: 'action-button' }, volumeUp: { command: 'hardware-button', positionals: ['volume-up'] }, volumeDown: { command: 'hardware-button', positionals: ['volume-down'] }, + lockScreen: { command: 'lock-screen', positionals: ['lock'] }, + unlockScreen: { command: 'lock-screen', positionals: ['unlock'] }, keyboardDismiss: { command: 'keyboard', positionals: ['dismiss'] }, keyboardReturn: { command: 'keyboard', positionals: ['enter'] }, // The new runner read pairs with the registry's own read leg, so the parity check below compares diff --git a/src/commands/replay/replay-script.fixtures.ts b/src/commands/replay/replay-script.fixtures.ts index 94c569da75..0787037368 100644 --- a/src/commands/replay/replay-script.fixtures.ts +++ b/src/commands/replay/replay-script.fixtures.ts @@ -182,6 +182,7 @@ const REPLAY_SCRIPT_LINE_PLANS = { 'trigger-app-event': GENERIC_REPLAY_LINE, 'tv-remote': GENERIC_REPLAY_LINE, 'hardware-button': GENERIC_REPLAY_LINE, + 'lock-screen': GENERIC_REPLAY_LINE, uninstall: GENERIC_REPLAY_LINE, viewport: GENERIC_REPLAY_LINE, audit: { waived: 'audit reports one observation and is never recorded in replay scripts' }, diff --git a/src/core/interactors/android.ts b/src/core/interactors/android.ts index 2008359b62..69d2f6dc44 100644 --- a/src/core/interactors/android.ts +++ b/src/core/interactors/android.ts @@ -28,6 +28,8 @@ import { readAndroidSetting, setAndroidSetting, shakeAndroidEmulator, + lockAndroidScreen, + unlockAndroidScreen, snapshotAndroid, typeAndroid, withAndroidAdbProvider, @@ -130,6 +132,8 @@ export function createAndroidInteractor( unlockOrientation: () => unlockAndroidOrientation(device), appSwitcher: () => appSwitcherAndroid(device), shake: () => shakeAndroidEmulator(device, runnerContext?.signal), + lockScreen: () => lockAndroidScreen(device, runnerContext?.signal), + unlockScreen: () => unlockAndroidScreen(device, runnerContext?.signal), volumeUp: () => pressAndroidHardwareButton(device, 'volumeUp'), volumeDown: () => pressAndroidHardwareButton(device, 'volumeDown'), power: () => pressAndroidHardwareButton(device, 'power'), diff --git a/test/integration/command-coverage/declarations.ts b/test/integration/command-coverage/declarations.ts index d609c0ae76..bb2a860647 100644 --- a/test/integration/command-coverage/declarations.ts +++ b/test/integration/command-coverage/declarations.ts @@ -20,6 +20,7 @@ import { ANDROID_HOVER_RUNTIME_CONTRACT_EVIDENCE, ANDROID_INSTALL_SOURCE_CONTRACT_EVIDENCE, ANDROID_LIFECYCLE_CONTRACT_EVIDENCE, + ANDROID_LOCK_SCREEN_CONTRACT_EVIDENCE, ANDROID_SHAKE_RUNTIME_CONTRACT_EVIDENCE, ANDROID_TELEPHONY_RUNTIME_CONTRACT_EVIDENCE, ANDROID_TV_REMOTE_RUNTIME_CONTRACT_EVIDENCE, @@ -28,6 +29,7 @@ import { APPLE_ACTION_BUTTON_FACT_EVIDENCE, APPLE_HARDWARE_BUTTON_FACT_EVIDENCE, APPLE_HOVER_DENIAL_EVIDENCE, + APPLE_LOCK_SCREEN_FACT_EVIDENCE, APPLE_NAVIGATION_FACTS_EVIDENCE, APPLE_SHAKE_FACT_EVIDENCE, LINUX_HOVER_DENIAL_EVIDENCE, @@ -1493,6 +1495,37 @@ const COMMAND_COVERAGE_DECLARATIONS = { 'the exact-owner runtime fact refuses a hardware-button press on every Linux leaf', ), }, + [C.lockScreen]: { + androidEmulator: androidEmulator.contract( + ANDROID_LOCK_SCREEN_CONTRACT_EVIDENCE, + 'the Android emulator locks with KEYCODE_SLEEP, unlocks with KEYCODE_WAKEUP and wm dismiss-keyguard, and refuses a PIN lock before sending anything', + ), + iosSimulator: iosSimulator.contract( + 'test/integration/provider-scenarios/ios-lock-screen.test.ts', + 'Provider-backed integration iOS lock-screen sends lockScreen and unlockScreen to the runner without activating the app', + 'the iOS simulator leaf sends the lock and unlock runner commands without activating the session app', + ), + macos: macos.contract( + APPLE_LOCK_SCREEN_FACT_EVIDENCE.path, + APPLE_LOCK_SCREEN_FACT_EVIDENCE.test, + 'the exact-owner runtime fact refuses lock-screen on the macOS host leaf', + ), + tvos: tvos.contract( + APPLE_LOCK_SCREEN_FACT_EVIDENCE.path, + APPLE_LOCK_SCREEN_FACT_EVIDENCE.test, + 'the exact-owner runtime fact refuses lock-screen on the tvOS leaf', + ), + web: web.contract( + WEB_SYSTEM_SURFACE_DENIAL_EVIDENCE.path, + WEB_SYSTEM_SURFACE_DENIAL_EVIDENCE.test, + 'the exact-owner runtime fact refuses lock-screen on the web target', + ), + linux: linux.contract( + LINUX_RUNTIME_EVIDENCE.path, + LINUX_RUNTIME_EVIDENCE.test, + 'the exact-owner runtime fact refuses lock-screen on the Linux desktop', + ), + }, [C.fold]: { androidEmulator: androidEmulator.contract( ANDROID_FOLD_RUNTIME_CONTRACT_EVIDENCE, diff --git a/test/integration/command-coverage/evidence.ts b/test/integration/command-coverage/evidence.ts index 756a91d6bb..f19794205c 100644 --- a/test/integration/command-coverage/evidence.ts +++ b/test/integration/command-coverage/evidence.ts @@ -67,6 +67,12 @@ export const ANDROID_SHAKE_RUNTIME_CONTRACT_EVIDENCE: AndroidContractEvidence = [C.shake], 'Android admits the shake fact on emulators and refuses every other kind', ); +export const ANDROID_LOCK_SCREEN_CONTRACT_EVIDENCE: AndroidContractEvidence = + defineAndroidContractEvidence( + 'test/integration/provider-scenarios/android-lock-screen.test.ts', + [C.lockScreen], + 'Provider-backed integration Android lock-screen locks and unlocks a swipe keyguard and records both commands', + ); export const ANDROID_FOLD_RUNTIME_CONTRACT_EVIDENCE: AndroidContractEvidence = defineAndroidContractEvidence( 'packages/platform-android/src/runtime.test.ts', @@ -127,6 +133,10 @@ export const APPLE_SHAKE_FACT_EVIDENCE: RepositoryEvidence = { path: 'packages/platform-apple/src/navigation/shake.test.ts', test: 'classifies the shake fact for the %s leaf', }; +export const APPLE_LOCK_SCREEN_FACT_EVIDENCE: RepositoryEvidence = { + path: 'packages/platform-apple/src/runtime.test.ts', + test: 'classifies the lock-screen facts for the %s leaf', +}; export const APPLE_HARDWARE_BUTTON_FACT_EVIDENCE: RepositoryEvidence = { path: 'packages/platform-apple/src/runtime.test.ts', test: 'classifies the hardware-button volume facts for the %s leaf', diff --git a/test/integration/provider-scenarios/android-lock-screen.test.ts b/test/integration/provider-scenarios/android-lock-screen.test.ts new file mode 100644 index 0000000000..d65b5e8f32 --- /dev/null +++ b/test/integration/provider-scenarios/android-lock-screen.test.ts @@ -0,0 +1,151 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { test } from 'vitest'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { parseReplayScriptDetailed } from '@agent-device/ad-script'; +import { assertRpcError } from './assertions.ts'; +import { createAndroidSettingsWorld } from './android-world.ts'; + +const SETTINGS_FOCUS = 'mCurrentFocus=Window{42 u0 com.android.settings/.Settings}\n'; +const KEYCODE_SLEEP = '223'; +const KEYCODE_WAKEUP = '224'; + +/** + * An emulator whose keyguard follows the key events and dismissals it is sent, the way a swipe + * lock does: KEYCODE_SLEEP raises it and `wm dismiss-keyguard` clears it. `credential` is the + * foreground user's lock type in `dumpsys lock_settings`. + */ +function keyguardDevice(credential = 'NONE') { + let showing = false; + const answer = (stdout: string) => ({ stdout, stderr: '', exitCode: 0 }); + return (args: readonly string[]) => { + const command = args.join(' '); + if (command === 'shell dumpsys window') { + return answer(`${SETTINGS_FOCUS} isKeyguardShowing=${showing}\n`); + } + if (command === `shell input keyevent ${KEYCODE_SLEEP}`) { + showing = true; + return answer(''); + } + if (command === 'shell wm dismiss-keyguard') { + showing = false; + return answer(''); + } + if (command === 'shell dumpsys lock_settings') { + return answer(`User State:\n User 0\n CredentialType: ${credential}\n`); + } + return undefined; + }; +} + +function lockScreenShellCalls(calls: readonly string[][]): string[] { + return calls + .map((call) => call.join(' ')) + .filter( + (call) => + call.startsWith('shell input keyevent') || + call === 'shell wm dismiss-keyguard' || + call === 'shell dumpsys lock_settings', + ); +} + +test('Provider-backed integration Android lock-screen locks and unlocks a swipe keyguard and records both commands', async () => { + const world = await createAndroidSettingsWorld({ onAdbExec: keyguardDevice() }); + + try { + const client = world.daemon.client(); + await client.apps.open({ app: 'settings', ...world.selection, saveScript: true }); + world.adbCalls.splice(0); + + assert.deepEqual(await client.command.lockScreen({ action: 'lock', ...world.selection }), { + action: 'lock-screen', + state: 'locked', + message: 'Locked the screen', + }); + assert.deepEqual(await client.command.lockScreen({ action: 'unlock', ...world.selection }), { + action: 'lock-screen', + state: 'unlocked', + message: 'Unlocked the screen', + }); + assert.deepEqual(lockScreenShellCalls(world.adbCalls), [ + `shell input keyevent ${KEYCODE_SLEEP}`, + 'shell dumpsys lock_settings', + `shell input keyevent ${KEYCODE_WAKEUP}`, + 'shell wm dismiss-keyguard', + ]); + + // A screen already locked is left alone: nothing is sent. + await client.command.lockScreen({ action: 'lock', ...world.selection }); + world.adbCalls.splice(0); + await client.command.lockScreen({ action: 'lock', ...world.selection }); + assert.deepEqual(lockScreenShellCalls(world.adbCalls), []); + + await client.command.lockScreen({ action: 'unlock', ...world.selection }); + await client.command.wait({ selector: 'label="Apps"', ...world.selection }); + const published = await client.sessions.saveScript({ + path: path.join(world.tempRoot, 'lock-screen.ad'), + }); + const actions = parseReplayScriptDetailed( + fs.readFileSync(published.savedScript, 'utf8'), + ).actions.filter((action) => action.command === 'lock-screen'); + assert.deepEqual( + actions.map((action) => action.positionals), + [['lock'], ['unlock'], ['lock'], ['lock'], ['unlock']], + ); + } finally { + await world.close(); + } +}); + +test('Provider-backed integration Android lock-screen unlock refuses a PIN lock before sending anything', async () => { + const world = await createAndroidSettingsWorld({ onAdbExec: keyguardDevice('PIN') }); + + try { + await world.daemon.client().apps.open({ app: 'settings', ...world.selection }); + assert.ok( + await world.daemon.client().command.lockScreen({ action: 'lock', ...world.selection }), + ); + world.adbCalls.splice(0); + + const data = assertRpcError( + await world.daemon.callCommand('lock-screen', ['unlock'], world.selection), + 500, + 'UNSUPPORTED_OPERATION', + /asks for a credential \(pin\)/, + ); + const details = data.details as Record; + assert.equal(details.reason, 'lock-screen-secure'); + assert.equal(details.dispatched, 'no'); + assert.deepEqual(lockScreenShellCalls(world.adbCalls), ['shell dumpsys lock_settings']); + } finally { + await world.close(); + } +}); + +test('Provider-backed integration Android lock-screen refuses an Android TV target before adb', async () => { + const tv: DeviceInfo = { + platform: 'android', + id: 'emulator-5556', + name: 'Android TV', + kind: 'emulator', + target: 'tv', + booted: true, + }; + const world = await createAndroidSettingsWorld({ device: tv, onAdbExec: keyguardDevice() }); + + try { + await world.daemon.client().apps.open({ app: 'settings', ...world.selection }); + world.adbCalls.splice(0); + const data = assertRpcError( + await world.daemon.callCommand('lock-screen', ['lock'], world.selection), + 500, + 'UNSUPPORTED_OPERATION', + /lock-screen/, + ); + assert.equal((data.details as Record).reason, 'unsupported-platform-leaf'); + assert.deepEqual(lockScreenShellCalls(world.adbCalls), []); + } finally { + await world.close(); + } +}); diff --git a/test/integration/provider-scenarios/apple-platform-output-guard.test.ts b/test/integration/provider-scenarios/apple-platform-output-guard.test.ts index 09e433a9ed..38b94cfb39 100644 --- a/test/integration/provider-scenarios/apple-platform-output-guard.test.ts +++ b/test/integration/provider-scenarios/apple-platform-output-guard.test.ts @@ -132,6 +132,7 @@ const DRIVEN_COMMANDS: Record = { [PUBLIC_COMMANDS.actionButton]: () => one(), [PUBLIC_COMMANDS.shake]: () => one(), [PUBLIC_COMMANDS.hardwareButton]: () => one(['volume-up']), + [PUBLIC_COMMANDS.lockScreen]: () => one(['lock']), [PUBLIC_COMMANDS.fold]: () => one(['open']), [PUBLIC_COMMANDS.telephony]: () => one(['call', '5551234']), diff --git a/test/integration/provider-scenarios/ios-lock-screen.test.ts b/test/integration/provider-scenarios/ios-lock-screen.test.ts new file mode 100644 index 0000000000..3dfeafe14c --- /dev/null +++ b/test/integration/provider-scenarios/ios-lock-screen.test.ts @@ -0,0 +1,59 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { PROVIDER_SCENARIO_IOS_SIMULATOR } from './fixtures.ts'; +import { createProviderScenarioHarness } from './harness.ts'; +import { createRecordingAppleToolProvider } from './providers.ts'; + +test('Provider-backed integration iOS lock-screen sends lockScreen and unlockScreen to the runner without activating the app', async () => { + const ok = { stdout: '', stderr: '', exitCode: 0 }; + const tool = createRecordingAppleToolProvider({ + simctl: async (args) => { + if (args[0] !== 'list') return ok; + return { + ...ok, + stdout: JSON.stringify({ + devices: { + 'iOS 18.5': [{ udid: PROVIDER_SCENARIO_IOS_SIMULATOR.id, state: 'Booted' }], + }, + }), + }; + }, + }); + const runnerCommands: string[] = []; + const daemon = await createProviderScenarioHarness({ + deviceInventoryProvider: async () => [PROVIDER_SCENARIO_IOS_SIMULATOR], + appleRunnerProvider: () => ({ + hasLiveSession: () => true, + runCommand: async (_device, command) => { + runnerCommands.push(command.command); + return {}; + }, + }), + appleToolProvider: () => tool.provider, + }); + const selection = { platform: 'ios', udid: PROVIDER_SCENARIO_IOS_SIMULATOR.id } as const; + try { + await daemon.client().apps.open({ app: 'com.example.demo', ...selection }); + runnerCommands.splice(0); + tool.calls.splice(0); + + assert.deepEqual(await daemon.client().command.lockScreen({ action: 'lock', ...selection }), { + action: 'lock-screen', + state: 'locked', + message: 'Locked the screen', + }); + assert.deepEqual(await daemon.client().command.lockScreen({ action: 'unlock', ...selection }), { + action: 'lock-screen', + state: 'unlocked', + message: 'Unlocked the screen', + }); + // Activating the session app would dismiss the lock screen the first command shows. + assert.deepEqual(runnerCommands, ['lockScreen', 'unlockScreen']); + assert.deepEqual( + tool.calls.filter((call) => call.includes('launch')), + [], + ); + } finally { + await daemon.close(); + } +}); From c2f599ac4459d20ac690caec98e46d7cad26eb77 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 01:48:55 +0530 Subject: [PATCH 02/10] docs(lock-screen): document lock-screen, its reasons, and its targets --- website/docs/docs/capabilities.md | 5 +++++ website/docs/docs/client-api.md | 5 +++++ website/docs/docs/commands.md | 20 +++++++++++++++++++- website/docs/docs/error-reasons.md | 8 ++++++++ 4 files changed, 37 insertions(+), 1 deletion(-) diff --git a/website/docs/docs/capabilities.md b/website/docs/docs/capabilities.md index 6b36bce7c7..a53df8540e 100644 --- a/website/docs/docs/capabilities.md +++ b/website/docs/docs/capabilities.md @@ -255,6 +255,7 @@ What a **Yes** does not claim: | [Phone hardware buttons](/docs/commands#navigation) | No | Volume only | Yes | Yes | No | No | | [iPhone Action Button](/docs/commands#navigation) | Models with an Action Button only | Models with an Action Button only | No | No | No | No | | [Shake](/docs/commands#navigation) | Yes | No | Yes | No | No | No | +| [Lock screen](/docs/commands#navigation) | Yes | No | Yes | Yes | No | No | | [Foldable pose](/docs/commands#navigation) | Foldable models only | No | Foldable models only | No | No | No | | [TV remote keys](/docs/commands#tv-targets) | No | No | No | No | No | No | | [System and app settings helpers](/docs/commands#settings-helpers) | Yes | No | Yes | Yes | Clear app state only; other settings and reads unsupported | Clear app state only; other settings and reads unsupported | @@ -273,6 +274,7 @@ What a **Yes** does not claim: | [Phone hardware buttons](/docs/commands#navigation) | No | No | No | No | No | | [iPhone Action Button](/docs/commands#navigation) | No | No | No | No | No | | [Shake](/docs/commands#navigation) | No | No | No | No | No | +| [Lock screen](/docs/commands#navigation) | No | No | No | No | No | | [Foldable pose](/docs/commands#navigation) | Foldable models only | No | No | No | No | | [TV remote keys](/docs/commands#tv-targets) | Yes | Yes | Yes | Yes | Yes | | [System and app settings helpers](/docs/commands#settings-helpers) | Yes | Yes | Set only; no reads | No | No | @@ -291,6 +293,7 @@ What a **Yes** does not claim: | [Phone hardware buttons](/docs/commands#navigation) | No | No | No | No | | [iPhone Action Button](/docs/commands#navigation) | No | No | No | No | | [Shake](/docs/commands#navigation) | No | No | No | No | +| [Lock screen](/docs/commands#navigation) | No | No | No | No | | [Foldable pose](/docs/commands#navigation) | No | No | No | No | | [TV remote keys](/docs/commands#tv-targets) | No | No | No | No | | [System and app settings helpers](/docs/commands#settings-helpers) | Set only; no reads | No | No | No | @@ -309,6 +312,7 @@ What a **Yes** does not claim: | [Phone hardware buttons](/docs/commands#navigation) | Yes | Yes | Yes | Yes | No | Yes | No | No | | [iPhone Action Button](/docs/commands#navigation) | No | No | No | No | Models with an Action Button only | No | No | No | | [Shake](/docs/commands#navigation) | No | No | No | No | No | No | No | No | +| [Lock screen](/docs/commands#navigation) | No | No | No | No | Yes | No | No | No | | [Foldable pose](/docs/commands#navigation) | No | No | No | No | No | No | No | No | | [TV remote keys](/docs/commands#tv-targets) | No | No | No | No | No | No | No | No | | [System and app settings helpers](/docs/commands#settings-helpers) | No | No | No | No | Yes | Yes | Appearance, location coordinates, permission, clear app state, and reset keychain; no reads | Appearance, location coordinates, permission, and clear app state; no reads | @@ -320,6 +324,7 @@ What a **Yes** does not claim: What a **Yes** does not claim: - **Phone hardware buttons**: Each button is a separate operation; a target that answers the row still refuses buttons it does not model. +- **Lock screen**: Unlock refuses a lock that asks for a PIN, pattern, password, or passcode. - **System and app settings helpers**: Each helper admits on its own, and a target may run only a subset of the helpers. - **Clipboard read and write**: A **Yes** means the target exposes clipboard automation. Android depends on the build: AOSP clipboard services from `android13-release` through `android16-release` have no `cmd clipboard` implementation, so such a build refuses the commands, and on builds that answer, Android focus rules can still make a read come back blank. diff --git a/website/docs/docs/client-api.md b/website/docs/docs/client-api.md index 7f8a9fbfe0..4c078edcf2 100644 --- a/website/docs/docs/client-api.md +++ b/website/docs/docs/client-api.md @@ -288,6 +288,8 @@ await client.command.shake(); await client.command.hardwareButton({ button: 'volume-up' }); await client.command.hardwareButton({ button: 'volume-down' }); await client.command.hardwareButton({ button: 'power', platform: 'android' }); +await client.command.lockScreen({ action: 'lock' }); +await client.command.lockScreen({ action: 'unlock' }); await client.command.fold({ pose: 'open' }); await client.command.telephony({ action: 'call', number: '5551234' }); await client.command.telephony({ action: 'sms', number: '5551234', text: 'Your code is 1234' }); @@ -305,6 +307,8 @@ await client.command.fold({ `hardwareButton` presses one phone hardware key once: `button` is `'volume-up'`, `'volume-down'`, `'power'`, `'mute'`, `'sleep'`, `'wake'`, `'media-play-pause'`, `'media-next'`, `'media-previous'`, `'media-rewind'`, or `'media-fast-forward'`. It takes no hold duration and activates no app; the result reports the dispatched press, not the OS reaction. Android presses all eleven on phones and tablets; a physical iPhone or iPad presses volume only; iOS Simulators, Android TV, and tvOS refuse (use `tvRemote` on TV targets). `sleep` and `wake` are the explicit Android events that turn the screen off or on; `power` toggles it. +`lockScreen` shows the lock screen (`action: 'lock'`) or dismisses it back to the app that was in front (`action: 'unlock'`), and resolves with `{ action: 'lock-screen', state: 'locked' | 'unlocked', message }` once the device reports that state. `lock` leaves a locked screen alone, and no app is activated. Android phones and tablets and iPhone and iPad simulators support it. `unlock` never enters a credential: a PIN, pattern, password, or passcode lock fails with `UNSUPPORTED_OPERATION` and `details.reason: 'lock-screen-secure'`. + `press`, `click`, and `longpress` do not wait for a missing target to appear. When a screen is still loading, wait for its landmark before interacting: ```ts @@ -337,6 +341,7 @@ Supported command methods: - `actionButton` - `shake` - `hardwareButton` +- `lockScreen` - `fold` - `telephony` - `keyboard` diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index dfdcefe854..c532108f94 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -56,6 +56,7 @@ agent-device close agent-device back agent-device orientation landscape-left agent-device hardware-button volume-up +agent-device lock-screen lock agent-device fold half-open agent-device telephony sms 5551234 "Your code is 1234" agent-device device status --platform android --serial emulator-5554 @@ -359,6 +360,20 @@ Exact behavior: `agent-device help hardware-button`. + + +Lock or unlock the device screen. + +```bash +agent-device lock-screen +``` + +Supported targets: [Lock screen](/docs/capabilities#system-and-hardware). + +Exact behavior: `agent-device help lock-screen`. + + + - `back` uses the app's own back navigation: the back key on Android, the visible back control on macOS, and the Menu button on tvOS. On macOS, an app with no back control by identifier or "Back" label refuses with `in_app_back_control_unavailable` and nothing is pressed; press the app's control by its ref. - iOS has no system back. `back` presses the navigation bar's system back button when it finds exactly one, and otherwise swipes from the left edge. It never presses a custom "Back" button, and it does not dismiss a modal or sheet: press that screen's Close or Cancel control. On Android, system back also closes dialogs. - `back_swipe_no_change` means the swipe did not change the screen. `details.dismissControls` lists the Back, Close, and Cancel buttons at the top of the app window as selectors, for example `agent-device press 'role=button label="Close"'`. `back` never presses them itself, because they can discard a draft. @@ -371,7 +386,10 @@ Exact behavior: `agent-device help hardware-button`. - `shake` works on iOS simulators and local Android emulators, not on Android TV or remote providers. On iOS, the app gets a motion-shake event but no accelerometer data, so an app that detects shakes through CoreMotion does not see it. Take a snapshot to see what the app did. - On Android, `shake-rest-acceleration-unreadable` means the emulator console returned no accelerometer reading, so nothing was sent. `shake-console-refused` after a swing means the accelerometer may not be back at rest. Check with `adb emu sensor get acceleration`. - `hardware-button` presses a key once and reports the press, not what the OS did with it. Android presses every key. A physical iPhone or iPad presses volume only, iOS simulators refuse every key, and TV targets point you to `tv-remote`. -- On Android, `power` toggles the screen. After a press that turns the screen off, later commands can hit a locked screen; use `hardware-button wake`. +- On Android, `power` toggles the screen. After a press that turns the screen off, later commands can hit a locked screen; use `hardware-button wake`, or `lock-screen unlock` to dismiss the lock screen too. +- `lock-screen` returns once the device reports the lock state, in `state`. `lock` leaves a locked screen alone. Android verifies with the keyguard state that `dumpsys window` reports, and needs a screen lock other than None. iOS simulators verify with SpringBoard's lock state and, for `lock`, a lock screen surface. On iOS, `unlock` first wakes a dark screen with the lock button, then swipes up, and also needs the screen on. `unlock` lands on the app that was in front, not on the Home Screen. On Android it always sends the wake event, which leaves a screen that is on unchanged. +- The session app is not activated, so check the result with `screenshot`. On iOS, an app-scoped command such as `snapshot` brings the session app back to the front, which can dismiss the lock screen. +- `lock-screen unlock` never enters a credential. A PIN, pattern, password, or passcode lock fails with `lock-screen-secure`; on Android nothing is sent (`dispatched: no`). `lock-screen-unverified` means the device still reports the previous state. On Android, `lock-screen-state-unreadable` means `dumpsys` reported no keyguard state or no lock type for the foreground user, and nothing was sent. Fold a foldable device: diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 5d853bf9b7..a15125fd1b 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -162,6 +162,14 @@ Treat a reason that this page does not list as unknown, not as an error in the r | --- | --- | | `keyboard_dismiss_unavailable` | The keyboard stayed up: the Apple runner leaves a visible keyboard alone and presses nothing, or the Android IME stayed visible after Escape key events, which may have reached the app. `details.dispatched` says which. | +### `lock-screen` + +| Reason | Meaning | +| --- | --- | +| `lock-screen-secure` | The lock needs a PIN, pattern, password, or passcode, so unlock typed nothing and left it locked. | +| `lock-screen-unverified` | The lock or unlock was sent, but the device still reports the previous lock state. | +| `lock-screen-state-unreadable` | dumpsys reported no keyguard state, or no lock type for the foreground user, so nothing was sent. | + ### `logs` | Reason | Meaning | From 28e5e1e837beb56980353574c714ae5e185f8d76 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 01:48:55 +0530 Subject: [PATCH 03/10] chore(gates): admit the lock-screen facet module to the eager closures The system family keeps one module per command, so the new facet adds one module and 15 top-level statements to the client, CLI and command-surface entries. No maintainer has approved the row yet, so its owner is a placeholder. --- scripts/__tests__/eager-closure-budgets.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/scripts/__tests__/eager-closure-budgets.ts b/scripts/__tests__/eager-closure-budgets.ts index 899147cb73..a9253bf8b6 100644 --- a/scripts/__tests__/eager-closure-budgets.ts +++ b/scripts/__tests__/eager-closure-budgets.ts @@ -174,6 +174,13 @@ export const APPROVED_CLOSURE_ADDITIONS: readonly Readonly<{ 'The registry and identity stamp are the provenance contract every capture path already evaluates; this is the module boundary only (#4309, #4205). Measured: +1 module and +5 to +9 top-level statements per closure that reaches snapshot-model.', owner: 'thymikee', }, + { + module: 'packages/command-surface/src/system/lock-screen.ts', + issue: '#4798', + reason: + 'The lock-screen command facet. The system family keeps one module per command (command-output-schemas-system.test.ts), so a new command is a new module in every entry that composes the family. Measured: +1 module and +15 top-level statements for the client, CLI and command-surface entries.', + owner: 'pending maintainer approval', + }, ]); /** The category is a function of the path, never a hand-written column. */ From f09be4cd8fef1bd174945ba3e62ad41c34a6aeb4 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 09:57:25 +0530 Subject: [PATCH 04/10] refactor(contracts): spell the lock-screen states once LOCK_SCREEN_STATES sits beside LOCK_SCREEN_ACTIONS, and the result type, the MCP output schema, the session journal and the daemon rows read it instead of repeating 'locked' and 'unlocked'. --- packages/command-surface/src/system/output-schemas.ts | 3 ++- packages/contracts/src/client-system.ts | 2 +- packages/contracts/src/device-rotation.ts | 4 ++++ packages/contracts/src/facades/device.ts | 8 +++++++- packages/contracts/src/navigation.ts | 9 +++++++-- packages/daemon/src/execution/system-button-runtime.ts | 3 ++- .../src/session-event-action-presentation.ts | 2 +- 7 files changed, 24 insertions(+), 7 deletions(-) diff --git a/packages/command-surface/src/system/output-schemas.ts b/packages/command-surface/src/system/output-schemas.ts index 1a6c86a9ea..b7231b0e87 100644 --- a/packages/command-surface/src/system/output-schemas.ts +++ b/packages/command-surface/src/system/output-schemas.ts @@ -4,6 +4,7 @@ import { FOLD_SCREEN_COORDINATE_SPACE, FOLD_POSES, HARDWARE_BUTTON_NAMES, + LOCK_SCREEN_STATES, ORIENTATION_REQUESTS, TELEPHONY_CALL_ACTIONS, } from '@agent-device/contracts/device'; @@ -105,7 +106,7 @@ export const SYSTEM_COMMAND_OUTPUT_SCHEMAS = { 'lock-screen': objectSchema( { action: constSchema('lock-screen'), - state: enumSchema(['locked', 'unlocked']), + state: enumSchema(LOCK_SCREEN_STATES), message: stringSchema(), }, ['action', 'state', 'message'], diff --git a/packages/contracts/src/client-system.ts b/packages/contracts/src/client-system.ts index df2353c0c0..a80848bf81 100644 --- a/packages/contracts/src/client-system.ts +++ b/packages/contracts/src/client-system.ts @@ -7,9 +7,9 @@ import type { DeviceCommandBaseOptions } from './client-connection.ts'; import type { SettleCommandOptions } from './client-gesture.ts'; import type { HardwareButtonName, - LockScreenAction, OrientationRequest, SetFoldPoseInput, + LockScreenAction, } from './device-rotation.ts'; import type { TelephonyEventInput } from './telephony-input.ts'; import type { TvRemoteButton } from './tv-remote.ts'; diff --git a/packages/contracts/src/device-rotation.ts b/packages/contracts/src/device-rotation.ts index 9d88296906..c1052ec64a 100644 --- a/packages/contracts/src/device-rotation.ts +++ b/packages/contracts/src/device-rotation.ts @@ -226,6 +226,10 @@ export function parseHardwareButtonPositionals(positionals: readonly string[]): export const LOCK_SCREEN_ACTIONS = ['lock', 'unlock'] as const; export type LockScreenAction = (typeof LOCK_SCREEN_ACTIONS)[number]; +/** The lock states a `lock-screen` result reports, each read back from the device. */ +export const LOCK_SCREEN_STATES = ['locked', 'unlocked'] as const; +export type LockScreenState = (typeof LOCK_SCREEN_STATES)[number]; + /** The CLI synopsis tail naming the accepted actions. */ export const LOCK_SCREEN_USAGE = `<${LOCK_SCREEN_ACTIONS.join('|')}>`; diff --git a/packages/contracts/src/facades/device.ts b/packages/contracts/src/facades/device.ts index d7d554d292..ee50220a8e 100644 --- a/packages/contracts/src/facades/device.ts +++ b/packages/contracts/src/facades/device.ts @@ -56,10 +56,16 @@ export { parseHardwareButtonPositionals, LOCK_SCREEN_ACTIONS, LOCK_SCREEN_REASONS, + LOCK_SCREEN_STATES, LOCK_SCREEN_USAGE, parseLockScreenPositionals, } from '../device-rotation.ts'; -export type { HardwareButton, HardwareButtonName, LockScreenAction } from '../device-rotation.ts'; +export type { + HardwareButton, + HardwareButtonName, + LockScreenAction, + LockScreenState, +} from '../device-rotation.ts'; export { TELEPHONY_ACTIONS, TELEPHONY_CALL_ACTIONS, diff --git a/packages/contracts/src/navigation.ts b/packages/contracts/src/navigation.ts index 9426c32841..489e51b80f 100644 --- a/packages/contracts/src/navigation.ts +++ b/packages/contracts/src/navigation.ts @@ -1,5 +1,10 @@ import type { BackMode } from './back-mode.ts'; -import type { DeviceRotation, FoldPose, HardwareButtonName } from './device-rotation.ts'; +import type { + DeviceRotation, + FoldPose, + HardwareButtonName, + LockScreenState, +} from './device-rotation.ts'; import type { FoldScreenReport } from './fold-runtime.ts'; import type { SettleObservation } from './interaction.ts'; import type { TvRemoteButton } from './tv-remote.ts'; @@ -121,6 +126,6 @@ export type HardwareButtonCommandResult = { */ export type LockScreenCommandResult = { action: 'lock-screen'; - state: 'locked' | 'unlocked'; + state: LockScreenState; message: string; }; diff --git a/packages/daemon/src/execution/system-button-runtime.ts b/packages/daemon/src/execution/system-button-runtime.ts index 2d371b6856..a6b0b45402 100644 --- a/packages/daemon/src/execution/system-button-runtime.ts +++ b/packages/daemon/src/execution/system-button-runtime.ts @@ -28,6 +28,7 @@ import { parseLockScreenPositionals, type HardwareButton, type LockScreenAction, + type LockScreenState, } from '@agent-device/contracts/device'; import type { LockScreenCommandResult } from '@agent-device/contracts/navigation'; import type { @@ -132,7 +133,7 @@ const LOCK_SCREEN_COMMAND_ROWS = { unlock: { use: unlockScreenRuntimeUse, state: 'unlocked', message: 'Unlocked the screen' }, } as const satisfies Record< LockScreenAction, - Readonly<{ use: SystemButtonUse; state: LockScreenCommandResult['state']; message: string }> + Readonly<{ use: SystemButtonUse; state: LockScreenState; message: string }> >; /** The neutral intent one press carries, projected from a resolved command context. */ diff --git a/packages/session-journal/src/session-event-action-presentation.ts b/packages/session-journal/src/session-event-action-presentation.ts index cdd3bf33d1..856e2c4a23 100644 --- a/packages/session-journal/src/session-event-action-presentation.ts +++ b/packages/session-journal/src/session-event-action-presentation.ts @@ -4,6 +4,7 @@ import { HARDWARE_BUTTON_NAMES, ORIENTATION_REQUESTS, TELEPHONY_ACTIONS, + LOCK_SCREEN_STATES, } from '@agent-device/contracts/device'; import { BACK_MODES } from '@agent-device/contracts/back-mode'; import { isTvRemoteButton } from '@agent-device/contracts/tv-remote'; @@ -23,7 +24,6 @@ import type { DaemonRequest } from '@agent-device/kernel/contracts'; const SCROLL_DIRECTIONS = ['up', 'down', 'left', 'right'] as const; const SCROLL_EDGES = ['top', 'bottom'] as const; -const LOCK_SCREEN_STATES = ['locked', 'unlocked'] as const; export function buildInstallActionSummary(action: SessionAction): string { const verb = action.command === PUBLIC_COMMANDS.reinstall ? 'Reinstalled' : 'Installed'; From ed96b8fafe50d90cf7568bbdebda396339705689 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 09:57:25 +0530 Subject: [PATCH 05/10] fix(android): refuse a None screen lock and wait for a deferred keyguard With the screen lock set to None, Android shows no keyguard, so lock sent the sleep key and then failed unverified. It now reads the foreground user's lock settings first and refuses with lock-screen-disabled and dispatched: no. On a secure device with "Power button instantly locks" off, the keyguard appears only after lock_screen_lock_after_timeout. Lock now waits that long on top of its 5 s window, 5 s when the setting is unset, up to one minute so the command stays inside the daemon's request envelope. --- .../command-surface/src/system/lock-screen.ts | 2 +- .../platform-android/src/lock-screen.test.ts | 58 +++++++- packages/platform-android/src/lock-screen.ts | 125 +++++++++++++----- .../android-lock-screen.test.ts | 30 ++++- 4 files changed, 174 insertions(+), 41 deletions(-) diff --git a/packages/command-surface/src/system/lock-screen.ts b/packages/command-surface/src/system/lock-screen.ts index 62695333b8..11513496bc 100644 --- a/packages/command-surface/src/system/lock-screen.ts +++ b/packages/command-surface/src/system/lock-screen.ts @@ -13,7 +13,7 @@ import { defineFieldCommandMetadata } from '../field-command-contract.ts'; const LOCK_SCREEN_COMMAND_NAME = 'lock-screen'; const lockScreenCommandDescription = - 'Lock or unlock the device screen. lock shows the lock screen and leaves a locked screen alone; unlock dismisses it back to the app that was in front. Each returns once the device reports that lock state. Android locks with KEYCODE_SLEEP and unlocks with KEYCODE_WAKEUP then wm dismiss-keyguard, verified by the keyguard state dumpsys window reports; unlock always sends the wake event, which leaves a screen that is on unchanged. iPhone and iPad simulators lock through the XCUITest lock button, verified by the SpringBoard lock state and a lock screen surface, and unlock with a swipe up from the bottom edge after the lock button wakes a dark screen; unlock also needs the screen on. A PIN, pattern, password, or passcode lock is never unlocked: unlock refuses with reason lock-screen-secure and types nothing. The session app is not activated, so verify with screenshot; an app-scoped command such as snapshot can bring the app back to the front on iOS. Every other target refuses this command, including physical iPhones and iPads and Android TV.'; + 'Lock or unlock the device screen. lock shows the lock screen and leaves a locked screen alone; unlock dismisses it back to the app that was in front. Each returns once the device reports that lock state. Android locks with KEYCODE_SLEEP and unlocks with KEYCODE_WAKEUP then wm dismiss-keyguard, verified by the keyguard state dumpsys window reports; a screen lock set to None is refused with lock-screen-disabled, and unlock always sends the wake event, which leaves a screen that is on unchanged. iPhone and iPad simulators lock through the XCUITest lock button, verified by the SpringBoard lock state and a lock screen surface, and unlock with a swipe up from the bottom edge after the lock button wakes a dark screen; unlock also needs the screen on. A PIN, pattern, password, or passcode lock is never unlocked: unlock refuses with reason lock-screen-secure and types nothing. The session app is not activated, so verify with screenshot; an app-scoped command such as snapshot can bring the app back to the front on iOS. Every other target refuses this command, including physical iPhones and iPads and Android TV.'; const lockScreenCommandMetadata = defineFieldCommandMetadata( LOCK_SCREEN_COMMAND_NAME, diff --git a/packages/platform-android/src/lock-screen.test.ts b/packages/platform-android/src/lock-screen.test.ts index 1ab28727fb..90ea05c43b 100644 --- a/packages/platform-android/src/lock-screen.test.ts +++ b/packages/platform-android/src/lock-screen.test.ts @@ -26,19 +26,26 @@ const mockPress = vi.mocked(pressAndroidHardwareButton); const mockCurrentUser = vi.mocked(readAndroidCurrentUserId); /** `dumpsys lock_settings` as Android 16 prints it, one block per user. */ -function lockSettingsDump(users: Record): string { +function lockSettingsDump(users: Record, lockScreenDisabled = false): string { const blocks = Object.entries(users).map( ([id, type]) => - ` User ${id}\n LSKF-based SP protector ID: 0000000000000000\n Quality: 0\n CredentialType: ${type}\n SeparateChallenge: false\n`, + ` User ${id}\n LSKF-based SP protector ID: 0000000000000000\n Quality: 0\n CredentialType: ${type}\n` + + (type === 'NONE' ? ` IsLockScreenDisabled: ${lockScreenDisabled}\n` : '') + + ' SeparateChallenge: false\n', ); - return `Current lock settings service state:\n\nUser State:\n${blocks.join('')}\nStorage:\n`; + return `Current lock settings service state:\n\nUser State:\n${blocks.join('')}\nStorage:\n User 0 [/data/system_de/0/spblob]:\n`; } /** * One device answered by command: `keyguardReads` are the successive `isKeyguardShowing` values * (the last repeats), `credentials` the lock_settings blocks per user. */ -function stubDevice(options: { keyguardReads: boolean[]; credentials?: Record }) { +function stubDevice(options: { + keyguardReads: boolean[]; + credentials?: Record; + lockScreenDisabled?: boolean; + lockAfterTimeout?: string; +}) { const reads = [...options.keyguardReads]; mockShell.mockImplementation(async (_device, words) => { const command = words.join(' '); @@ -48,7 +55,12 @@ function stubDevice(options: { keyguardReads: boolean[]; credentials?: Record await lockAndroidScreen(ANDROID_EMULATOR, undefined); expect(mockPress.mock.calls.map(([, button]) => button)).toEqual(['sleep']); expect(keyguardReads()).toBe(3); + // A swipe lock has no credential, so its keyguard is never deferred. + expect(shellCommands()).not.toContain('settings get secure lock_screen_lock_after_timeout'); +}); + +test('lock refuses a screen lock set to None before sending anything', async () => { + stubDevice({ keyguardReads: [false], lockScreenDisabled: true }); + await expect(lockAndroidScreen(ANDROID_EMULATOR, undefined)).rejects.toMatchObject({ + code: 'UNSUPPORTED_OPERATION', + details: { reason: 'lock-screen-disabled', dispatched: 'no' }, + }); + expect(mockPress).not.toHaveBeenCalled(); +}); + +// With "Power button instantly locks" off, a secure keyguard waits for "Lock after screen +// timeout", so the window grows by that delay, Android's 5 s when unset, and never past 60 s. +test.each([ + ['an unset delay as 5 s', 'null', 10_000], + ['a 30 s delay', '30000', 35_000], + ['a delay past one minute as 60 s', '1800000', 65_000], +])('lock on a secure device waits for %s', async (_name, lockAfterTimeout, windowMs) => { + stubDevice({ keyguardReads: [false], credentials: { 0: 'PIN' }, lockAfterTimeout }); + await expect(lockAndroidScreen(ANDROID_EMULATOR, undefined)).rejects.toMatchObject({ + details: { reason: 'lock-screen-unverified', dispatched: 'unknown' }, + }); + // One read before the key event, then one right after it and one after each 250 ms poll. + expect(keyguardReads()).toBe(2 + windowMs / 250); +}); + +test('lock on a secure device returns once the deferred keyguard shows', async () => { + stubDevice({ + keyguardReads: [false, ...Array(24).fill(false), true], + credentials: { 0: 'PIN' }, + lockAfterTimeout: '5000', + }); + await lockAndroidScreen(ANDROID_EMULATOR, undefined); + expect(keyguardReads()).toBe(26); }); test('lock reads the keyguard once more after the last poll before it reports unverified', async () => { diff --git a/packages/platform-android/src/lock-screen.ts b/packages/platform-android/src/lock-screen.ts index c009e22777..cb219b68c3 100644 --- a/packages/platform-android/src/lock-screen.ts +++ b/packages/platform-android/src/lock-screen.ts @@ -11,32 +11,65 @@ import { readAndroidCurrentUserId } from './permission-grant-state.ts'; const ANDROID_LOCK_SCREEN_REASONS = { // dumpsys reported no keyguard state, or no lock type for the foreground user, so nothing was sent. stateUnreadable: { reason: 'lock-screen-state-unreadable' }, + // The screen lock is set to None, so there is no lock screen to show; nothing was sent. + lockScreenDisabled: { reason: 'lock-screen-disabled' }, } as const satisfies ReasonTable<'lock-screen'>; /** How long the keyguard has to reach the requested state after the key event or dismissal. */ const LOCK_STATE_WINDOW_MS = 5_000; const LOCK_STATE_POLL_MS = 250; +/** + * A secure device whose "Power button instantly locks" is off shows the keyguard only after its + * "Lock after screen timeout" delay (`lock_screen_lock_after_timeout`, 5 s when unset). The lock + * waits that long on top of its own window, up to this cap, which keeps the command inside the + * daemon's 90 s request envelope. + */ +const LOCK_AFTER_TIMEOUT_DEFAULT_MS = 5_000; +const LOCK_AFTER_TIMEOUT_CAP_MS = 60_000; const SECURE_LOCK_HINT = 'unlock never enters a credential. Unlock the device by hand, or remove its screen lock in Settings > Security, then retry.'; const STATE_UNREADABLE_HINT = 'Check adb shell dumpsys window, adb shell dumpsys lock_settings, and adb shell am get-current-user; if the device is still booting, retry once it reports a user.'; -const LOCK_UNVERIFIED_HINT = - 'Android raised no keyguard after KEYCODE_SLEEP. A device whose screen lock is set to None has no lock screen to show.'; +const LOCK_DISABLED_HINT = + 'Set a screen lock other than None in Settings > Security > Screen lock (Swipe needs no credential), then retry.'; +const LOCK_UNVERIFIED_HINT = 'Android raised no keyguard after KEYCODE_SLEEP.'; +const DEFERRED_LOCK_UNVERIFIED_HINT = + 'Android raised no keyguard after KEYCODE_SLEEP. With "Power button instantly locks" off, the keyguard waits for "Lock after screen timeout"; a delay above one minute outlasts this command.'; const UNLOCK_UNVERIFIED_HINT = 'The keyguard stayed up after wm dismiss-keyguard. Take a screenshot to see what covers the screen.'; +type LockSettings = Readonly<{ credentialType: string; lockScreenDisabled: boolean }>; + /** * Shows the keyguard with KEYCODE_SLEEP and returns once `dumpsys window` reports it. A keyguard - * already up is left alone. + * already up is left alone, and a screen lock set to None is refused before anything is sent. */ export async function lockAndroidScreen( device: DeviceInfo, signal: AbortSignal | undefined, ): Promise { if (await readKeyguardBeforeDispatch(device, signal)) return; + const settings = await readLockSettingsBeforeDispatch(device, signal); + if (settings.lockScreenDisabled) { + throw new AppError( + 'UNSUPPORTED_OPERATION', + `The screen lock of ${device.name} is set to None, so there is no lock screen to show`, + { + deviceId: device.id, + reason: ANDROID_LOCK_SCREEN_REASONS.lockScreenDisabled.reason, + dispatched: 'no', + hint: LOCK_DISABLED_HINT, + }, + ); + } + const deferMs = + settings.credentialType === 'none' ? 0 : await readLockAfterTimeoutMs(device, signal); await pressAndroidHardwareButton(device, 'sleep'); - await awaitKeyguardState(device, true, signal); + await awaitKeyguardState(device, true, signal, { + windowMs: LOCK_STATE_WINDOW_MS + Math.min(deferMs, LOCK_AFTER_TIMEOUT_CAP_MS), + hint: deferMs > 0 ? DEFERRED_LOCK_UNVERIFIED_HINT : LOCK_UNVERIFIED_HINT, + }); } /** @@ -59,7 +92,11 @@ export async function unlockAndroidScreen( await dismiss(); // A dismissal that lands while the screen is still waking can be dropped, so each poll that // still finds the keyguard sends it again; a secure keyguard was refused above. - await awaitKeyguardState(device, false, signal, dismiss); + await awaitKeyguardState(device, false, signal, { + windowMs: LOCK_STATE_WINDOW_MS, + hint: UNLOCK_UNVERIFIED_HINT, + retry: dismiss, + }); } /** The keyguard state before anything is sent; a dump without one refuses instead of guessing. */ @@ -75,15 +112,16 @@ async function readKeyguardBeforeDispatch( /** * Polls until the keyguard reaches `showing`. The window starts after the dispatch returned, and * every wait is followed by a read, so a state the device reached during the last wait is seen. - * `retry` runs after each wait that follows a read in the wrong state. + * `retry` runs after each wait that follows a read in the wrong state. The dispatch was sent, so + * a failure discloses `dispatched: unknown`: the only wire value for a send that may have acted. */ async function awaitKeyguardState( device: DeviceInfo, showing: boolean, signal: AbortSignal | undefined, - retry?: () => Promise, + options: Readonly<{ windowMs: number; hint: string; retry?: () => Promise }>, ): Promise { - const deadline = Deadline.fromTimeoutMs(LOCK_STATE_WINDOW_MS); + const deadline = Deadline.fromTimeoutMs(options.windowMs); while ((await readAndroidKeyguardShowing(device, signal)) !== showing) { if (deadline.isExpired()) { throw new AppError( @@ -93,12 +131,12 @@ async function awaitKeyguardState( deviceId: device.id, reason: LOCK_SCREEN_REASONS.stateUnverified.reason, dispatched: 'unknown', - hint: showing ? LOCK_UNVERIFIED_HINT : UNLOCK_UNVERIFIED_HINT, + hint: options.hint, }, ); } await sleep(LOCK_STATE_POLL_MS, signal); - await retry?.(); + await options.retry?.(); } } @@ -106,18 +144,15 @@ async function refuseSecureLock( device: DeviceInfo, signal: AbortSignal | undefined, ): Promise { - const credential = await readCredentialType(device, signal); - if (credential === 'none') return; - if (credential === undefined) { - throw stateUnreadable(device, 'the screen lock type of the foreground user'); - } + const { credentialType } = await readLockSettingsBeforeDispatch(device, signal); + if (credentialType === 'none') return; throw new AppError( 'UNSUPPORTED_OPERATION', - `The screen lock of ${device.name} asks for a credential (${credential}), which lock-screen unlock does not enter`, + `The screen lock of ${device.name} asks for a credential (${credentialType}), which lock-screen unlock does not enter`, { deviceId: device.id, reason: LOCK_SCREEN_REASONS.secureLock.reason, - credentialType: credential, + credentialType, dispatched: 'no', hint: SECURE_LOCK_HINT, }, @@ -134,34 +169,58 @@ function stateUnreadable(device: DeviceInfo, what: string): AppError { } /** - * The foreground user's credential type from `dumpsys lock_settings`, lower-cased (`none`, `pin`, - * `pattern`, `password`), or `undefined` when the user or its `CredentialType:` line is missing. - * Builds that print the type as a number report it unchanged, except -1, which is none. + * The foreground user's lock settings from `dumpsys lock_settings`: the credential type, + * lower-cased (`none`, `pin`, `pattern`, `password`), and whether the lock screen is disabled, + * which builds print only for a user with no credential. Builds that print the type as a number + * report it unchanged, except -1, which is none. A missing user or type refuses before dispatch. */ -async function readCredentialType( +async function readLockSettingsBeforeDispatch( device: DeviceInfo, signal: AbortSignal | undefined, -): Promise { +): Promise { const userId = await readAndroidCurrentUserId(device); - if (userId === undefined) return undefined; - const { stdout } = await runCheckedAndroidShell(device, ['dumpsys', 'lock_settings'], signal); - const type = credentialTypeForUser(stdout, userId); - if (type === undefined) return undefined; - return type === '-1' ? 'none' : type.toLowerCase(); + const { stdout } = + userId === undefined + ? { stdout: '' } + : await runCheckedAndroidShell(device, ['dumpsys', 'lock_settings'], signal); + const block = userId === undefined ? undefined : userBlock(stdout, userId); + const type = block === undefined ? undefined : /^\s*CredentialType:\s*(\S+)/m.exec(block)?.[1]; + if (type === undefined) { + throw stateUnreadable(device, 'the screen lock type of the foreground user'); + } + return { + credentialType: type === '-1' ? 'none' : type.toLowerCase(), + lockScreenDisabled: /^\s*IsLockScreenDisabled:\s*true\b/m.test(block!), + }; } -/** The `CredentialType:` value inside the `User ` block of a `dumpsys lock_settings` dump. */ -function credentialTypeForUser(dump: string, userId: number): string | undefined { +/** The lines inside the `User ` block of a `dumpsys lock_settings` dump. */ +function userBlock(dump: string, userId: number): string | undefined { + const lines: string[] = []; + let found = false; let inUser = false; for (const line of dump.split('\n')) { const user = /^\s*User (\d+)\s*$/.exec(line); if (user) { inUser = Number(user[1]) === userId; + found ||= inUser; continue; } - if (!inUser) continue; - const type = /^\s*CredentialType:\s*(\S+)/.exec(line); - if (type) return type[1]; + if (inUser) lines.push(line); } - return undefined; + return found ? lines.join('\n') : undefined; +} + +/** `lock_screen_lock_after_timeout` in milliseconds; an unset or unreadable value is Android's 5 s default. */ +async function readLockAfterTimeoutMs( + device: DeviceInfo, + signal: AbortSignal | undefined, +): Promise { + const { stdout } = await runCheckedAndroidShell( + device, + ['settings', 'get', 'secure', 'lock_screen_lock_after_timeout'], + signal, + ); + const value = Number.parseInt(stdout.trim(), 10); + return Number.isInteger(value) && value >= 0 ? value : LOCK_AFTER_TIMEOUT_DEFAULT_MS; } diff --git a/test/integration/provider-scenarios/android-lock-screen.test.ts b/test/integration/provider-scenarios/android-lock-screen.test.ts index d65b5e8f32..cecc2eb0ea 100644 --- a/test/integration/provider-scenarios/android-lock-screen.test.ts +++ b/test/integration/provider-scenarios/android-lock-screen.test.ts @@ -16,7 +16,7 @@ const KEYCODE_WAKEUP = '224'; * lock does: KEYCODE_SLEEP raises it and `wm dismiss-keyguard` clears it. `credential` is the * foreground user's lock type in `dumpsys lock_settings`. */ -function keyguardDevice(credential = 'NONE') { +function keyguardDevice(credential = 'NONE', lockScreenDisabled = false) { let showing = false; const answer = (stdout: string) => ({ stdout, stderr: '', exitCode: 0 }); return (args: readonly string[]) => { @@ -33,8 +33,12 @@ function keyguardDevice(credential = 'NONE') { return answer(''); } if (command === 'shell dumpsys lock_settings') { - return answer(`User State:\n User 0\n CredentialType: ${credential}\n`); + return answer( + `User State:\n User 0\n CredentialType: ${credential}\n IsLockScreenDisabled: ${lockScreenDisabled}\n`, + ); } + if (command === 'shell settings get secure lock_screen_lock_after_timeout') + return answer('null\n'); return undefined; }; } @@ -69,6 +73,7 @@ test('Provider-backed integration Android lock-screen locks and unlocks a swipe message: 'Unlocked the screen', }); assert.deepEqual(lockScreenShellCalls(world.adbCalls), [ + 'shell dumpsys lock_settings', `shell input keyevent ${KEYCODE_SLEEP}`, 'shell dumpsys lock_settings', `shell input keyevent ${KEYCODE_WAKEUP}`, @@ -149,3 +154,24 @@ test('Provider-backed integration Android lock-screen refuses an Android TV targ await world.close(); } }); + +test('Provider-backed integration Android lock-screen lock refuses a screen lock set to None before sending anything', async () => { + const world = await createAndroidSettingsWorld({ onAdbExec: keyguardDevice('NONE', true) }); + + try { + await world.daemon.client().apps.open({ app: 'settings', ...world.selection }); + world.adbCalls.splice(0); + const data = assertRpcError( + await world.daemon.callCommand('lock-screen', ['lock'], world.selection), + 500, + 'UNSUPPORTED_OPERATION', + /set to None/, + ); + const details = data.details as Record; + assert.equal(details.reason, 'lock-screen-disabled'); + assert.equal(details.dispatched, 'no'); + assert.deepEqual(lockScreenShellCalls(world.adbCalls), ['shell dumpsys lock_settings']); + } finally { + await world.close(); + } +}); From dd591862f86b308771ea2f0ccdea08116df321a2 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 09:57:25 +0530 Subject: [PATCH 06/10] fix(ios): wake a dark unlocked screen before locking it On a simulator whose screen SpringBoard has blanked while unlocked, the lock button can wake the screen instead of locking it. lockScreen now wakes such a screen first and presses again only if it is still unlocked. --- .../RunnerTests+LockScreen.swift | 32 ++++++++++++++----- apple/runner/RUNNER_PROTOCOL.md | 4 ++- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LockScreen.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LockScreen.swift index a0ed609503..6d25d46a4b 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LockScreen.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LockScreen.swift @@ -51,7 +51,7 @@ extension RunnerTests { lock: lock, steps: LockScreenTransitionSteps( readState: currentLockScreenState, - dispatch: lock ? dispatchLockButton : dispatchUnlock, + dispatch: lock ? dispatchLock : dispatchUnlock, lockScreenSurfaceIsVisible: lockScreenSurfaceIsVisible, passcodePromptIsVisible: passcodePromptIsVisible, shouldContinue: { Date() < deadline }, @@ -167,18 +167,23 @@ extension RunnerTests { return nil } + /// Presses the lock button on a lit screen. On a blanked screen that is still unlocked, the first + /// press can wake the screen instead of locking it, so the screen is woken first and pressed + /// again only if it is still unlocked. + private func dispatchLock() -> Response? { + if screenIsBlanked() { + if let refusal = wakeBlankedScreen() { return refusal } + guard currentLockScreenState() == .unlocked else { return nil } + } + return dispatchLockButton() + } + /// Wakes a blanked screen with the lock button, then swipes up from the bottom edge, as a person /// dismisses the lock screen. A swipe on a blanked screen unlocks SpringBoard but leaves the /// screen off. The swipe lands on whatever was in front before the lock, unlike a Home press, /// which lands on the Home Screen. private func dispatchUnlock() -> Response? { - if screenIsBlanked() { - if let refusal = dispatchLockButton() { return refusal } - let wakeDeadline = Date().addingTimeInterval(Self.lockScreenVerificationTimeout) - while screenIsBlanked() && Date() < wakeDeadline { - RunLoop.current.run(until: Date().addingTimeInterval(Self.lockScreenPollInterval)) - } - } + if screenIsBlanked(), let refusal = wakeBlankedScreen() { return refusal } guard currentLockScreenState() == .locked else { return nil } let start = springboard.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.99)) let end = springboard.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.4)) @@ -186,6 +191,17 @@ extension RunnerTests { return nil } + /// Presses the lock button to light a blanked screen and waits, within the verification + /// timeout, until SpringBoard reports it lit. + private func wakeBlankedScreen() -> Response? { + if let refusal = dispatchLockButton() { return refusal } + let wakeDeadline = Date().addingTimeInterval(Self.lockScreenVerificationTimeout) + while screenIsBlanked() && Date() < wakeDeadline { + RunLoop.current.run(until: Date().addingTimeInterval(Self.lockScreenPollInterval)) + } + return nil + } + /// The lock screen's date view, or SpringBoard's cover sheet window. The cover sheet also hosts /// Notification Center, so it counts only together with the locked state the caller read. private func lockScreenSurfaceIsVisible() -> Bool { diff --git a/apple/runner/RUNNER_PROTOCOL.md b/apple/runner/RUNNER_PROTOCOL.md index 703ffccf10..7075025d61 100644 --- a/apple/runner/RUNNER_PROTOCOL.md +++ b/apple/runner/RUNNER_PROTOCOL.md @@ -325,7 +325,9 @@ reply produced) and publishes its `details.reason`. reports the requested state; a lock also waits for the lock screen's date view or cover sheet window, and an unlock for `com.apple.springboard.hasBlankedScreen` to report the screen on. A swipe on a dark screen unlocks SpringBoard but leaves the screen off, so `unlockScreen` wakes a dark -screen with the lock button before it swipes. The verification window starts after the lock button press or the unlock swipe returns, +screen with the lock button before it swipes. On a dark screen that is still unlocked, the lock +button can wake the screen instead of locking it, so `lockScreen` wakes it first and presses again +only if it is still unlocked. The verification window starts after the lock button press or the unlock swipe returns, and the runner reads the state once more after its last wait. `LOCK_SCREEN_UNVERIFIED` means the state did not change in time, and `LOCK_SCREEN_SECURE` means the unlock swipe raised a passcode prompt, which the runner leaves unanswered. Either can follow a dispatch, so the host reports From 5b1e08bcc082ceef5a63370385c3fe3c8285ffa3 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 09:57:25 +0530 Subject: [PATCH 07/10] docs(lock-screen): document the None refusal, the deferred keyguard, and the iOS wake --- website/docs/docs/commands.md | 4 ++-- website/docs/docs/error-reasons.md | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index c532108f94..770351ebe7 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -387,9 +387,9 @@ Exact behavior: `agent-device help lock-screen`. - On Android, `shake-rest-acceleration-unreadable` means the emulator console returned no accelerometer reading, so nothing was sent. `shake-console-refused` after a swing means the accelerometer may not be back at rest. Check with `adb emu sensor get acceleration`. - `hardware-button` presses a key once and reports the press, not what the OS did with it. Android presses every key. A physical iPhone or iPad presses volume only, iOS simulators refuse every key, and TV targets point you to `tv-remote`. - On Android, `power` toggles the screen. After a press that turns the screen off, later commands can hit a locked screen; use `hardware-button wake`, or `lock-screen unlock` to dismiss the lock screen too. -- `lock-screen` returns once the device reports the lock state, in `state`. `lock` leaves a locked screen alone. Android verifies with the keyguard state that `dumpsys window` reports, and needs a screen lock other than None. iOS simulators verify with SpringBoard's lock state and, for `lock`, a lock screen surface. On iOS, `unlock` first wakes a dark screen with the lock button, then swipes up, and also needs the screen on. `unlock` lands on the app that was in front, not on the Home Screen. On Android it always sends the wake event, which leaves a screen that is on unchanged. +- `lock-screen` returns once the device reports the lock state, in `state`. `lock` leaves a locked screen alone. Android verifies with the keyguard state that `dumpsys window` reports. On a device with a PIN, pattern, or password and "Power button instantly locks" off, the keyguard appears only after "Lock after screen timeout", so `lock` waits that long too, up to one minute. iOS simulators verify with SpringBoard's lock state and, for `lock`, a lock screen surface. On iOS, a dark screen is woken with the lock button first: `unlock` then swipes up and needs the screen on, and `lock` presses again if the screen woke unlocked. `unlock` lands on the app that was in front, not on the Home Screen. On Android it always sends the wake event, which leaves a screen that is on unchanged. - The session app is not activated, so check the result with `screenshot`. On iOS, an app-scoped command such as `snapshot` brings the session app back to the front, which can dismiss the lock screen. -- `lock-screen unlock` never enters a credential. A PIN, pattern, password, or passcode lock fails with `lock-screen-secure`; on Android nothing is sent (`dispatched: no`). `lock-screen-unverified` means the device still reports the previous state. On Android, `lock-screen-state-unreadable` means `dumpsys` reported no keyguard state or no lock type for the foreground user, and nothing was sent. +- `lock-screen unlock` never enters a credential. A PIN, pattern, password, or passcode lock fails with `lock-screen-secure`; on Android nothing is sent (`dispatched: no`). `lock-screen-unverified` means the device still reports the previous state. On Android, `lock` on a screen lock set to None fails with `lock-screen-disabled` and sends nothing (`dispatched: no`), because there is no lock screen to show. `lock-screen-state-unreadable` means `dumpsys` reported no keyguard state or no lock type for the foreground user, and nothing was sent. Fold a foldable device: diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index a15125fd1b..23719a2d8a 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -169,6 +169,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `lock-screen-secure` | The lock needs a PIN, pattern, password, or passcode, so unlock typed nothing and left it locked. | | `lock-screen-unverified` | The lock or unlock was sent, but the device still reports the previous lock state. | | `lock-screen-state-unreadable` | dumpsys reported no keyguard state, or no lock type for the foreground user, so nothing was sent. | +| `lock-screen-disabled` | The screen lock is set to None, so there is no lock screen to show; nothing was sent. | ### `logs` From ac306f6541d25292b0aa5b829e02b1f607533da9 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 10:07:44 +0530 Subject: [PATCH 08/10] fix(android): never wait under 5 s for a deferred keyguard On an Android 16 emulator with a PIN and "Power button instantly locks" off, the keyguard showed about 0.2 s after lock_screen_lock_after_timeout and never sooner than 5 s, even with the setting unset, 0 or 2000. The deferral now has that 5 s floor, so a 0 setting no longer leaves a 5 s window that ends as the keyguard appears. --- packages/platform-android/src/lock-screen.test.ts | 4 +++- packages/platform-android/src/lock-screen.ts | 15 +++++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/packages/platform-android/src/lock-screen.test.ts b/packages/platform-android/src/lock-screen.test.ts index 90ea05c43b..32decbfac0 100644 --- a/packages/platform-android/src/lock-screen.test.ts +++ b/packages/platform-android/src/lock-screen.test.ts @@ -113,9 +113,11 @@ test('lock refuses a screen lock set to None before sending anything', async () }); // With "Power button instantly locks" off, a secure keyguard waits for "Lock after screen -// timeout", so the window grows by that delay, Android's 5 s when unset, and never past 60 s. +// timeout", so the window grows by that delay: never under 5 s, measured with the setting unset, +// 0 and 2000 on an Android 16 emulator, and never past 60 s. test.each([ ['an unset delay as 5 s', 'null', 10_000], + ['a delay under 5 s as 5 s', '2000', 10_000], ['a 30 s delay', '30000', 35_000], ['a delay past one minute as 60 s', '1800000', 65_000], ])('lock on a secure device waits for %s', async (_name, lockAfterTimeout, windowMs) => { diff --git a/packages/platform-android/src/lock-screen.ts b/packages/platform-android/src/lock-screen.ts index cb219b68c3..17342b346d 100644 --- a/packages/platform-android/src/lock-screen.ts +++ b/packages/platform-android/src/lock-screen.ts @@ -20,11 +20,12 @@ const LOCK_STATE_WINDOW_MS = 5_000; const LOCK_STATE_POLL_MS = 250; /** * A secure device whose "Power button instantly locks" is off shows the keyguard only after its - * "Lock after screen timeout" delay (`lock_screen_lock_after_timeout`, 5 s when unset). The lock - * waits that long on top of its own window, up to this cap, which keeps the command inside the - * daemon's 90 s request envelope. + * "Lock after screen timeout" delay (`lock_screen_lock_after_timeout`). On an Android 16 emulator + * the keyguard showed about 0.2 s after that delay, and never sooner than 5 s, even with the + * setting unset, 0 or 2000. The lock waits that long on top of its own window, up to the cap, + * which keeps the command inside the daemon's 90 s request envelope. */ -const LOCK_AFTER_TIMEOUT_DEFAULT_MS = 5_000; +const LOCK_AFTER_TIMEOUT_MIN_MS = 5_000; const LOCK_AFTER_TIMEOUT_CAP_MS = 60_000; const SECURE_LOCK_HINT = @@ -211,7 +212,7 @@ function userBlock(dump: string, userId: number): string | undefined { return found ? lines.join('\n') : undefined; } -/** `lock_screen_lock_after_timeout` in milliseconds; an unset or unreadable value is Android's 5 s default. */ +/** How long Android defers the keyguard: `lock_screen_lock_after_timeout`, never under 5 s. */ async function readLockAfterTimeoutMs( device: DeviceInfo, signal: AbortSignal | undefined, @@ -222,5 +223,7 @@ async function readLockAfterTimeoutMs( signal, ); const value = Number.parseInt(stdout.trim(), 10); - return Number.isInteger(value) && value >= 0 ? value : LOCK_AFTER_TIMEOUT_DEFAULT_MS; + return Number.isInteger(value) + ? Math.max(value, LOCK_AFTER_TIMEOUT_MIN_MS) + : LOCK_AFTER_TIMEOUT_MIN_MS; } From c9d03acfd3fc230809133226a6625bba3a1f3c2c Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 10:07:44 +0530 Subject: [PATCH 09/10] test(ios): cover waking a dark screen before a lock The lock dispatch's decision moves into dispatchLock(screenIsBlanked:wake: readState:press:) so the runner unit tests drive it: a dark screen is woken and pressed again only while still unlocked, a lit screen is pressed once, and a wake refusal stops before any press. --- .../RunnerTests+LockScreen.swift | 30 +++++++++---- .../RunnerTests+LockScreenTests.swift | 44 +++++++++++++++++++ 2 files changed, 66 insertions(+), 8 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LockScreen.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LockScreen.swift index 6d25d46a4b..8aa9af126b 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LockScreen.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LockScreen.swift @@ -134,6 +134,22 @@ extension RunnerTests { ) } + /// Presses the lock button on a lit screen. On a blanked screen that is still unlocked, the first + /// press can wake the screen instead of locking it, so the screen is woken first and pressed + /// again only if it is still unlocked. + func dispatchLock( + screenIsBlanked: () -> Bool, + wake: () -> Response?, + readState: () -> LockScreenStateRead, + press: () -> Response? + ) -> Response? { + if screenIsBlanked() { + if let refusal = wake() { return refusal } + guard readState() == .unlocked else { return nil } + } + return press() + } + private func lockScreenUnverifiedResponse(_ message: String) -> Response { Response(ok: false, error: ErrorPayload( code: RunnerWireErrorCode.lockScreenUnverified, @@ -167,15 +183,13 @@ extension RunnerTests { return nil } - /// Presses the lock button on a lit screen. On a blanked screen that is still unlocked, the first - /// press can wake the screen instead of locking it, so the screen is woken first and pressed - /// again only if it is still unlocked. private func dispatchLock() -> Response? { - if screenIsBlanked() { - if let refusal = wakeBlankedScreen() { return refusal } - guard currentLockScreenState() == .unlocked else { return nil } - } - return dispatchLockButton() + dispatchLock( + screenIsBlanked: screenIsBlanked, + wake: wakeBlankedScreen, + readState: currentLockScreenState, + press: dispatchLockButton + ) } /// Wakes a blanked screen with the lock button, then swipes up from the bottom edge, as a person diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+LockScreenTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+LockScreenTests.swift index e9b458d976..160032d67c 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+LockScreenTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+LockScreenTests.swift @@ -111,6 +111,50 @@ extension RunnerTests { XCTAssertEqual(script.log.filter { $0 == "passcode" }.count, 0, "an unlocked screen asks for no passcode") } + /// A dark screen is woken first; the lock button is pressed again only if the wake left it unlocked. + func testLockScreenWakesADarkScreenAndPressesAgainOnlyWhileUnlocked() { + for (afterWake, presses) in [(LockScreenStateRead.unlocked, 1), (.locked, 0)] { + var log: [String] = [] + let refusal = dispatchLock( + screenIsBlanked: { true }, + wake: { log.append("wake"); return nil }, + readState: { afterWake }, + press: { log.append("press"); return nil } + ) + XCTAssertNil(refusal) + XCTAssertEqual(log, ["wake"] + Array(repeating: "press", count: presses), "\(afterWake)") + } + } + + func testLockScreenPressesALitScreenOnceWithoutWaking() { + var log: [String] = [] + let refusal = dispatchLock( + screenIsBlanked: { false }, + wake: { log.append("wake"); return nil }, + readState: { .unlocked }, + press: { log.append("press"); return nil } + ) + XCTAssertNil(refusal) + XCTAssertEqual(log, ["press"]) + } + + func testLockScreenPropagatesAWakeRefusalWithoutPressing() { + var presses = 0 + let refusal = dispatchLock( + screenIsBlanked: { true }, + wake: { + Response(ok: false, error: ErrorPayload( + code: RunnerWireErrorCode.hardwareControlUnavailable, + message: "no lock button" + )) + }, + readState: { .unlocked }, + press: { presses += 1; return nil } + ) + XCTAssertEqual(refusal?.error?.code, RunnerWireErrorCode.hardwareControlUnavailable) + XCTAssertEqual(presses, 0) + } + func testLockScreenNeverAsksForAPasscodePrompt() { let script = LockScreenScript(reads: [.unlocked], waitsAllowed: 1) script.passcodePrompt = true From e55a5d4d7c58d21c8f915023b5e824bead76ed13 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 10:14:12 +0530 Subject: [PATCH 10/10] docs(lock-screen): state the 5 s floor of the deferred keyguard wait --- website/docs/docs/commands.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 770351ebe7..c4677e226d 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -387,7 +387,7 @@ Exact behavior: `agent-device help lock-screen`. - On Android, `shake-rest-acceleration-unreadable` means the emulator console returned no accelerometer reading, so nothing was sent. `shake-console-refused` after a swing means the accelerometer may not be back at rest. Check with `adb emu sensor get acceleration`. - `hardware-button` presses a key once and reports the press, not what the OS did with it. Android presses every key. A physical iPhone or iPad presses volume only, iOS simulators refuse every key, and TV targets point you to `tv-remote`. - On Android, `power` toggles the screen. After a press that turns the screen off, later commands can hit a locked screen; use `hardware-button wake`, or `lock-screen unlock` to dismiss the lock screen too. -- `lock-screen` returns once the device reports the lock state, in `state`. `lock` leaves a locked screen alone. Android verifies with the keyguard state that `dumpsys window` reports. On a device with a PIN, pattern, or password and "Power button instantly locks" off, the keyguard appears only after "Lock after screen timeout", so `lock` waits that long too, up to one minute. iOS simulators verify with SpringBoard's lock state and, for `lock`, a lock screen surface. On iOS, a dark screen is woken with the lock button first: `unlock` then swipes up and needs the screen on, and `lock` presses again if the screen woke unlocked. `unlock` lands on the app that was in front, not on the Home Screen. On Android it always sends the wake event, which leaves a screen that is on unchanged. +- `lock-screen` returns once the device reports the lock state, in `state`. `lock` leaves a locked screen alone. Android verifies with the keyguard state that `dumpsys window` reports. On a device with a PIN, pattern, or password and "Power button instantly locks" off, the keyguard appears only after "Lock after screen timeout", so `lock` waits that long too: at least 5 s, which Android applies even to a shorter setting, and at most one minute. iOS simulators verify with SpringBoard's lock state and, for `lock`, a lock screen surface. On iOS, a dark screen is woken with the lock button first: `unlock` then swipes up and needs the screen on, and `lock` presses again if the screen woke unlocked. `unlock` lands on the app that was in front, not on the Home Screen. On Android it always sends the wake event, which leaves a screen that is on unchanged. - The session app is not activated, so check the result with `screenshot`. On iOS, an app-scoped command such as `snapshot` brings the session app back to the front, which can dismiss the lock screen. - `lock-screen unlock` never enters a credential. A PIN, pattern, password, or passcode lock fails with `lock-screen-secure`; on Android nothing is sent (`dispatched: no`). `lock-screen-unverified` means the device still reports the previous state. On Android, `lock` on a screen lock set to None fails with `lock-screen-disabled` and sends nothing (`dispatched: no`), because there is no lock screen to show. `lock-screen-state-unreadable` means `dumpsys` reported no keyguard state or no lock type for the foreground user, and nothing was sent.