From f1e3508aac9561468682252437e61ced11d5e665 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 14:39:15 +0100 Subject: [PATCH 01/20] feat(apple-runner): build the XCUITest runner for the watchOS simulator The runner's host app and UI-test targets add the watchOS simulator SDK. A SwiftUI host replaces the UIKit host there. The runner gains watchOS branches: scroll turns the Digital Crown, back presses the navigation bar back button or swipes from the left edge, typing goes through the system input sheet, and one-finger planned gestures use the event synthesizer. Build, clean, and package scripts learn the watchos platform. Part of #4738. Co-Authored-By: Claude Opus 5.5 --- .../project.pbxproj | 32 +++- .../AgentDeviceRunner/AgentDeviceRunnerApp.m | 3 +- .../AgentDeviceRunnerWatchApp.swift | 12 ++ .../RunnerTests+CommandExecution.swift | 3 + .../RunnerTests+Interaction.swift | 4 +- .../RunnerTests+Navigation.swift | 2 + .../RunnerTests+Orientation.swift | 4 +- .../RunnerTests+ScreenRecorder.swift | 21 +++ .../RunnerTests+SynthesizedInteraction.swift | 2 + .../RunnerTests+TypeExecution.swift | 3 + .../RunnerTests+WatchInteraction.swift | 159 ++++++++++++++++++ .../RunnerTests.swift | 6 +- apple/snapshot-presentation/Package.swift | 1 + package.json | 3 + .../runner-toolchain-identity.test.ts | 2 + .../apple-runner/src/apple-runner-platform.ts | 31 +++- .../src/runner-toolchain-identity.ts | 6 +- packages/contracts/src/interactor-types.ts | 1 + .../src/core/__tests__/runner-script.test.ts | 2 +- .../platform-apple/src/core/runner-script.ts | 4 +- .../test-kit/src/apple-toolchain-fixtures.ts | 2 + .../__tests__/build-package-xcuitest.test.ts | 2 +- scripts/build-package-xcuitest.mjs | 2 +- scripts/build-xcuitest-apple.sh | 8 +- scripts/check-affected/device-lanes.ts | 3 +- scripts/clean-xcuitest-derived.mjs | 1 + scripts/write-xcuitest-cache-metadata.ts | 2 +- scripts/xcuitest-build-settings.ts | 2 +- 28 files changed, 297 insertions(+), 26 deletions(-) create mode 100644 apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerWatchApp.swift create mode 100644 apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj b/apple/runner/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj index 89b7ac51a3..1b3291f153 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj @@ -367,6 +367,12 @@ GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = AgentDeviceRunner/Info.plist; "INFOPLIST_FILE[sdk=macosx*]" = ""; + "INFOPLIST_FILE[sdk=watchsimulator*]" = ""; + "INFOPLIST_KEY_WKApplication[sdk=watchsimulator*]" = YES; + "INFOPLIST_KEY_WKWatchOnly[sdk=watchsimulator*]" = YES; + // The SwiftUI watch host replaces the Objective-C UIKit host on watchOS only. + EXCLUDED_SOURCE_FILE_NAMES = AgentDeviceRunnerWatchApp.swift; + "EXCLUDED_SOURCE_FILE_NAMES[sdk=watchsimulator*]" = ""; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = NO; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; INFOPLIST_KEY_UILaunchScreen_Generation = YES; @@ -387,9 +393,10 @@ SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; SWIFT_VERSION = 5.0; - SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator xros xrsimulator"; - TARGETED_DEVICE_FAMILY = "1,2,3,7"; + SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator xros xrsimulator watchsimulator"; + TARGETED_DEVICE_FAMILY = "1,2,3,4,7"; TVOS_DEPLOYMENT_TARGET = 15.6; + WATCHOS_DEPLOYMENT_TARGET = 10.0; }; name = Debug; }; @@ -403,6 +410,12 @@ GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = AgentDeviceRunner/Info.plist; "INFOPLIST_FILE[sdk=macosx*]" = ""; + "INFOPLIST_FILE[sdk=watchsimulator*]" = ""; + "INFOPLIST_KEY_WKApplication[sdk=watchsimulator*]" = YES; + "INFOPLIST_KEY_WKWatchOnly[sdk=watchsimulator*]" = YES; + // The SwiftUI watch host replaces the Objective-C UIKit host on watchOS only. + EXCLUDED_SOURCE_FILE_NAMES = AgentDeviceRunnerWatchApp.swift; + "EXCLUDED_SOURCE_FILE_NAMES[sdk=watchsimulator*]" = ""; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = NO; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; INFOPLIST_KEY_UILaunchScreen_Generation = YES; @@ -423,9 +436,10 @@ SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; SWIFT_VERSION = 5.0; - SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator xros xrsimulator"; - TARGETED_DEVICE_FAMILY = "1,2,3,7"; + SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator xros xrsimulator watchsimulator"; + TARGETED_DEVICE_FAMILY = "1,2,3,4,7"; TVOS_DEPLOYMENT_TARGET = 15.6; + WATCHOS_DEPLOYMENT_TARGET = 10.0; }; name = Release; }; @@ -456,9 +470,10 @@ SWIFT_OBJC_BRIDGING_HEADER = "AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h"; SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; SWIFT_VERSION = 5.0; - SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator xros xrsimulator"; - TARGETED_DEVICE_FAMILY = "1,2,3,7"; + SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator xros xrsimulator watchsimulator"; + TARGETED_DEVICE_FAMILY = "1,2,3,4,7"; TVOS_DEPLOYMENT_TARGET = 15.6; + WATCHOS_DEPLOYMENT_TARGET = 10.0; TEST_TARGET_NAME = AgentDeviceRunner; }; name = Debug; @@ -487,9 +502,10 @@ SWIFT_OBJC_BRIDGING_HEADER = "AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h"; SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; SWIFT_VERSION = 5.0; - SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator xros xrsimulator"; - TARGETED_DEVICE_FAMILY = "1,2,3,7"; + SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator xros xrsimulator watchsimulator"; + TARGETED_DEVICE_FAMILY = "1,2,3,4,7"; TVOS_DEPLOYMENT_TARGET = 15.6; + WATCHOS_DEPLOYMENT_TARGET = 10.0; TEST_TARGET_NAME = AgentDeviceRunner; }; name = Release; diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m b/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m index 3c6bc8f59e..93d60ee3d4 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m @@ -53,7 +53,8 @@ int main(int argc, const char *argv[]) { return 0; } -#else +// watchOS has no UIApplicationMain. Its host is AgentDeviceRunnerWatchApp.swift. +#elif !TARGET_OS_WATCH #import "AgentDeviceRunnerApp.h" #import diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerWatchApp.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerWatchApp.swift new file mode 100644 index 0000000000..f1d7e4fc13 --- /dev/null +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerWatchApp.swift @@ -0,0 +1,12 @@ +import SwiftUI + +/// The watchOS host the runner's XCTest bundle launches. The runner drives other apps by bundle ID, +/// so the host shows only its title, like the UIKit host on the other Apple OSes. +@main +struct AgentDeviceRunnerWatchApp: App { + var body: some Scene { + WindowGroup { + Text("Agent Device Runner") + } + } +} diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift index 03d14d5996..741186b39b 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift @@ -303,6 +303,9 @@ extension RunnerTests { else { return invalidScrollDirectionResponse(commandName: "scroll") } +#if os(watchOS) + return try watchCrownScroll(app: activeApp, command: command, direction: direction) +#endif guard let scrollContext = try synthesizedCoordinateContext(app: activeApp) else { return Response( ok: false, diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift index 767a6cec36..714dc66743 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift @@ -251,8 +251,8 @@ extension RunnerTests { /// lower, so an older system refuses rather than pressing a control that cannot exist there. @discardableResult func pressActionButton() -> Bool { -#if os(iOS) - guard #available(iOS 16.0, *) else { return false } +#if os(iOS) || os(watchOS) + guard #available(iOS 16.0, watchOS 9.0, *) else { return false } guard XCUIDevice.shared.hasHardwareButton(.action) else { return false } XCUIDevice.shared.press(.action) return true diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift index 7376f426a1..12f97bad61 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift @@ -149,6 +149,8 @@ extension RunnerTests { logSwipe(trace.logLine(name: "error", code: String(describing: type(of: error)))) throw error } +#elseif os(watchOS) + return try performWatchBack(app: app) #else // visionOS has no back command. The daemon refuses it at the back capability fact, so this // answers only a direct runner request, with nothing sent. diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Orientation.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Orientation.swift index 45ef96f5e1..1858750059 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Orientation.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Orientation.swift @@ -45,7 +45,7 @@ extension RunnerTests { } private func rotateDevice(to orientationName: String) -> String? { -#if os(macOS) || os(tvOS) || os(visionOS) +#if os(macOS) || os(tvOS) || os(visionOS) || os(watchOS) return nil #else switch orientationName { @@ -72,7 +72,7 @@ extension RunnerTests { } private func observedDeviceOrientation() -> String? { -#if os(macOS) || os(tvOS) || os(visionOS) +#if os(macOS) || os(tvOS) || os(visionOS) || os(watchOS) return nil #else switch XCUIDevice.shared.orientation { diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift index 0bfe1a2e64..f261e5bca2 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift @@ -4,6 +4,26 @@ import CoreVideo extension RunnerTests { // MARK: - Screen Recorder + #if os(watchOS) + /// watchOS has no `AVAssetWriter`. The daemon refuses recording on a watch, so this answers only a + /// direct runner request. + final class ScreenRecorder { + init(outputPath: String, fps: Int32?) {} + + func start( + bootstrap: () -> Result, + frame: @escaping @Sendable () -> RunnerImage? + ) throws { + throw NSError( + domain: "AgentDeviceRunner.Record", + code: 2, + userInfo: [NSLocalizedDescriptionKey: "runner recording is unavailable on watchOS"] + ) + } + + func stop() throws {} + } + #else final class ScreenRecorder { private let outputPath: String private let fps: Int32? @@ -291,6 +311,7 @@ extension RunnerTests { } } + #endif } extension RunnerTests { diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift index 9254c5cc85..fb31e6895c 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift @@ -871,6 +871,8 @@ extension RunnerTests { message: "multi-touch gestures are not supported on tvOS", hint: "tvOS has no touch input; use remote-driven navigation." ) +#elseif os(watchOS) + return try watchSampledPlannedGesture(app: app, plan: plan) #elseif os(visionOS) return .unsupported( message: "multi-touch gestures are not supported on visionOS", diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TypeExecution.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TypeExecution.swift index aaf9af4cc6..d3d16f15fe 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TypeExecution.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TypeExecution.swift @@ -22,6 +22,9 @@ extension RunnerTests { guard let text = command.text else { return Response(ok: false, error: ErrorPayload(message: "type requires text")) } +#if os(watchOS) + return try watchTypeCommandResponse(activeApp: activeApp, command: command, text: text) +#endif let delaySeconds = Double(max(command.delayMs ?? 0, 0)) / 1000.0 let textEntryMode = resolveTextEntryMode(command) let target: TextEntryTarget diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift new file mode 100644 index 0000000000..83d5225ff7 --- /dev/null +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift @@ -0,0 +1,159 @@ +#if os(watchOS) +import XCTest + +// The watchOS leaf of the runner: the Digital Crown, the system text input sheet, back, and +// one-finger synthesized gestures. Everything else a watch admits runs the shared paths. +extension RunnerTests { + /// Crown rotations that scroll about one viewport. Measured on watchOS 27 simulators: half a turn + /// moved a Settings list by one screen height. + static let watchCrownRotationsPerViewport = 0.5 + /// How long the input sheet may take to appear after the tap that focuses a field. + static let watchInputSheetTimeout: TimeInterval = 3.0 + /// The input sheet's commit button. The sheet exposes no identifier for it. + static let watchInputSheetDoneLabel = "Done" + + /// `scroll` on a watch turns the Digital Crown, the watch's scroll input. The crown is vertical, + /// so a horizontal scroll is refused; horizontal pages answer `swipe`. + @MainActor + func watchCrownScroll(app: XCUIApplication, command: Command, direction: RunnerScrollDirection) throws -> Response { + guard direction.isVertical else { + return Response(ok: false, error: ErrorPayload( + code: "UNSUPPORTED_OPERATION", + message: "scroll \(direction.rawValue) is not supported on watchOS", + hint: "The Digital Crown scrolls vertically. Use swipe for horizontal pages." + )) + } + let viewportFraction: Double + if let pixels = command.pixels { + let height = try resolvedTouchReferenceFrame(app: app).height + guard height > 0 else { + return Response(ok: false, error: ErrorPayload(message: "scroll could not resolve a usable interaction frame")) + } + viewportFraction = pixels / Double(height) + } else if let amount = runnerDragCommandDefaults(command).scrollAmount { + viewportFraction = amount + } else { + return Response(ok: false, error: ErrorPayload(code: "INVALID_ARGS", message: "scroll requires an amount or pixels")) + } + let delta = viewportFraction * Self.watchCrownRotationsPerViewport + let timing = measureGesture { + withBoundedInteractionIdleTimeoutIfSupported(app, waits: .bothSkipped) { + XCUIDevice.shared.rotateDigitalCrown(delta: direction == .down ? delta : -delta) + } + } + return gestureResponse(message: "scrolled", timing: timing) + } + + /// Back on a watch presses the navigation bar's back button, else swipes in from the left edge, + /// the two ways watchOS pops a navigation stack. + @MainActor + func performWatchBack(app: XCUIApplication) throws -> InAppBackOutcome { + let button = app.buttons[Self.navigationBarBackButtonIdentifier] + if button.exists, button.isHittable { + let frame = button.frame + _ = try tapAt(app: app, x: frame.midX, y: frame.midY) + return .performed + } + let surface = try resolvedTouchReferenceFrame(app: app) + _ = try dragAt( + app: app, + x: surface.minX + 1, + y: surface.midY, + x2: surface.minX + surface.width * 0.8, + y2: surface.midY, + holdDuration: coordinateDragHoldDuration() + ) + return .performed + } + + /// A one-finger planned gesture through the private synthesizer, which keeps the plan's timing. A + /// watch has no rotation and its app fills the screen, so plan points are digitizer points. + @MainActor + func watchSampledPlannedGesture(app: XCUIApplication, plan: RunnerGesturePlan) throws -> RunnerInteractionOutcome { + guard plan.pointers.count == 1 else { + return .unsupported( + message: "multi-touch gestures are not supported on watchOS", + hint: "watchOS apps have no multi-touch gestures. Use swipe, gesture pan, or scroll." + ) + } + let pointerSamples: [[[String: NSNumber]]] = plan.pointers.map { pointer in + pointer.samples.map { sample in + [ + "x": NSNumber(value: sample.point.x), + "y": NSNumber(value: sample.point.y), + "offsetMs": NSNumber(value: sample.offsetMs), + ] + } + } + var dispatched: ObjCBool = false + let failure = RunnerSynthesizedGesture.synthesizeGesture( + withApplication: app, + resolvedWindow: app.windows.firstMatch, + interfaceOrientation: 1, + pointerSamples: pointerSamples, + dispatched: &dispatched + ) + return try Self.synthesizedGestureOutcome( + failure: failure, + dispatched: dispatched.boolValue, + refusalHint: "This gesture uses private XCTest event-synthesis APIs; rebuild the runner with a supported Xcode if this persists." + ) + } + + /// watchOS edits text in a system input sheet that a field tap opens; the field itself never takes + /// keyboard focus. Typing goes to the sheet, and Done commits it to the field. + @MainActor + func watchTypeCommandResponse(activeApp: XCUIApplication, command: Command, text: String) throws -> Response { + var point: CGPoint? + if let x = command.x, let y = command.y { + if case .unsupported(let message, let hint) = try tapAt(app: activeApp, x: x, y: y) { + return Response(ok: false, error: ErrorPayload(message: message, hint: hint)) + } + point = CGPoint(x: x, y: y) + } + guard waitForWatchInputSheet(app: activeApp) else { + let failure = TextEntryFailure.notFocused + return Response(ok: false, error: ErrorPayload( + code: failure.rawValue, + message: failure.message, + hint: "Press the text field first. On watchOS the field opens a system input sheet, and the text goes there." + )) + } + withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .bothSkipped) { + if resolveTextEntryMode(command) == .replacement { + let existing = (activeApp.textViews.firstMatch.value as? String) ?? "" + if !existing.isEmpty { + activeApp.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: existing.count)) + } + } + activeApp.typeText(text) + } + let done = activeApp.buttons[Self.watchInputSheetDoneLabel] + guard done.exists else { + return Response(ok: false, error: ErrorPayload( + code: TextEntryFailure.commitNotObserved.rawValue, + message: "the watchOS input sheet has no Done button to commit the text", + hint: "The text is typed into the open input sheet. Press its commit button by ref." + )) + } + withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .bothSkipped) { + done.tap() + } + return Response(ok: true, data: DataPayload( + message: "typed", + x: point.map { Double($0.x) }, + y: point.map { Double($0.y) }, + textEntryRoute: "watch-input-sheet" + )) + } + + private func waitForWatchInputSheet(app: XCUIApplication) -> Bool { + let deadline = Date().addingTimeInterval(Self.watchInputSheetTimeout) + repeat { + if app.keyboards.firstMatch.exists { return true } + RunLoop.current.run(until: Date().addingTimeInterval(TextEntryTiming.pollInterval * 5)) + } while Date() < deadline + return false + } +} +#endif diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift index 73e11c0456..0b87537131 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift @@ -97,10 +97,10 @@ final class RunnerTests: XCTestCase { } static let springboardBundleId = "com.apple.springboard" - // SpringBoard hosts blocking system modals on iOS/visionOS; tvOS (PineBoard/HeadBoard) - // and macOS have no such host, so there is nothing to probe there. + // SpringBoard hosts blocking system modals on iOS/visionOS; tvOS (PineBoard/HeadBoard), + // watchOS (Carousel), and macOS have no such host, so there is nothing to probe there. static let hasSpringBoardSystemModalHost: Bool = { - #if os(tvOS) || os(macOS) + #if os(tvOS) || os(macOS) || os(watchOS) return false #else return true diff --git a/apple/snapshot-presentation/Package.swift b/apple/snapshot-presentation/Package.swift index 018a655709..d9c9f14cef 100644 --- a/apple/snapshot-presentation/Package.swift +++ b/apple/snapshot-presentation/Package.swift @@ -8,6 +8,7 @@ let package = Package( .macOS(.v13), .tvOS(.v15), .visionOS(.v1), + .watchOS(.v10), ], products: [ .library( diff --git a/package.json b/package.json index a90cbfa132..a34b43f974 100644 --- a/package.json +++ b/package.json @@ -95,6 +95,7 @@ "clean:xcuitest:macos": "node --experimental-strip-types scripts/clean-xcuitest-derived.mjs macos", "clean:xcuitest:tvos": "node --experimental-strip-types scripts/clean-xcuitest-derived.mjs tvos", "clean:xcuitest:visionos": "node --experimental-strip-types scripts/clean-xcuitest-derived.mjs visionos", + "clean:xcuitest:watchos": "node --experimental-strip-types scripts/clean-xcuitest-derived.mjs watchos", "rebuild:cli": "pnpm build && pnpm clean:daemon", "build:xcuitest": "pnpm build:xcuitest:ios && pnpm build:xcuitest:macos", "build:xcuitest:ios": "AGENT_DEVICE_XCUITEST_PLATFORM=ios sh ./scripts/build-xcuitest-apple.sh", @@ -105,6 +106,8 @@ "build:xcuitest:tvos:clean": "pnpm clean:xcuitest:tvos && pnpm build:xcuitest:tvos", "build:xcuitest:visionos": "AGENT_DEVICE_XCUITEST_PLATFORM=visionos sh ./scripts/build-xcuitest-apple.sh", "build:xcuitest:visionos:clean": "pnpm clean:xcuitest:visionos && pnpm build:xcuitest:visionos", + "build:xcuitest:watchos": "AGENT_DEVICE_XCUITEST_PLATFORM=watchos sh ./scripts/build-xcuitest-apple.sh", + "build:xcuitest:watchos:clean": "pnpm clean:xcuitest:watchos && pnpm build:xcuitest:watchos", "package:xcuitest": "node scripts/build-package-xcuitest.mjs", "generate:recording-swift-sources": "node --experimental-strip-types scripts/generate-recording-swift-sources.ts", "build:android-snapshot-helper": "AGENT_DEVICE_ANDROID_HELPER=snapshot sh ./scripts/build-android-helper.sh $(node -p \"require('./package.json').version\") .tmp/android-snapshot-helper", diff --git a/packages/apple-runner/src/__tests__/runner-toolchain-identity.test.ts b/packages/apple-runner/src/__tests__/runner-toolchain-identity.test.ts index 889ba6abf6..c9ab868ecd 100644 --- a/packages/apple-runner/src/__tests__/runner-toolchain-identity.test.ts +++ b/packages/apple-runner/src/__tests__/runner-toolchain-identity.test.ts @@ -177,6 +177,8 @@ test('each runner SDK reads its version and build from its own platform director macosx: 'MacOSX', xrsimulator: 'XRSimulator', xros: 'XROS', + watchsimulator: 'WatchSimulator', + watchos: 'WatchOS', }; const expected = Object.entries(sdkDirectories).map(([sdkName, directory], index) => { const sdk = path.join( diff --git a/packages/apple-runner/src/apple-runner-platform.ts b/packages/apple-runner/src/apple-runner-platform.ts index 4ca09c3d8b..8066ef8846 100644 --- a/packages/apple-runner/src/apple-runner-platform.ts +++ b/packages/apple-runner/src/apple-runner-platform.ts @@ -32,7 +32,7 @@ export const SHARED_SNAPSHOT_BRIDGE_READER_FILENAMES = [ SHARED_FOREGROUND_GEOMETRY_HEADER_FILENAME, ] as const; -export type RunnerApplePlatformName = 'iOS' | 'tvOS' | 'macOS' | 'visionOS'; +export type RunnerApplePlatformName = 'iOS' | 'tvOS' | 'macOS' | 'visionOS' | 'watchOS'; type RunnerPlatformDeviceKind = 'simulator' | 'device'; @@ -137,6 +137,35 @@ const RUNNER_PLATFORM_PROFILES: Record = { macosx: 'MacOSX', xrsimulator: 'XRSimulator', xros: 'XROS', + watchsimulator: 'WatchSimulator', + watchos: 'WatchOS', }; /** The symlink `xcode-select -s` writes and `xcode-select -p` reads back. */ diff --git a/packages/contracts/src/interactor-types.ts b/packages/contracts/src/interactor-types.ts index 515a961501..be8c4e12ba 100644 --- a/packages/contracts/src/interactor-types.ts +++ b/packages/contracts/src/interactor-types.ts @@ -132,6 +132,7 @@ export const TEXT_ENTRY_ROUTES = [ 'synthesized-first-responder', 'synthesized-first-responder-replacement', 'xctest-application-fallback', + 'watch-input-sheet', ] as const; export type TextEntryRoute = (typeof TEXT_ENTRY_ROUTES)[number]; diff --git a/packages/platform-apple/src/core/__tests__/runner-script.test.ts b/packages/platform-apple/src/core/__tests__/runner-script.test.ts index 8dd6025ccd..89952f54ad 100644 --- a/packages/platform-apple/src/core/__tests__/runner-script.test.ts +++ b/packages/platform-apple/src/core/__tests__/runner-script.test.ts @@ -45,7 +45,7 @@ test('resolveRunnerScriptDevice refuses a destination that leaves the SDK to the test('isRunnerXcuitestScriptPlatform accepts only the platforms the build script knows', () => { assert.equal(isRunnerXcuitestScriptPlatform('ios'), true); assert.equal(isRunnerXcuitestScriptPlatform('visionos'), true); - assert.equal(isRunnerXcuitestScriptPlatform('watchos'), false); + assert.equal(isRunnerXcuitestScriptPlatform('watchos'), true); assert.equal(isRunnerXcuitestScriptPlatform('iOS'), false); assert.equal(isRunnerXcuitestScriptPlatform(''), false); }); diff --git a/packages/platform-apple/src/core/runner-script.ts b/packages/platform-apple/src/core/runner-script.ts index 11aee6cd3e..7633d4ed03 100644 --- a/packages/platform-apple/src/core/runner-script.ts +++ b/packages/platform-apple/src/core/runner-script.ts @@ -8,7 +8,7 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; * record; this module owns the script-side platform vocabulary, so the runner entry carries none of it. */ -const RUNNER_XCUITEST_SCRIPT_PLATFORMS = ['ios', 'macos', 'tvos', 'visionos'] as const; +const RUNNER_XCUITEST_SCRIPT_PLATFORMS = ['ios', 'macos', 'tvos', 'visionos', 'watchos'] as const; export type RunnerXcuitestScriptPlatform = (typeof RUNNER_XCUITEST_SCRIPT_PLATFORMS)[number]; export function isRunnerXcuitestScriptPlatform( @@ -25,6 +25,7 @@ const RUNNER_SCRIPT_TARGET: Record< macos: 'desktop', tvos: 'tv', visionos: 'mobile', + watchos: 'mobile', }; const RUNNER_SCRIPT_APPLE_OS: Record< @@ -35,6 +36,7 @@ const RUNNER_SCRIPT_APPLE_OS: Record< macos: 'macos', tvos: 'tvos', visionos: 'visionos', + watchos: 'watchos', }; /** diff --git a/packages/test-kit/src/apple-toolchain-fixtures.ts b/packages/test-kit/src/apple-toolchain-fixtures.ts index 715db61f72..bed2fff77b 100644 --- a/packages/test-kit/src/apple-toolchain-fixtures.ts +++ b/packages/test-kit/src/apple-toolchain-fixtures.ts @@ -19,6 +19,8 @@ const SDK_DIRECTORY_NAMES = [ 'MacOSX', 'XRSimulator', 'XROS', + 'WatchSimulator', + 'WatchOS', ]; function plist(entries: Record): string { diff --git a/scripts/__tests__/build-package-xcuitest.test.ts b/scripts/__tests__/build-package-xcuitest.test.ts index 4a34da404f..783cb80ccc 100644 --- a/scripts/__tests__/build-package-xcuitest.test.ts +++ b/scripts/__tests__/build-package-xcuitest.test.ts @@ -21,7 +21,7 @@ test('builds every platform into a scratch directory under the repo and removes assert.deepEqual( seen.map(({ platform }) => platform), - ['ios', 'macos', 'tvos', 'visionos'], + ['ios', 'macos', 'tvos', 'visionos', 'watchos'], ); for (const { derivedPath } of seen) { assert.equal(path.dirname(derivedPath), path.join(root, '.tmp', 'package-xcuitest')); diff --git a/scripts/build-package-xcuitest.mjs b/scripts/build-package-xcuitest.mjs index 0bba87fce9..337f3598ae 100644 --- a/scripts/build-package-xcuitest.mjs +++ b/scripts/build-package-xcuitest.mjs @@ -4,7 +4,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; -const PLATFORMS = ['ios', 'macos', 'tvos', 'visionos']; +const PLATFORMS = ['ios', 'macos', 'tvos', 'visionos', 'watchos']; /** * Compiles the Apple runner for every platform the package supports, into a scratch directory diff --git a/scripts/build-xcuitest-apple.sh b/scripts/build-xcuitest-apple.sh index 3c1c6402d6..f75b2102ee 100644 --- a/scripts/build-xcuitest-apple.sh +++ b/scripts/build-xcuitest-apple.sh @@ -6,7 +6,7 @@ PROJECT_PATH="apple/runner/AgentDeviceRunner/AgentDeviceRunner.xcodeproj" SCHEME="AgentDeviceRunner" if [ -z "$PLATFORM" ]; then - echo "AGENT_DEVICE_XCUITEST_PLATFORM is required (ios, macos, tvos, visionos)" >&2 + echo "AGENT_DEVICE_XCUITEST_PLATFORM is required (ios, macos, tvos, visionos, watchos)" >&2 exit 1 fi @@ -35,6 +35,9 @@ resolve_default_destination() { visionos) resolve_simulator_destination 'visionOS' 'Apple Vision' || printf '%s\n' 'generic/platform=visionOS Simulator' ;; + watchos) + resolve_simulator_destination 'watchOS' 'Apple Watch' || printf '%s\n' 'generic/platform=watchOS Simulator' + ;; *) echo "Unsupported AGENT_DEVICE_XCUITEST_PLATFORM: $PLATFORM" >&2 exit 1 @@ -90,6 +93,9 @@ resolve_default_derived_path() { visionos) printf '%s\n' "$HOME/.agent-device/apple-runner/derived/visionos" ;; + watchos) + printf '%s\n' "$HOME/.agent-device/apple-runner/derived/watchos" + ;; *) echo "Unsupported AGENT_DEVICE_XCUITEST_PLATFORM: $PLATFORM" >&2 exit 1 diff --git a/scripts/check-affected/device-lanes.ts b/scripts/check-affected/device-lanes.ts index 035f8f8de4..fcb35f17b9 100644 --- a/scripts/check-affected/device-lanes.ts +++ b/scripts/check-affected/device-lanes.ts @@ -51,7 +51,7 @@ const LEAF_LANES: Readonly> = { }; // Directory segments that tag a path with a family. Apple's leaves are separate tags so a -// macOS-only tree does not own the iOS lane; a tree tagged `apple` (or `tvos`/`visionos`/ +// macOS-only tree does not own the iOS lane; a tree tagged `apple` (or `tvos`/`visionos`/`watchos`/ // `xcuitest`, whose only lanes today are the Apple family's, or `apple-runner`, the Apple-family // runner engine package) owns every Apple lane. const APPLE_LEAF_TAGS: Readonly> = { @@ -62,6 +62,7 @@ const APPLE_LEAF_TAGS: Readonly> = { 'apple-runner': 'apple', tvos: 'apple', visionos: 'apple', + watchos: 'apple', xcuitest: 'apple', }; diff --git a/scripts/clean-xcuitest-derived.mjs b/scripts/clean-xcuitest-derived.mjs index fe5a7cbc6a..504a233ba8 100644 --- a/scripts/clean-xcuitest-derived.mjs +++ b/scripts/clean-xcuitest-derived.mjs @@ -17,6 +17,7 @@ const PLATFORM_LABELS = new Map([ ['macos', 'macOS'], ['tvos', 'tvOS'], ['visionos', 'visionOS'], + ['watchos', 'watchOS'], ]); const requested = platforms.length > 0 ? platforms : [...PLATFORM_LABELS.keys()]; const MAX_SUMMARY_ENTRY_NAMES = 3; diff --git a/scripts/write-xcuitest-cache-metadata.ts b/scripts/write-xcuitest-cache-metadata.ts index fdc2686648..81812cacb3 100644 --- a/scripts/write-xcuitest-cache-metadata.ts +++ b/scripts/write-xcuitest-cache-metadata.ts @@ -17,7 +17,7 @@ import { } from '@agent-device/platform-apple/runner/operations'; const USAGE = - 'Usage: write-xcuitest-cache-metadata.ts '; + 'Usage: write-xcuitest-cache-metadata.ts '; /** * Publishes the cache metadata for a `scripts/build-xcuitest-apple.sh` build. The identity half diff --git a/scripts/xcuitest-build-settings.ts b/scripts/xcuitest-build-settings.ts index 4d6782083a..e8fd5f3e1f 100644 --- a/scripts/xcuitest-build-settings.ts +++ b/scripts/xcuitest-build-settings.ts @@ -13,7 +13,7 @@ import { resolveRunnerSigningBuildSettings, } from '@agent-device/platform-apple/runner/operations'; -const USAGE = 'Usage: xcuitest-build-settings.ts '; +const USAGE = 'Usage: xcuitest-build-settings.ts '; /** The `xcodebuild` build settings `scripts/build-xcuitest-apple.sh` is about to run with. */ function resolveXcuitestBuildSettings( From 7f0d8dc855b3e1b0fcdf095819724a5cfe23ce27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 14:39:16 +0100 Subject: [PATCH 02/20] feat(apple): admit watchOS simulators through one watch fact leaf Discovery classifies watch simulators as appleOs watchos and ranks them last for --platform ios. The interactor sentinel is gone. os/watchos/facts.ts admits only operations with a watch meaning (lifecycle, snapshot, touch, swipe and pan, the Digital Crown, back, typing, screenshots, the Action Button) and refuses the rest, so the per-module watchOS checks are removed. A physical watch is refused. Closes #4738. Co-Authored-By: Claude Opus 5.5 --- .../src/interaction/metadata.ts | 2 +- packages/command-surface/src/system/index.ts | 8 +- packages/contracts/src/gesture-admission.ts | 3 +- packages/kernel/src/device.ts | 17 +-- .../interactor-watchos-sentinel.test.ts | 56 ------- .../src/deployment/runtime.test.ts | 14 -- .../platform-apple/src/deployment/runtime.ts | 2 +- .../platform-apple/src/gesture-facts.test.ts | 8 +- packages/platform-apple/src/gesture-facts.ts | 8 +- packages/platform-apple/src/interactor.ts | 10 -- .../src/inventory-classification.ts | 5 +- .../platform-apple/src/logs/runtime.test.ts | 26 ---- packages/platform-apple/src/logs/runtime.ts | 25 ---- packages/platform-apple/src/logs/start.ts | 3 - .../platform-apple/src/multitouch-support.ts | 2 + .../src/navigation/runtime.test.ts | 2 +- .../platform-apple/src/navigation/runtime.ts | 36 ++--- .../src/os/watchos/facts.test.ts | 91 ++++++++++++ .../platform-apple/src/os/watchos/facts.ts | 94 ++++++++++++ .../platform-apple/src/recording/runtime.ts | 2 - .../src/runner-interaction-facts.ts | 21 +-- packages/platform-apple/src/runtime.test.ts | 138 ++++++++---------- packages/platform-apple/src/runtime.ts | 47 ++---- .../src/shutdown/runtime.test.ts | 4 +- .../platform-apple/src/shutdown/runtime.ts | 2 +- .../src/simulator-inventory.test.ts | 14 +- .../platform-apple/src/system/runtime.test.ts | 20 +-- packages/platform-apple/src/system/runtime.ts | 16 +- ...criptor-shutdown-runtime-execution.test.ts | 2 +- ...-runtime-gateway-gesture-admission.test.ts | 3 +- 30 files changed, 320 insertions(+), 361 deletions(-) delete mode 100644 packages/platform-apple/src/__tests__/interactor-watchos-sentinel.test.ts create mode 100644 packages/platform-apple/src/os/watchos/facts.test.ts create mode 100644 packages/platform-apple/src/os/watchos/facts.ts diff --git a/packages/command-surface/src/interaction/metadata.ts b/packages/command-surface/src/interaction/metadata.ts index 68c04f406d..619a569789 100644 --- a/packages/command-surface/src/interaction/metadata.ts +++ b/packages/command-surface/src/interaction/metadata.ts @@ -79,7 +79,7 @@ const interactionCommandDescriptions = { 'Move input focus to explicit screen coordinates without entering text. This command changes focus only and does not enter or replace text.', type: 'Append text to the currently focused input. This requires an active input and preserves its existing text.', scroll: - 'Scroll in a direction, or toward the top/bottom edge of scrollable content. The until input scrolls to an off-screen selector in one command. The optional amount is the finger-path fraction of the viewport axis, honored up to 0.8 of it; directional scrolls reduce release momentum, while app scroll physics determine the final content offset. A visible keyboard shortens the swiped band instead of being dismissed; when too little is left, the command refuses with scroll_keyboard_occludes_surface. A directional scroll also reports the movement it observed as movement: moved, at-edge, unchanged, or unobserved when the two reads could not back a claim either way; an unchanged surface inside a container that still hides content in that direction refuses with scroll_no_progress rather than repeating the requested distance. The movement field is absent where a tier verifies per pass (top/bottom, until), where the runtime cannot read a screen, where a settle observation or a replay already owns that observation, or where the operator opted out of it.', + 'Scroll in a direction, or toward the top/bottom edge of scrollable content. The until input scrolls to an off-screen selector in one command. The optional amount is the finger-path fraction of the viewport axis, honored up to 0.8 of it; directional scrolls reduce release momentum, while app scroll physics determine the final content offset. A visible keyboard shortens the swiped band instead of being dismissed; when too little is left, the command refuses with scroll_keyboard_occludes_surface. A directional scroll also reports the movement it observed as movement: moved, at-edge, unchanged, or unobserved when the two reads could not back a claim either way; an unchanged surface inside a container that still hides content in that direction refuses with scroll_no_progress rather than repeating the requested distance. The movement field is absent where a tier verifies per pass (top/bottom, until), where the runtime cannot read a screen, where a settle observation or a replay already owns that observation, or where the operator opted out of it. On watchOS, scroll turns the Digital Crown: up and down only, and the amount is a fraction of the screen height. Use swipe for horizontal pages.', get: 'Read text or accessibility attributes from a snapshot ref or selector without changing the app. The text format returns visible content; attrs returns the element attribute map.', is: 'Check whether a selector satisfies a UI predicate such as visible, hidden, exists, absent, editable, selected, checked, focused, or text. `absent` passes only when one readable, complete, settled, unscoped, full-depth accessibility capture has zero matches. This command checks the current condition without polling.', find: 'Find by text/label/value/role/id and run action; the action defaults to click. The role locator matches snapshot kind vocabulary (button, text, text-field, switch, ...); pre-reconciliation leaf spellings (statictext, edittext, textview) stay accepted on the nodes that carried them during a deprecation window. The focus and type actions aim at a text field: the match or the field holding it, even beside other fields, or else the one enabled on-screen field inside the match. Several enabled on-screen fields inside the match refuse with AMBIGUOUS_MATCH and the field candidates, and a disabled target refuses with reason target_disabled. Web text boxes are not recognized as text fields.', diff --git a/packages/command-surface/src/system/index.ts b/packages/command-surface/src/system/index.ts index 029c9e5df8..26277da6fa 100644 --- a/packages/command-surface/src/system/index.ts +++ b/packages/command-surface/src/system/index.ts @@ -306,7 +306,7 @@ const appStateCommandDescription = const backCommandDescription = "Navigate back in the app or through system navigation. The in-app mode targets the app navigation stack; system targets platform back behavior. iOS has no system back: both modes only pop the navigation stack and never close a modal or sheet, whose own Close or Cancel control does; Android's system back also closes dialogs and modal screens. On iOS, back presses the navigation bar system back button (identifier BackButton) only when exactly one hittable one is found in a readable accessibility tree, and succeeds only when the bar count, the back button count, or a back button title then changes; a back button with no title, such as the iPhone Duo's floating one, is confirmed by its bar's title instead, which must hold still before the tap, and a bar that retitles itself can be misread as a pop. Otherwise it swipes from the left edge (on an iPad whose app window cannot be resolved, only while the app fills the screen) and succeeds only when the app screen changes. Reason back_swipe_no_change: the swipe was sent and the screen did not change; details.dismissControls then lists the top-band Back, Close, Cancel, or xmark buttons (never Done or Save) as { selector, label, identifier? }, and the hint names a lone one. Press one by its selector; back returns no refs, because it expires them. Reason back_swipe_unverified: the button was pressed but the bar state did not change after the tap, or the swipe may or may not have navigated because the screen kept changing before it or could not be sampled after it. Reason back_swipe_not_dispatched, or a screen that cannot be sampled before the swipe, means nothing was sent. An app with a left-edge drawer may open the drawer instead."; const homeCommandDescription = - 'Send the selected device to its home screen. This leaves the app session open but moves the foreground away from the app.'; + 'Send the selected device to its home screen. This leaves the app session open but moves the foreground away from the app. On watchOS, home presses the Digital Crown: from an app it shows the watch face, and from the watch face it opens the app grid.'; const orientationCommandDescription = 'Set device orientation on iOS and Android. auto hands rotation back to the sensor on ADB-backed Android (local and Limrun); other backends refuse it. In both default and scoped simulator sets, an iPhone Duo classified with more than one integrated panel refuses portrait-upside-down and rotates through the fold helper; it succeeds only when the lit panel shows the requested orientation, otherwise it fails with orientation-unverified, or orientation-panel-table-unavailable when the final guest panel table cannot be read. A simulator classified with one panel, or whose first classification read is unresolved, uses the standard runner rotation.'; const foldGuidance = { @@ -323,7 +323,7 @@ const keyboardCommandDescription = const clipboardCommandDescription = 'Read the current device clipboard text, or replace its contents with the given text. Android runs both through the clipboard service shell command, and a build that implements none (Android 16 does not) refuses with UNSUPPORTED_OPERATION rather than reporting an empty clipboard.'; const actionButtonCommandDescription = - 'Press the iPhone or iPad Action Button once. The press is dispatched without activating the session app and nothing is re-observed afterwards, so the app keeps the state the press found. What the system does with the press is not observed by this command: Simulators run no Shortcuts or App Intents, so delivery to an assigned Shortcut is verifiable only on a physical iPhone. A model with no Action Button refuses with UNSUPPORTED_OPERATION, error.details.reason hardware_control_unavailable and dispatched: no.'; + 'Press the iPhone, iPad, or Apple Watch Ultra Action Button once. The press is dispatched without activating the session app and nothing is re-observed afterwards, so the app keeps the state the press found. What the system does with the press is not observed by this command: Simulators run no Shortcuts or App Intents, so delivery to an assigned Shortcut is verifiable only on a physical iPhone. A model with no Action Button refuses with UNSUPPORTED_OPERATION, error.details.reason hardware_control_unavailable and dispatched: no.'; const tvRemoteCommandDescription = 'Press or long-press a TV remote button on Android TV, tvOS, or Vega OS. Android TV also supports volume, power, media, channel, guide, captions, input, color keys, and android-keycode:N. tvOS and Vega OS support up, down, left, right, select, menu, home, and back. Phones and WebDriver sessions are unsupported. The aliases ok, center, and enter map to select.'; @@ -751,10 +751,10 @@ const actionButtonCommandFacet = defineParameterlessCommandFacet({ effect: 'destructive', description: actionButtonCommandDescription, text: { - summary: 'Press the iPhone or iPad Action Button', + summary: 'Press the iPhone, iPad, or Apple Watch Ultra Action Button', searchHint: 'side switch', cliDetail: - 'iPhone and iPad only. The runner asks the device for the button and reports unsupported when that model has none.', + 'iPhone, iPad, and Apple Watch simulators. The runner asks the device for the button and reports unsupported when that model has none.', }, run: (client, input) => client.command.actionButton(input), }); diff --git a/packages/contracts/src/gesture-admission.ts b/packages/contracts/src/gesture-admission.ts index 0f04b6b2c1..7e8447dd2b 100644 --- a/packages/contracts/src/gesture-admission.ts +++ b/packages/contracts/src/gesture-admission.ts @@ -63,7 +63,8 @@ function multiTouchRefusalSubject(device: DeviceInfo): string | undefined { appleOs === 'ipados' || appleOs === 'macos' || appleOs === 'tvos' || - appleOs === 'visionos' + appleOs === 'visionos' || + appleOs === 'watchos' ) { return APPLE_OS_DISPLAY_NAMES[appleOs]; } diff --git a/packages/kernel/src/device.ts b/packages/kernel/src/device.ts index d223799c0b..98e02005ac 100644 --- a/packages/kernel/src/device.ts +++ b/packages/kernel/src/device.ts @@ -17,9 +17,7 @@ export { // still emits; the internal `Platform` no longer carries them — every Apple OS // collapses to the single `apple` platform (ADR-0009 / issue #979). export type ApplePlatform = 'ios' | 'macos'; -// Explicit, stored Apple operating system. All six literals are reserved so the -// type is stable as platform support grows, but discovery only ever populates -// the four currently supported ones ('ios' | 'ipados' | 'tvos' | 'macos'). +// Explicit, stored Apple operating system. Discovery produces watchOS for simulators only. const APPLE_OS_VALUES = ['ios', 'ipados', 'tvos', 'watchos', 'visionos', 'macos'] as const; export type AppleOS = (typeof APPLE_OS_VALUES)[number]; // Internal device platforms. Apple OSes collapse to a single `apple` platform; the @@ -526,7 +524,7 @@ export function platformSelectorsConflict( export function resolveApplePlatformName( platformOrTarget: ApplePlatform | DeviceTarget | undefined, appleOs?: AppleOS, -): 'iOS' | 'tvOS' | 'macOS' | 'visionOS' { +): 'iOS' | 'tvOS' | 'macOS' | 'visionOS' | 'watchOS' { // Prefer the explicit, stored Apple OS when present; legacy records without // it keep resolving through the existing target-based inference below. if (appleOs) return resolveRunnerPlatformNameForAppleOs(appleOs); @@ -537,7 +535,7 @@ export function resolveApplePlatformName( function resolveRunnerPlatformNameForAppleOs( appleOs: AppleOS, -): 'iOS' | 'tvOS' | 'macOS' | 'visionOS' { +): 'iOS' | 'tvOS' | 'macOS' | 'visionOS' | 'watchOS' { switch (appleOs) { case 'tvos': return 'tvOS'; @@ -545,10 +543,9 @@ function resolveRunnerPlatformNameForAppleOs( return 'macOS'; case 'visionos': return 'visionOS'; - // iOS and iPadOS share the single iOS runner profile/SDK. watchOS remains - // reserved in the type but is never produced by discovery; defaulting it to - // iOS keeps any future record on a valid runner profile without introducing - // watchOS support. + case 'watchos': + return 'watchOS'; + // iOS and iPadOS share the single iOS runner profile and SDK. default: return 'iOS'; } @@ -955,6 +952,8 @@ function compareAppleDevicesForSelection( } function appleDeviceSelectionRank(device: DeviceInfo): number { + // A watch answers `--platform ios` only when no other Apple simulator can. + if (device.kind === 'simulator' && device.appleOs === 'watchos') return 4; if (device.kind === 'simulator') return appleTargetSelectionRank(device, 0, 1, 2, 3); if (device.kind === 'device' && isApplePlatform(device.platform) && !isMacOs(device)) return appleTargetSelectionRank(device, 10, 11, 12, 13); diff --git a/packages/platform-apple/src/__tests__/interactor-watchos-sentinel.test.ts b/packages/platform-apple/src/__tests__/interactor-watchos-sentinel.test.ts deleted file mode 100644 index a438f45faf..0000000000 --- a/packages/platform-apple/src/__tests__/interactor-watchos-sentinel.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { test, expect } from 'vitest'; -import { createAppleInteractor } from '../interactor.ts'; -import type { DeviceInfo } from '@agent-device/kernel/device'; -import type { RunnerContext } from '@agent-device/contracts/interactor-types'; -import { AppError } from '@agent-device/kernel/errors'; - -// watchOS is an explicit unsupported sentinel: XCUITest cannot drive watchOS UI, -// so a `appleOs: 'watchos'` device must be rejected at interactor creation (the -// admission seam) rather than silently falling through to the iOS runner. -const watchOsDevice: DeviceInfo = { - platform: 'apple', - id: 'watch-1', - name: 'Apple Watch Series 10', - kind: 'device', - appleOs: 'watchos', -}; - -test('createAppleInteractor rejects a watchOS device as UNSUPPORTED_PLATFORM', () => { - // The guard throws before touching runnerContext, so an empty context is fine. - const create = () => - createAppleInteractor(watchOsDevice, {} as RunnerContext, { - env: process.env, - cwd: process.cwd(), - }); - expect(create).toThrow(AppError); - try { - create(); - expect.unreachable('expected createAppleInteractor to throw for watchOS'); - } catch (error) { - expect(error).toBeInstanceOf(AppError); - expect((error as AppError).code).toBe('UNSUPPORTED_PLATFORM'); - expect((error as AppError).message).toMatch(/watchOS/i); - } -}); - -test('a non-watchOS appleOs does not trigger the watchOS sentinel', () => { - // A tvOS device must pass the watchOS admission guard. Interactor creation - // succeeds on an empty runner context, and pinning that success keeps this - // oracle unconditional — the previous shape only asserted inside a catch - // block that never fired, so no assertion executed on the observed path. - const tvOsDevice: DeviceInfo = { - platform: 'apple', - id: 'tv-1', - name: 'Apple TV 4K', - kind: 'simulator', - target: 'tv', - appleOs: 'tvos', - booted: true, - }; - expect( - createAppleInteractor(tvOsDevice, {} as RunnerContext, { - env: process.env, - cwd: process.cwd(), - }), - ).toBeTruthy(); -}); diff --git a/packages/platform-apple/src/deployment/runtime.test.ts b/packages/platform-apple/src/deployment/runtime.test.ts index 540e4934b8..269ea258ca 100644 --- a/packages/platform-apple/src/deployment/runtime.test.ts +++ b/packages/platform-apple/src/deployment/runtime.test.ts @@ -195,20 +195,6 @@ test.each([ false, 'unsupported-platform-leaf', ], - [ - 'watchOS sentinel', - appleDevice({ appleOs: 'watchos' }), - false, - false, - 'unsupported-platform-leaf', - ], - [ - 'watchOS physical sentinel', - appleDevice({ appleOs: 'watchos', kind: 'device', iosPhysicalDeviceBackend: 'coredevice' }), - false, - false, - 'unsupported-platform-leaf', - ], [ 'invalid Apple emulator kind', appleDevice({ kind: 'emulator' }), diff --git a/packages/platform-apple/src/deployment/runtime.ts b/packages/platform-apple/src/deployment/runtime.ts index d58e2d19e5..7d2e173b77 100644 --- a/packages/platform-apple/src/deployment/runtime.ts +++ b/packages/platform-apple/src/deployment/runtime.ts @@ -308,5 +308,5 @@ function applePushFact(device: DeviceInfo): RuntimeOperationFact { } function isSupportedAppleDeploymentLeaf(device: DeviceInfo): boolean { - return isIosFamily(device) && device.appleOs !== 'watchos'; + return isIosFamily(device); } diff --git a/packages/platform-apple/src/gesture-facts.test.ts b/packages/platform-apple/src/gesture-facts.test.ts index e1eacdfb06..b14e108a29 100644 --- a/packages/platform-apple/src/gesture-facts.test.ts +++ b/packages/platform-apple/src/gesture-facts.test.ts @@ -48,7 +48,7 @@ test.each([ ['tvOS simulator', leaves.tvos, true, true, false, false, true, true], ['macOS host', leaves.macos, true, true, false, false, true, true], ['visionOS simulator', leaves.visionos, false, false, false, false, true, true], - ['watchOS sentinel', leaves.watchos, false, false, false, false, false, true], + ['watchOS simulator', leaves.watchos, true, true, false, false, true, true], ])( 'declares the %s gesture and scroll cells', async (_name, device, plan, directionalFling, multiTouch, drag, viewport, scroll) => { @@ -75,12 +75,10 @@ test('carries the retired multi-touch hints on every Apple leaf that refused', a available: false, hint: expect.stringContaining('source hold, timed movement, and destination hold'), }); - // watchOS was caught by the retired admission's FIRST branch, before the policy that carries - // the per-OS hints ever ran, so it refuses without one. const watchos = await runtime.inspectFacts(leaves.watchos); - expect(watchos.operations.performGesturePlan).toEqual({ + expect(watchos.operations.performMultiTouchGesturePlan).toMatchObject({ available: false, - reason: 'unsupported-platform-leaf', + hint: expect.stringContaining('watchOS apps have no multi-touch gestures'), }); }); diff --git a/packages/platform-apple/src/gesture-facts.ts b/packages/platform-apple/src/gesture-facts.ts index 09f1e6a68d..8f71771c2c 100644 --- a/packages/platform-apple/src/gesture-facts.ts +++ b/packages/platform-apple/src/gesture-facts.ts @@ -46,18 +46,15 @@ export function appleGestureAndScrollFacts(device: DeviceInfo) { /** The reason this leaf refuses gestures it does not name, before any tier is consulted. */ function appleGestureFamilyUnavailable(device: DeviceInfo): RuntimeOperationUnavailability { - return device.appleOs === 'watchos' || device.appleOs === 'visionos' - ? gestureLeafUnavailable - : gestureKindUnavailable; + return device.appleOs === 'visionos' ? gestureLeafUnavailable : gestureKindUnavailable; } function appleGesturePlanFact(device: DeviceInfo): RuntimeOperationFact { - if (device.appleOs === 'watchos' || device.appleOs === 'visionos') return gestureLeafUnavailable; + if (device.appleOs === 'visionos') return gestureLeafUnavailable; return appleTouchKind(device) ? available : gestureKindUnavailable; } function appleMultiTouchGestureFact(device: DeviceInfo): RuntimeOperationFact { - if (device.appleOs === 'watchos') return gestureLeafUnavailable; if (!appleTouchKind(device)) return gestureKindUnavailable; const appleOs = resolveDeviceAppleOs(device); if (appleOs !== 'ios' && appleOs !== 'ipados') { @@ -81,7 +78,6 @@ function appleTargetAuthoredDragFact(device: DeviceInfo): RuntimeOperationFact { } function appleGestureViewportFact(device: DeviceInfo): RuntimeOperationFact { - if (device.appleOs === 'watchos') return gestureLeafUnavailable; return appleTouchKind(device) ? available : gestureKindUnavailable; } diff --git a/packages/platform-apple/src/interactor.ts b/packages/platform-apple/src/interactor.ts index 700811e728..3893fe2371 100644 --- a/packages/platform-apple/src/interactor.ts +++ b/packages/platform-apple/src/interactor.ts @@ -60,16 +60,6 @@ export function createAppleInteractor( host: HostEnvironment, runnerProvider?: AppleRunnerProvider | AppleRunnerCommandExecutor, ): Interactor { - // watchOS unsupported sentinel: XCUITest cannot drive watchOS UI (no - // XCUIApplication), so a watchOS device has no runner backend. Reject it - // explicitly here rather than letting `appleOs: 'watchos'` silently fall - // through to the iOS runner profile (see resolveRunnerPlatformNameForAppleOs). - if (device.appleOs === 'watchos') { - throw new AppError( - 'UNSUPPORTED_PLATFORM', - 'watchOS is not supported: XCUITest cannot drive watchOS UI, so this device has no runner backend.', - ); - } const env = host.env; const { overrides, runnerOpts } = iosRunnerOverrides(device, runnerContext, env); const appBackend = isMacOs(device) ? hostMacOsAppBackend(env) : 'xctest'; diff --git a/packages/platform-apple/src/inventory-classification.ts b/packages/platform-apple/src/inventory-classification.ts index 2d1ba61018..7c572a86d6 100644 --- a/packages/platform-apple/src/inventory-classification.ts +++ b/packages/platform-apple/src/inventory-classification.ts @@ -4,6 +4,7 @@ import { isCoreDeviceReachable } from './core/physical-device-constants.ts'; const APPLE_PRODUCT_TYPE_PATTERN = /^(iphone|ipad|ipod|appletv|realitydevice)/i; const APPLE_IPAD_PATTERN = /ipad/i; const APPLE_VISION_PATTERN = /\b(apple vision|vision pro|xros|visionos|realitydevice)\b/i; +const APPLE_WATCH_PATTERN = /\b(apple watch|apple-watch|watchos)\b/i; const APPLE_MOBILE_LABEL_PATTERN = /\b(iphone|ipad|ipod)\b/i; const APPLE_TV_PRODUCT_TYPE_PATTERN = /^appletv/i; const APPLE_TV_LABEL_HINTS = ['apple tv', 'appletv', 'tvos'] as const; @@ -48,7 +49,8 @@ export function isSupportedAppleRuntime(runtime: string): boolean { normalized.includes('ios') || normalized.includes('tvos') || normalized.includes('xros') || - normalized.includes('visionos') + normalized.includes('visionos') || + normalized.includes('watchos') ); } @@ -70,6 +72,7 @@ export function resolveAppleTargetFromLabel(value: string): DeviceTarget | null export function resolveAppleOs(target: DeviceTarget, descriptors: string[]): AppleOS { if (target === 'tv') return 'tvos'; if (descriptors.some((descriptor) => APPLE_VISION_PATTERN.test(descriptor))) return 'visionos'; + if (descriptors.some((descriptor) => APPLE_WATCH_PATTERN.test(descriptor))) return 'watchos'; if (descriptors.some((descriptor) => APPLE_IPAD_PATTERN.test(descriptor))) return 'ipados'; return 'ios'; } diff --git a/packages/platform-apple/src/logs/runtime.test.ts b/packages/platform-apple/src/logs/runtime.test.ts index 382cc452b2..a93f6b1aaf 100644 --- a/packages/platform-apple/src/logs/runtime.test.ts +++ b/packages/platform-apple/src/logs/runtime.test.ts @@ -47,12 +47,6 @@ describe('Apple app-log runtime', () => { available: true, hint: undefined, }, - { - name: 'watchOS sentinel', - device: appleDevice({ appleOs: 'watchos' }), - available: false, - hint: 'watchOS app logs are not supported', - }, ])('classifies the $name leaf explicitly', async ({ device, available, hint }) => { const binding = await createAppleAppLogRuntime(hostFixture().host).bind({ device, @@ -84,26 +78,6 @@ describe('Apple app-log runtime', () => { ); }); - test('fails closed for the reserved watchOS leaf', async () => { - const binding = await createAppleAppLogRuntime(hostFixture().host).bind({ - device: appleDevice({ appleOs: 'watchos' }), - intent: { kind: 'ordinary' }, - scope, - }); - expect(binding.facts.operations.appLogInspect).toMatchObject({ - available: false, - reason: 'unsupported-platform-leaf', - }); - await expect( - binding.operations.appLogStart?.({ - sessionId: 'session', - appBundleId: 'com.example.app', - outputPath: '/tmp/app.log', - fence: { token: 'fence', generation: 1 }, - }), - ).rejects.toMatchObject({ code: 'UNSUPPORTED_PLATFORM' }); - }); - test('rolls back the output sink if simulator process startup fails', async () => { const fixture = hostFixture({ failProcessStart: true }); const binding = await createAppleAppLogRuntime(fixture.host).bind({ diff --git a/packages/platform-apple/src/logs/runtime.ts b/packages/platform-apple/src/logs/runtime.ts index 8a62535aa2..b1ec8bfd3d 100644 --- a/packages/platform-apple/src/logs/runtime.ts +++ b/packages/platform-apple/src/logs/runtime.ts @@ -95,7 +95,6 @@ function bindAppleAppLogs( } function appleAppLogFacts(device: DeviceInfo): RuntimeFacts { - if (device.appleOs === 'watchos') return unavailableAppleFacts(device); const admitted = isIosFamily(device) && device.kind === 'device' && device.iosPhysicalDeviceBackend === 'xctest' ? ({ @@ -124,27 +123,3 @@ function appleAppLogFacts(device: DeviceInfo): RuntimeFacts { - const unavailable = Object.freeze({ - available: false, - reason: 'unsupported-platform-leaf', - hint: 'watchOS app logs are not supported.', - } as const); - return Object.freeze({ - device: { - family: 'apple', - appleOs: 'watchos', - kind: device.kind, - ...(device.target === undefined ? {} : { target: device.target }), - providerMode: 'local', - }, - operations: { - appLogInspect: unavailable, - appLogDoctor: unavailable, - appLogStart: unavailable, - appLogReattach: unavailable, - appLogCleanup: unavailable, - }, - }); -} diff --git a/packages/platform-apple/src/logs/start.ts b/packages/platform-apple/src/logs/start.ts index 7fc1fda44c..f30a5dd240 100644 --- a/packages/platform-apple/src/logs/start.ts +++ b/packages/platform-apple/src/logs/start.ts @@ -103,9 +103,6 @@ export async function startAppleAppLogs( } function assertAppleLogStartSupported(device: DeviceInfo): void { - if (device.appleOs === 'watchos') { - throw new AppError('UNSUPPORTED_PLATFORM', 'watchOS app logs are not supported'); - } if ( isIosFamily(device) && device.kind === 'device' && diff --git a/packages/platform-apple/src/multitouch-support.ts b/packages/platform-apple/src/multitouch-support.ts index 3dc47cb8f2..66cc08ed37 100644 --- a/packages/platform-apple/src/multitouch-support.ts +++ b/packages/platform-apple/src/multitouch-support.ts @@ -7,12 +7,14 @@ import { import { APPLE_OS_DISPLAY_NAMES } from '@agent-device/contracts/gesture-admission'; import { AppError } from '@agent-device/kernel/errors'; import type { GesturePlan } from '@agent-device/contracts/gesture-plan-types'; +import { WATCH_OS_MULTI_TOUCH_UNSUPPORTED_HINT } from './os/watchos/facts.ts'; export const APPLE_MULTI_TOUCH_UNSUPPORTED_HINTS: Partial> = { visionos: 'visionOS uses spatial input and does not support two-finger touch synthesis.', tvos: 'tvOS has no touch input — this gesture is supported on Android, iOS, and iPadOS.', macos: 'macOS automation has no multi-touch input — this gesture is supported on Android, iOS, and iPadOS.', + watchos: WATCH_OS_MULTI_TOUCH_UNSUPPORTED_HINT, }; /** One policy shared by command admission and the defensive Apple adapter check. */ diff --git a/packages/platform-apple/src/navigation/runtime.test.ts b/packages/platform-apple/src/navigation/runtime.test.ts index 14690772c6..ea1366ccd0 100644 --- a/packages/platform-apple/src/navigation/runtime.test.ts +++ b/packages/platform-apple/src/navigation/runtime.test.ts @@ -36,7 +36,7 @@ test.each([ ['ios', true], ['tvos', true], ['macos', true], - ['watchos', false], + ['watchos', true], ['visionos', false], ] as const)('back on %s is available: %s', (appleOs, availableExpected) => { const fact = appleNavigationFacts({ diff --git a/packages/platform-apple/src/navigation/runtime.ts b/packages/platform-apple/src/navigation/runtime.ts index ba567ef434..8bd0708c27 100644 --- a/packages/platform-apple/src/navigation/runtime.ts +++ b/packages/platform-apple/src/navigation/runtime.ts @@ -21,26 +21,17 @@ const backKindUnavailable = Object.freeze({ reason: 'unsupported-device-kind', hint: 'back is supported on Apple simulators and physical devices.', } as const); -/** watchOS has no XCUITest-driveable UI (ADR-0009): no Apple interactor can be constructed for - * it, so every interactor-backed operation below stays unavailable there regardless of what the - * retired per-command capability table said for it — facts are the support authority (ADR 0019), - * not a mirror of a table that never modeled interactor constructibility. */ -const backOsUnavailable = Object.freeze({ - available: false, - reason: 'unsupported-platform-leaf', -} as const); /** visionOS has no back gesture or button; the runner refuses the same way if reached directly. */ const backVisionOsUnavailable = Object.freeze({ available: false, reason: 'unsupported-platform-leaf', hint: 'visionOS has no back command. Press the visible back control by its ref.', } as const); -/** tvOS presses the remote's Menu button, macOS taps the window back control, and iOS presses the - * navigation bar back button or swipes from the left edge. watchOS and visionOS have no back. */ +/** tvOS presses the remote's Menu button, macOS taps the window back control, and iOS and watchOS + * press the navigation bar back button or swipe from the left edge. visionOS has no back. */ function appleBackFact(device: DeviceInfo): RuntimeOperationFact { if (device.kind !== 'simulator' && device.kind !== 'device') return backKindUnavailable; const os = resolveDeviceAppleOs(device); - if (os === 'watchos') return backOsUnavailable; return os === 'visionos' ? backVisionOsUnavailable : available; } @@ -50,8 +41,7 @@ const homeKindUnavailable = Object.freeze({ hint: 'home is supported on Apple simulators and physical devices.', } as const); /** Parity with the retired `supportsAppAndDeviceLifecycle` closure: unavailable on macOS, which - * drives an already-running app with no springboard home; also unavailable on watchOS, whose - * interactor cannot be constructed at all (see {@link backOsUnavailable}). */ + * drives an already-running app with no springboard home. */ const homeLifecycleUnavailable = Object.freeze({ available: false, reason: 'unsupported-platform-leaf', @@ -73,20 +63,19 @@ function appleSpringboardFact( ): RuntimeOperationFact { if (device.kind !== 'simulator' && device.kind !== 'device') return kindUnavailable; const os = resolveDeviceAppleOs(device); - return os === 'macos' || os === 'watchos' ? homeLifecycleUnavailable : available; + return os === 'macos' ? homeLifecycleUnavailable : available; } /** * The per-AppleOS mobile-input eligibility `orientation` and `keyboard` (dismiss/enter) share: * unavailable on tvOS (focus-only XCUIRemote navigation, no orientation or keyboard), macOS (an - * AppKit desktop host, no device orientation or software keyboard), and watchOS (no constructible - * interactor at all, see {@link backOsUnavailable}). Parity with the retired + * AppKit desktop host, no device orientation or software keyboard). Parity with the retired * `supportsOrientation`/`supportsKeyboard` closures, which read the same per-OS table. */ function appleMobileInputEligible(device: DeviceInfo): boolean { if (device.kind !== 'simulator' && device.kind !== 'device') return false; const os = resolveDeviceAppleOs(device); - return os !== 'tvos' && os !== 'macos' && os !== 'watchos'; + return os !== 'tvos' && os !== 'macos'; } const orientationKindUnavailable = Object.freeze({ @@ -152,23 +141,26 @@ const systemButtonUnavailable = Object.freeze({ const actionButtonKindUnavailable = Object.freeze({ available: false, reason: 'unsupported-device-kind', - hint: 'action-button is supported on iPhone and iPad simulators and physical devices.', + hint: 'action-button is supported on iPhone and iPad simulators and physical devices, and on Apple Watch simulators.', } as const); const actionButtonOsUnavailable = Object.freeze({ available: false, reason: 'unsupported-platform-leaf', - hint: 'The Action Button is iPhone and iPad hardware; tvOS, macOS, watchOS and visionOS have no such control.', + hint: 'The Action Button is iPhone, iPad, and Apple Watch Ultra hardware; tvOS, macOS and visionOS have no such control.', } as const); /** * The leaf reading is {@link isHandheldAppleDevice}, the same rule a provider owner reads; what * this owner adds is its kind gate. `DeviceInfo` records no model identifier, so which iPhone or * iPad carries the button is a hardware question the runner answers with - * `hasHardwareButton(.action)`. iPhone and iPad is deliberately not - * {@link appleMobileInputEligible}, which is `orientation`'s reading and admits visionOS. + * `hasHardwareButton(.action)`, on a watch as on a phone (Apple Watch Ultra has the button). iPhone + * and iPad is deliberately not {@link appleMobileInputEligible}, which is `orientation`'s reading and + * admits visionOS. */ function appleActionButtonFact(device: DeviceInfo): RuntimeOperationFact { if (device.kind !== 'simulator' && device.kind !== 'device') return actionButtonKindUnavailable; - return isHandheldAppleDevice(device) ? available : actionButtonOsUnavailable; + return isHandheldAppleDevice(device) || device.appleOs === 'watchos' + ? available + : actionButtonOsUnavailable; } const volumeButtonOsUnavailable = Object.freeze({ diff --git a/packages/platform-apple/src/os/watchos/facts.test.ts b/packages/platform-apple/src/os/watchos/facts.test.ts new file mode 100644 index 0000000000..beb6f91e73 --- /dev/null +++ b/packages/platform-apple/src/os/watchos/facts.test.ts @@ -0,0 +1,91 @@ +import { bindTestCommandHost } from '@agent-device/test-kit'; +import { expect, test } from 'vitest'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { createApplePlatformRuntime } from '../../runtime.ts'; +import { platformRuntimeHostFixture } from '../../runtime.fixtures.ts'; +import { WATCH_OS_MULTI_TOUCH_UNSUPPORTED_HINT } from './facts.ts'; + +bindTestCommandHost(); + +function watch(kind: DeviceInfo['kind'] = 'simulator'): DeviceInfo { + return { + platform: 'apple', + appleOs: 'watchos', + id: 'watch', + name: 'Apple Watch', + kind, + target: 'mobile', + booted: true, + }; +} + +async function availableOperations(device: DeviceInfo): Promise { + const facts = await createApplePlatformRuntime(platformRuntimeHostFixture()).inspectFacts(device); + return Object.entries(facts.operations) + .filter(([, fact]) => fact.available) + .map(([operation]) => operation) + .sort(); +} + +test('a watchOS simulator admits only the operations with a watch meaning', async () => { + expect(await availableOperations(watch())).toEqual( + [ + 'actionButton', + 'appState', + 'back', + 'bootTarget', + 'captureScreenshot', + 'captureSnapshot', + 'closeApplication', + 'deployApp', + 'deployMaterializedApp', + 'ensureReady', + 'fillPoint', + 'finalizeApplicationClose', + 'findText', + 'focusPoint', + 'gestureViewport', + 'home', + 'longPressPoint', + 'materializeAppSource', + 'openApplication', + 'performDirectionalFlingPlan', + 'performGesturePlan', + 'prepareAppleRunner', + 'prepareApplicationOpen', + 'querySelector', + 'readTextAtPoint', + 'resolveOpenTarget', + 'scrollDirection', + 'shutdownTarget', + 'tapElementSelector', + 'tapPoint', + 'typeText', + 'uninstallApp', + ].sort(), + ); +}); + +test('a watchOS simulator names why it refuses multi-touch, the App Switcher, and recording', async () => { + const facts = await createApplePlatformRuntime(platformRuntimeHostFixture()).inspectFacts( + watch(), + ); + expect(facts.operations.performMultiTouchGesturePlan).toEqual({ + available: false, + reason: 'unsupported-platform-leaf', + hint: WATCH_OS_MULTI_TOUCH_UNSUPPORTED_HINT, + }); + expect(facts.operations.appSwitcher).toMatchObject({ + available: false, + hint: expect.stringContaining('Digital Crown double-click'), + }); + expect(facts.operations.screenRecordingStart).toMatchObject({ + available: false, + reason: 'unsupported-platform-leaf', + hint: expect.stringContaining('watchOS simulators support only watch interactions'), + }); +}); + +test('a physical Apple Watch is refused on every operation', async () => { + expect(await availableOperations(watch('device'))).toEqual([]); +}); diff --git a/packages/platform-apple/src/os/watchos/facts.ts b/packages/platform-apple/src/os/watchos/facts.ts new file mode 100644 index 0000000000..1fe80c6fb0 --- /dev/null +++ b/packages/platform-apple/src/os/watchos/facts.ts @@ -0,0 +1,94 @@ +import type { RuntimeOperationFact } from '@agent-device/contracts/platform-runtime'; +import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform-runtime-operations'; +import type { DeviceInfo } from '@agent-device/kernel/device'; + +/** + * The operations a watchOS simulator admits. The watch keeps only what has a watch meaning: app + * lifecycle, the runner tree, one-finger touch (tap, touch and hold, swipe, pan), the Digital Crown + * (`scrollDirection` rotates it, `home` presses it), the Action Button, back, typing through the + * system input sheet, and screenshots. Every other operation is refused here, so an operation added + * later stays closed on the watch until it has watch evidence (#4738). + */ +const WATCH_OS_OPERATIONS = new Set([ + 'deployApp', + 'materializeAppSource', + 'deployMaterializedApp', + 'uninstallApp', + 'ensureReady', + 'bootTarget', + 'shutdownTarget', + 'resolveOpenTarget', + 'prepareApplicationOpen', + 'openApplication', + 'closeApplication', + 'finalizeApplicationClose', + 'prepareAppleRunner', + 'appState', + 'captureSnapshot', + 'findText', + 'querySelector', + 'readTextAtPoint', + 'focusPoint', + 'tapPoint', + 'tapElementSelector', + 'longPressPoint', + 'fillPoint', + 'typeText', + 'performGesturePlan', + 'performDirectionalFlingPlan', + 'gestureViewport', + 'scrollDirection', + 'back', + 'home', + 'actionButton', + 'captureScreenshot', +]); + +/** Why a watch refuses multi-touch, shared by the fact and the Apple adapter's own check. */ +export const WATCH_OS_MULTI_TOUCH_UNSUPPORTED_HINT = + 'watchOS apps have no multi-touch gestures: the SDK has no pinch or rotate gesture, and two-finger pan belongs to the Zoom accessibility feature. Use swipe, gesture pan, or scroll (the Digital Crown).'; + +const WATCH_OS_REFUSALS: Partial> = { + appSwitcher: + 'The watchOS App Switcher opens on a Digital Crown double-click, which XCUITest cannot press.', + setOrientation: 'watchOS has no device orientation.', +}; + +const WATCH_OS_PHYSICAL_UNAVAILABLE = Object.freeze({ + available: false, + reason: 'unsupported-device-kind', + hint: 'watchOS is supported on simulators only. A physical Apple Watch reaches the Mac only through its paired iPhone.', +} as const); + +function watchOsRefusal(operation: string): RuntimeOperationFact { + return Object.freeze({ + available: false, + reason: 'unsupported-platform-leaf', + hint: + WATCH_OS_REFUSALS[operation as keyof PlatformRuntimeOperations] ?? + 'watchOS simulators support only watch interactions: app lifecycle, snapshot, press, swipe, scroll (the Digital Crown), back, home, typing, and screenshots.', + } as const); +} + +/** + * Applies the watchOS admission set to an Apple leaf's computed facts. An admitted operation, and a + * refused one its own module already refuses, keep the module's fact and hint. A physical watch is + * refused everywhere. + */ +export function applyWatchOsOperationFacts>( + device: DeviceInfo, + operations: T, +): T { + if (device.appleOs !== 'watchos') return operations; + return Object.fromEntries( + Object.entries(operations).map(([operation, fact]) => { + if (device.kind !== 'simulator') return [operation, WATCH_OS_PHYSICAL_UNAVAILABLE]; + return [ + operation, + WATCH_OS_OPERATIONS.has(operation as keyof PlatformRuntimeOperations) || !fact.available + ? fact + : watchOsRefusal(operation), + ]; + }), + ) as T; +} diff --git a/packages/platform-apple/src/recording/runtime.ts b/packages/platform-apple/src/recording/runtime.ts index 01601fe0ba..0e5a7147b1 100644 --- a/packages/platform-apple/src/recording/runtime.ts +++ b/packages/platform-apple/src/recording/runtime.ts @@ -39,8 +39,6 @@ const SIMULATOR_TARGET_LABEL = 'iOS recording'; const SIMULATOR_BACKEND_LABEL = 'simctl recordVideo'; export function appleScreenRecordingFacts(device: DeviceInfo) { - if (device.appleOs === 'watchos') - return unavailableFact('unsupported-platform-leaf', 'watchOS recording is not supported.'); if ( isIosFamily(device) && device.kind === 'device' && diff --git a/packages/platform-apple/src/runner-interaction-facts.ts b/packages/platform-apple/src/runner-interaction-facts.ts index dc85ed5321..05e8e824c0 100644 --- a/packages/platform-apple/src/runner-interaction-facts.ts +++ b/packages/platform-apple/src/runner-interaction-facts.ts @@ -2,7 +2,7 @@ import { unavailableFact, type RuntimeOperationFact, } from '@agent-device/contracts/platform-runtime'; -import { isIosFamily, resolveDeviceAppleOs, type DeviceInfo } from '@agent-device/kernel/device'; +import { isIosFamily, type DeviceInfo } from '@agent-device/kernel/device'; import { snapshotRuntimeOperationFacts } from '@agent-device/contracts/snapshot-runtime'; import { selectorObservationRuntimeOperationFacts } from '@agent-device/contracts/selector-observation-runtime'; import { focusRuntimeOperationFacts } from '@agent-device/contracts/focus-runtime'; @@ -33,11 +33,6 @@ const appStateUnavailable = unavailableFact( "Apple appstate is unavailable here: the runner reads the session app's XCUIApplication state on iOS-family simulators and physical devices only, and the Apple target answers no sessionless foreground probe. The per-command answer is the targetActivation disclosure, which a capture carries when its command had to re-activate the session app (#2682).", ); -const elementTextLeafUnavailable = unavailableFact( - 'unsupported-platform-leaf', - 'watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.', -); - const elementTextKindUnavailable = unavailableFact('unsupported-device-kind'); const snapshotKindUnavailable = unsupportedAppleDeviceKind( @@ -61,7 +56,7 @@ const snapshotActiveAppRequired = unavailableFact( * app took the screen stays nobody's to tell. */ function appleAppStateFact(device: DeviceInfo): RuntimeOperationFact { - if (!isIosFamily(device) || device.appleOs === 'watchos') return appStateUnavailable; + if (!isIosFamily(device)) return appStateUnavailable; return device.kind === 'simulator' || device.kind === 'device' ? available : appStateUnavailable; } @@ -71,18 +66,16 @@ function appleFocusFact(device: DeviceInfo): RuntimeOperationFact { /** * The live point read is the XCUITest runner's `readText` for app sessions and the macOS helper - * for desktop/menubar surfaces. Both need a driveable Apple UI, so watchOS and the non - * simulator/device kinds have no read at all. + * for desktop/menubar surfaces. Both need a driveable Apple UI, so the non simulator/device kinds + * have no read at all. */ function appleElementTextFact(device: DeviceInfo) { - if (resolveDeviceAppleOs(device) === 'watchos') return elementTextLeafUnavailable; return device.kind === 'simulator' || device.kind === 'device' ? available : elementTextKindUnavailable; } function appleSnapshotFact(device: DeviceInfo) { - if (resolveDeviceAppleOs(device) === 'watchos') return snapshotKindUnavailable; return device.kind === 'simulator' || device.kind === 'device' ? available : snapshotKindUnavailable; @@ -125,17 +118,11 @@ export function appleRunnerInteractionFacts(device: DeviceInfo) { }; } -const watchPrepareUnavailable = unavailableFact( - 'unsupported-platform-leaf', - 'watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.', -); - const applePrepareKindUnavailable = unsupportedAppleDeviceKind( 'prepare is supported only for Apple simulators and devices.', ); export function applePrepareAppleRunnerFact(device: DeviceInfo) { - if (resolveDeviceAppleOs(device) === 'watchos') return watchPrepareUnavailable; return device.kind === 'simulator' || device.kind === 'device' ? available : applePrepareKindUnavailable; diff --git a/packages/platform-apple/src/runtime.test.ts b/packages/platform-apple/src/runtime.test.ts index e180f745cd..24909ce1e7 100644 --- a/packages/platform-apple/src/runtime.test.ts +++ b/packages/platform-apple/src/runtime.test.ts @@ -50,6 +50,10 @@ const leaves = { watchos: appleDevice({ appleOs: 'watchos' }), } satisfies Record; +// watchOS admits its own operation set (`os/watchos/facts.ts`), tested in that leaf. The cross-leaf +// tables below cover the other Apple OSes. +const { watchos: _watchos, ...leavesWithoutWatch } = leaves; + // #1542 wiring on the owner side: the CONDITIONAL live selector read must be advertised AND // bound on every leaf the kind cell covers, and absent on the macOS desktop. Dropping // `...selectorQueryOperations` from the binding (while the fact stays available) breaks the @@ -98,14 +102,14 @@ test('tvOS audio capture availability follows the exact host-owned runtime fact' }); /** - * The runner reads the session app's state wherever it runs: every iOS-family leaf but the watchOS - * sentinel. macOS and watchOS keep the refusal that names the missing foreground probe. + * The runner reads the session app's state wherever it runs: every iOS-family leaf. macOS keeps the + * refusal that names the missing foreground probe. */ function expectAppStateFact( device: DeviceInfo, binding: Awaited['bind']>>, ): void { - if (device.appleOs === 'macos' || device.appleOs === 'watchos') { + if (device.appleOs === 'macos') { expect(binding.facts.operations.appState).toEqual({ available: false, reason: 'unsupported-platform-leaf', @@ -136,7 +140,6 @@ test.each([ ['tvOS simulator', leaves.tvos, true, undefined], ['macOS host', leaves.macos, true, undefined], ['visionOS simulator', leaves.visionos, true, undefined], - ['watchOS sentinel', leaves.watchos, false, 'watchOS app logs are not supported'], ])('classifies the %s leaf explicitly', async (_name, device, available, hint) => { const binding = await createApplePlatformRuntime(platformRuntimeHostFixture()).bind({ device, @@ -151,9 +154,7 @@ test.each([ expect(facts.device.providerMode).toBe('local'); expectAppStateFact(device, binding); expect(facts.operations.networkDump).toEqual({ available: true }); - expect(facts.operations.listApps.available).toBe( - device.appleOs !== 'watchos' && device.iosPhysicalDeviceBackend !== 'xctest', - ); + expect(facts.operations.listApps.available).toBe(device.iosPhysicalDeviceBackend !== 'xctest'); // R40/R41: touch and text ride the Apple interactor, which exists for the simulator and // physical device kinds — every leaf in this table is one of those two, so both cells are // available across it (parity with the retired buckets). @@ -179,15 +180,8 @@ test.each([ hint: expect.stringContaining('CoreDevice-backed physical iOS device'), }); } - if (device.appleOs === 'watchos') { - expect(facts.operations.screenRecordingStart).toMatchObject({ - hint: 'watchOS recording is not supported.', - }); - } - expect(facts.operations.ensureReady.available).toBe(device.appleOs !== 'watchos'); - expect(facts.operations.bootTarget.available).toBe( - device.appleOs !== 'macos' && device.appleOs !== 'watchos', - ); + expect(facts.operations.ensureReady.available).toBe(true); + expect(facts.operations.bootTarget.available).toBe(device.appleOs !== 'macos'); expect(facts.operations.bootTargetHeadless.available).toBe(false); expect(facts.operations.setViewport).toEqual({ available: false, @@ -195,7 +189,7 @@ test.each([ hint: 'viewport resizes web targets only (--platform web). Apple screen geometry is fixed by the selected simulator or device type — open a different simulator to test another screen size.', }); expect(binding.operations.setViewport).toBeUndefined(); - expectAppleCaptureAvailability(binding, device); + expectAppleCaptureAvailability(binding); expectAppleSnapshotAvailability(binding, device); }); @@ -217,39 +211,28 @@ function expectApplePerfAvailability( } } -/** - * watchOS is admitted by no capture cell: the Apple interactor cannot even be constructed for it, - * so the refusal is a fact rather than a throw from inside the leaf. - */ -function expectAppleCaptureAvailability( - binding: DeviceBinding, - device: DeviceInfo, -): void { - const available = device.appleOs !== 'watchos'; - expect(binding.facts.operations.captureScreenshot.available).toBe(available); - expect(binding.operations.captureScreenshot).toBeTypeOf(available ? 'function' : 'undefined'); +function expectAppleCaptureAvailability(binding: DeviceBinding): void { + expect(binding.facts.operations.captureScreenshot.available).toBe(true); + expect(binding.operations.captureScreenshot).toBeTypeOf('function'); } function expectAppleSnapshotAvailability( binding: DeviceBinding, device: DeviceInfo, ): void { - const available = device.appleOs !== 'watchos'; - expect(binding.facts.operations.captureSnapshot.available).toBe(available); + expect(binding.facts.operations.captureSnapshot.available).toBe(true); expect(binding.facts.operations.captureSnapshotWithCustomActions.available).toBe( - device.appleOs !== 'macos' && device.appleOs !== 'watchos' && device.kind === 'simulator', + device.appleOs !== 'macos' && device.kind === 'simulator', ); expect(binding.facts.operations.captureSnapshotWithoutActiveApp.available).toBe( device.appleOs === 'macos', ); - expect(binding.operations.captureSnapshot).toBeTypeOf(available ? 'function' : 'undefined'); - // The live point read needs a driveable Apple UI, so it follows the same watchOS sentinel the - // capture does; every other supported leaf advertises and binds it. - expect(binding.facts.operations.readTextAtPoint.available).toBe(available); - expect(binding.operations.readTextAtPoint).toBeTypeOf(available ? 'function' : 'undefined'); + expect(binding.operations.captureSnapshot).toBeTypeOf('function'); + expect(binding.facts.operations.readTextAtPoint.available).toBe(true); + expect(binding.operations.readTextAtPoint).toBeTypeOf('function'); } -test.each(Object.entries(leaves))( +test.each(Object.entries(leavesWithoutWatch))( 'classifies back/home/app-switcher/orientation/tv-remote/keyboard facts for the %s leaf', async (_name, device) => { const binding = await createApplePlatformRuntime(platformRuntimeHostFixture()).bind({ @@ -334,7 +317,7 @@ test('hover has no Apple interactor route on macOS, iOS, or tvOS; the touch fami } }); -test.each(Object.entries(leaves))( +test.each(Object.entries(leavesWithoutWatch))( 'classifies the action-button fact for the %s leaf', async (_name, device) => { const binding = await createApplePlatformRuntime(platformRuntimeHostFixture()).bind({ @@ -357,7 +340,7 @@ test.each(Object.entries(leaves))( // Power and the mute/sleep/wake/media keys are the family denial on every leaf: XCUITest exposes // no press route for any of them. test.each([ - ...Object.entries(leaves).map(([name, device]) => [name, device, false] as const), + ...Object.entries(leavesWithoutWatch).map(([name, device]) => [name, device, false] as const), ['ios physical device', appleDevice({ kind: 'device' }), true] as const, ['ipados physical device', appleDevice({ kind: 'device', appleOs: 'ipados' }), true] as const, [ @@ -416,7 +399,7 @@ test.each([ }, ); -test.each(Object.entries(leaves))( +test.each(Object.entries(leavesWithoutWatch))( 'classifies the fold fact for the %s leaf', async (_name, device) => { const binding = await createApplePlatformRuntime(platformRuntimeHostFixture()).bind({ @@ -443,26 +426,26 @@ test.each(Object.entries(leaves))( }, ); -test.each([...Object.entries(leaves), ['ios physical device', appleDevice({ kind: 'device' })]])( - 'refuses the telephony fact for the %s leaf', - async (_name, device) => { - const binding = await createApplePlatformRuntime(platformRuntimeHostFixture()).bind({ - device, - intent: { kind: 'ordinary' }, - scope: { - signal: new AbortController().signal, - diagnostics: { emit: () => {} }, - progress: { report: () => {} }, - }, - }); - expect(binding.facts.operations.sendTelephonyEvent).toMatchObject({ - available: false, - reason: 'unsupported-platform-leaf', - hint: expect.stringContaining('Android emulator console'), - }); - expect(binding.operations.sendTelephonyEvent).toBeUndefined(); - }, -); +test.each([ + ...Object.entries(leavesWithoutWatch), + ['ios physical device', appleDevice({ kind: 'device' })], +])('refuses the telephony fact for the %s leaf', async (_name, device) => { + const binding = await createApplePlatformRuntime(platformRuntimeHostFixture()).bind({ + device, + intent: { kind: 'ordinary' }, + scope: { + signal: new AbortController().signal, + diagnostics: { emit: () => {} }, + progress: { report: () => {} }, + }, + }); + expect(binding.facts.operations.sendTelephonyEvent).toMatchObject({ + available: false, + reason: 'unsupported-platform-leaf', + hint: expect.stringContaining('Android emulator console'), + }); + expect(binding.operations.sendTelephonyEvent).toBeUndefined(); +}); // A simulator in a scoped set is admitted by the owner's own fact: the HID send and the guest hinge // and panel reads all run through `simctl --set`, so ADR 0025's post-dispatch verification holds. @@ -495,7 +478,7 @@ function expectActionButtonFact( if (!available) { expect(binding.facts.operations.actionButton).toHaveProperty( 'hint', - expect.stringContaining('Action Button is iPhone and iPad hardware'), + expect.stringContaining('Action Button is iPhone, iPad, and Apple Watch Ultra hardware'), ); } } @@ -510,21 +493,13 @@ function expectOperationAvailability( expect(binding.operations[operation]).toBeTypeOf(available ? 'function' : 'undefined'); } -/** - * watchOS has no constructible Apple interactor (XCUITest cannot drive its UI, ADR-0009), so every - * interactor-backed operation here stays unavailable there regardless of what else gates it. - */ function expectNavigationAndKeyboardFacts( binding: DeviceBinding, device: DeviceInfo, ): void { - // Every simulator/device leaf supports back except watchOS, which has no interactor, and - // visionOS, which has no back gesture. tvOS presses the Menu remote button. - expectOperationAvailability( - binding, - 'back', - device.appleOs !== 'watchos' && device.appleOs !== 'visionos', - ); + // Every simulator/device leaf supports back except visionOS, which has no back gesture. tvOS + // presses the Menu remote button. + expectOperationAvailability(binding, 'back', device.appleOs !== 'visionos'); if (device.appleOs === 'visionos') { expect(binding.facts.operations.back).toMatchObject({ reason: 'unsupported-platform-leaf', @@ -533,18 +508,17 @@ function expectNavigationAndKeyboardFacts( } // home and app-switcher share one springboard reading (R56): both are unavailable on macOS, - // which drives an already-running app with no springboard, and on watchOS. That is parity, not - // convenience — the retired `supportsAppAndDeviceLifecycle` closure gated both off the same row. - const springboard = device.appleOs !== 'macos' && device.appleOs !== 'watchos'; + // which drives an already-running app with no springboard. That is parity, not convenience — + // the retired `supportsAppAndDeviceLifecycle` closure gated both off the same row. + const springboard = device.appleOs !== 'macos'; expectOperationAvailability(binding, 'home', springboard); expectOperationAvailability(binding, 'appSwitcher', springboard); // orientation and keyboard dismiss/enter share mobile-input eligibility: unavailable on tvOS - // (focus-only XCUIRemote navigation), macOS (an AppKit desktop host), and watchOS. `status` is + // (focus-only XCUIRemote navigation) and macOS (an AppKit desktop host). `status` is // the narrower leg: the runner answers it from the keyboard's own key elements, an iOS-only read, // so visionOS is refused there even though it can press the keyboard. - const mobileInputEligible = - device.appleOs !== 'tvos' && device.appleOs !== 'macos' && device.appleOs !== 'watchos'; + const mobileInputEligible = device.appleOs !== 'tvos' && device.appleOs !== 'macos'; expectOperationAvailability(binding, 'setOrientation', mobileInputEligible); expectOperationAvailability(binding, 'unlockOrientation', false); expectOperationAvailability(binding, 'keyboardDismiss', mobileInputEligible); @@ -829,7 +803,8 @@ const LEGACY_APPLE_LIFECYCLE_CELLS = { device: LEGACY_APPLE_DEVICE, }, watchos: { - simulator: LEGACY_UNSUPPORTED, + // A watch simulator opens and closes apps through its runner and takes no runtime hints. + simulator: LEGACY_APPLE_DEVICE, emulator: LEGACY_UNSUPPORTED, device: LEGACY_UNSUPPORTED, }, @@ -923,8 +898,9 @@ function expectLegacyLifecycleFactCell( } } const snapshotAvailable = - facts.device.appleOs !== 'watchos' && - (facts.device.kind === 'simulator' || facts.device.kind === 'device'); + facts.device.appleOs === 'watchos' + ? facts.device.kind === 'simulator' + : facts.device.kind === 'simulator' || facts.device.kind === 'device'; expect(facts.operations.captureSnapshot.available).toBe(snapshotAvailable); expect(facts.operations.readTextAtPoint.available).toBe(snapshotAvailable); } diff --git a/packages/platform-apple/src/runtime.ts b/packages/platform-apple/src/runtime.ts index efe68a92f6..8b918fb7d3 100644 --- a/packages/platform-apple/src/runtime.ts +++ b/packages/platform-apple/src/runtime.ts @@ -34,12 +34,7 @@ import { type SelectorObservationRuntimeOperations } from '@agent-device/contrac import { bindLocalTypeTextInteractor } from '@agent-device/contracts/type-text-runtime'; import { bindLocalTouchInteractor } from '@agent-device/contracts/touch-runtime'; import { viewportRuntimeOperationFacts } from '@agent-device/contracts/viewport-runtime'; -import { - isIosFamily, - isMacOs, - resolveDeviceAppleOs, - type DeviceInfo, -} from '@agent-device/kernel/device'; +import { isIosFamily, isMacOs, type DeviceInfo } from '@agent-device/kernel/device'; import { audioProbeRuntimeOperationFacts } from '@agent-device/contracts/audio-probe-runtime'; import { perfRuntimeOperationFacts } from '@agent-device/contracts/perf-runtime'; import { createHostAudioProbeCaptureOperations } from '@agent-device/capture-kit'; @@ -66,6 +61,7 @@ import { bindAppleQuerySelectorRuntime } from './runtime-selector-query.ts'; import { macOsHelperSurface, type MacOsAppBackend } from '@agent-device/contracts/session'; import { hostMacOsAppBackend } from './os/macos/app-backend.ts'; import { macOsNativeBackendFacts } from './os/macos/native-backend-facts.ts'; +import { applyWatchOsOperationFacts } from './os/watchos/facts.ts'; import { createAppleSnapshotRoute } from './snapshot-route.ts'; const owner = localRuntimeOwner('apple'); @@ -95,15 +91,6 @@ const headlessUnavailable = unavailableFact( 'Headless boot is supported only for local Android emulators.', ); -const watchOpenTargetUnavailable = unavailableFact( - 'unsupported-platform-leaf', - 'watchOS open is not supported because XCUITest cannot drive watchOS UI.', -); - -const watchCloseTargetUnavailable = unavailableFact( - 'unsupported-platform-leaf', - 'watchOS close is not supported because XCUITest cannot drive watchOS UI.', -); const runtimeHintsUnavailable = unavailableFact( 'unsupported-device-kind', 'Runtime hints are supported only for local iOS-family simulators and Android devices.', @@ -125,10 +112,6 @@ const shutdownKindUnavailable = unavailableFact( 'shutdown is supported only for Apple simulators and Android emulators.', ); -const screenshotWatchOsUnavailable = unavailableFact( - 'unsupported-platform-leaf', - 'screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.', -); const screenshotKindUnavailable = unsupportedAppleDeviceKind( 'screenshot is supported only for Apple simulators and devices.', ); @@ -138,7 +121,7 @@ function unsupportedAppleDeviceKind(hint: string) { } function shutdownFact(device: DeviceInfo) { - if (!isIosFamily(device) || device.appleOs === 'watchos') return unavailable; + if (!isIosFamily(device)) return unavailable; return device.kind === 'simulator' ? available : shutdownKindUnavailable; } @@ -161,31 +144,22 @@ function appleApplicationLifecycleFacts(device: DeviceInfo) { } function appleOpenTargetFact(device: DeviceInfo) { - if (resolveDeviceAppleOs(device) === 'watchos') return watchOpenTargetUnavailable; return device.kind === 'simulator' || device.kind === 'device' ? available : appleOpenTargetKindUnavailable; } function appleCloseTargetFact(device: DeviceInfo) { - if (resolveDeviceAppleOs(device) === 'watchos') return watchCloseTargetUnavailable; return device.kind === 'simulator' || device.kind === 'device' ? available : appleCloseTargetKindUnavailable; } function appleRuntimeHintsFact(device: DeviceInfo) { - return resolveDeviceAppleOs(device) !== 'watchos' && - isIosFamily(device) && - device.kind === 'simulator' - ? available - : runtimeHintsUnavailable; + return isIosFamily(device) && device.kind === 'simulator' ? available : runtimeHintsUnavailable; } function appInventoryFacts(device: DeviceInfo) { - if (device.appleOs === 'watchos') { - return unavailableFact('unsupported-platform-leaf', 'watchOS app inventory is not supported.'); - } if (device.kind === 'device' && device.iosPhysicalDeviceBackend === 'xctest') { return unavailableFact( 'unsupported-device-backend', @@ -216,12 +190,11 @@ export function createApplePlatformRuntime(host: PlatformRuntimeHost): PlatformR leafRecordingFacts.available && hostAvailability?.available === false ? unavailableFact('unsupported-provider-mode', hostAvailability.hint) : leafRecordingFacts; - const readiness = device.appleOs === 'watchos' ? unavailable : available; - const boot = isMacOs(device) || device.appleOs === 'watchos' ? unavailable : available; + const boot = isMacOs(device) ? unavailable : available; const apps = appInventoryFacts(device); return Object.freeze({ device: logs.device, - operations: { + operations: applyWatchOsOperationFacts(device, { ...logs.operations, ...deployment, networkDump: available, @@ -238,14 +211,14 @@ export function createApplePlatformRuntime(host: PlatformRuntimeHost): PlatformR query: audioQueryUnavailable, }), ...perfRuntimeOperationFacts(applePerfFacts(device)), - ensureReady: readiness, + ensureReady: available, bootTarget: boot, bootTargetHeadless: headlessUnavailable, listApps: apps, ...appleApplicationLifecycleFacts(device), shutdownTarget: shutdownFact(device), ...macOsNativeBackendFacts(device, macOsAppBackend(device)), - }, + }), }); }; return Object.freeze({ @@ -455,8 +428,7 @@ function applePerfFacts(device: DeviceInfo): Readonly<{ nativeCapture: RuntimeOperationFact; profileReport: RuntimeOperationFact; }> { - const supported = - device.iosPhysicalDeviceBackend !== 'xctest' && resolveDeviceAppleOs(device) !== 'watchos'; + const supported = device.iosPhysicalDeviceBackend !== 'xctest'; const fact = supported ? available : perfUnavailable; return { frames: fact, @@ -473,7 +445,6 @@ function applePerfFacts(device: DeviceInfo): Readonly<{ * snapshot, whose desktop surfaces come from a separate host port. */ function appleScreenshotFact(device: DeviceInfo) { - if (resolveDeviceAppleOs(device) === 'watchos') return screenshotWatchOsUnavailable; return device.kind === 'simulator' || device.kind === 'device' ? available : screenshotKindUnavailable; diff --git a/packages/platform-apple/src/shutdown/runtime.test.ts b/packages/platform-apple/src/shutdown/runtime.test.ts index e59c848be4..ebdd5db2a8 100644 --- a/packages/platform-apple/src/shutdown/runtime.test.ts +++ b/packages/platform-apple/src/shutdown/runtime.test.ts @@ -76,9 +76,9 @@ test('cancellation during the final simulator-state probe is not swallowed', asy expect(run).toHaveBeenCalledTimes(2); }); -test('watchOS and non-simulator Apple targets are unavailable', () => { +test('only Apple simulators can be shut down', () => { expect(canShutdownTarget(appleDevice())).toBe(true); - expect(canShutdownTarget(appleDevice({ appleOs: 'watchos' }))).toBe(false); + expect(canShutdownTarget(appleDevice({ appleOs: 'watchos' }))).toBe(true); expect(canShutdownTarget(appleDevice({ kind: 'device' }))).toBe(false); }); diff --git a/packages/platform-apple/src/shutdown/runtime.ts b/packages/platform-apple/src/shutdown/runtime.ts index d0e5931c5f..e5553fa717 100644 --- a/packages/platform-apple/src/shutdown/runtime.ts +++ b/packages/platform-apple/src/shutdown/runtime.ts @@ -23,7 +23,7 @@ export function createAppleShutdownRuntime( } export function canShutdownTarget(device: DeviceInfo): boolean { - return isIosFamily(device) && device.appleOs !== 'watchos' && device.kind === 'simulator'; + return isIosFamily(device) && device.kind === 'simulator'; } async function shutdownAppleTarget( diff --git a/packages/platform-apple/src/simulator-inventory.test.ts b/packages/platform-apple/src/simulator-inventory.test.ts index eb2103f94d..1bf9603d26 100644 --- a/packages/platform-apple/src/simulator-inventory.test.ts +++ b/packages/platform-apple/src/simulator-inventory.test.ts @@ -61,6 +61,16 @@ test('simctl parser keeps available supported runtimes and their target semantic booted: false, simulatorSetPath: '/tmp/custom-set', }, + { + platform: 'apple', + id: 'watch-1', + name: 'Apple Watch', + kind: 'simulator', + target: 'mobile', + appleOs: 'watchos', + booted: true, + simulatorSetPath: '/tmp/custom-set', + }, ]); }); @@ -148,9 +158,9 @@ test('simulator inventory scopes bounded simctl and reports fresh booted observa ]); assert.deepEqual( devices.map((device) => device.id), - ['iphone-1', 'tv-1'], + ['iphone-1', 'tv-1', 'watch-1'], ); - assert.deepEqual(observed, ['iphone-1']); + assert.deepEqual(observed, ['iphone-1', 'watch-1']); }); test('simulator inventory classifies malformed native output as a command failure', async () => { diff --git a/packages/platform-apple/src/system/runtime.test.ts b/packages/platform-apple/src/system/runtime.test.ts index 0092de7a05..0eb8f3db22 100644 --- a/packages/platform-apple/src/system/runtime.test.ts +++ b/packages/platform-apple/src/system/runtime.test.ts @@ -24,9 +24,7 @@ function appleDevice( * The R55 parity cell table, restated as facts. The retired admission was the `clipboard` * capability bucket (`{ simulator: true, device: true }`) intersected with the Apple plugin's * `supportsHostOrSimulatorSurface` closure — `macos || simulator`. Every row below is that - * verdict; the one deliberate narrowing is watchOS, which the bucket admitted as a simulator but - * for which no XCUITest interactor can be constructed at all (the same reading `appleBackFact` - * takes). + * verdict. watchOS refuses clipboard in its own leaf (`os/watchos/facts.ts`). */ test.each([ { appleOs: 'ios', kind: 'simulator', expected: true }, @@ -38,7 +36,6 @@ test.each([ { appleOs: 'visionos', kind: 'simulator', expected: true }, { appleOs: 'visionos', kind: 'device', expected: false }, { appleOs: 'macos', kind: 'device', expected: true }, - { appleOs: 'watchos', kind: 'simulator', expected: false }, ] as const)( 'clipboard on an Apple $appleOs $kind is available: $expected', ({ appleOs, kind, expected }) => { @@ -58,7 +55,6 @@ test.each([ { appleOs: 'ios', kind: 'device', expected: true }, { appleOs: 'macos', kind: 'device', expected: true }, { appleOs: 'tvos', kind: 'simulator', expected: true }, - { appleOs: 'watchos', kind: 'simulator', expected: false }, ] as const)( 'trigger-app-event on an Apple $appleOs $kind is available: $expected', ({ appleOs, kind, expected }) => { @@ -70,7 +66,7 @@ test.each([ * `settings` shares clipboard's exact reading, and that sharing is the parity claim: the retired * admission intersected the `settings` bucket (`{ simulator: true, device: true }`) with the same * `supportsHostOrSimulatorSurface` closure. Only the refusal wording differs, so the table is - * clipboard's verbatim — including the watchOS narrowing. + * clipboard's verbatim. */ test.each([ { appleOs: 'ios', kind: 'simulator', expected: true }, @@ -82,7 +78,6 @@ test.each([ { appleOs: 'visionos', kind: 'simulator', expected: true }, { appleOs: 'visionos', kind: 'device', expected: false }, { appleOs: 'macos', kind: 'device', expected: true }, - { appleOs: 'watchos', kind: 'simulator', expected: false }, ] as const)( 'settings on an Apple $appleOs $kind is available: $expected', ({ appleOs, kind, expected }) => { @@ -127,7 +122,6 @@ test.each([ { appleOs: 'visionos', kind: 'simulator', expected: false }, { appleOs: 'visionos', kind: 'device', expected: false }, { appleOs: 'macos', kind: 'device', expected: false }, - { appleOs: 'watchos', kind: 'simulator', expected: false }, ] as const)( 'reading a setting on an Apple $appleOs $kind is available: $expected', ({ appleOs, kind, expected }) => { @@ -184,13 +178,6 @@ test('a setting outside the handheld simulators names the leaf that serves it', }); }); -test('watchOS closes the read leg for the reason it closes every interactor-backed operation', () => { - expect(appleSystemFacts(appleDevice('watchos', 'simulator')).readSetting).toEqual({ - available: false, - reason: 'unsupported-platform-leaf', - }); -}); - test('a leaf that can set a setting can be refused the right to read one back', () => { // The asymmetry the two-leg split exists for: tvOS keeps `settings wifi on` and loses the read. const facts = appleSystemFacts(appleDevice('tvos', 'simulator')); @@ -201,7 +188,7 @@ test('a leaf that can set a setting can be refused the right to read one back', /** * `alert`'s retired admission was the host-or-simulator closure widened by one leaf: physical * iOS, whose XCTest alert path is device-verified. Every other physical Apple leaf stays closed - * exactly as `supportsAlertSurface` left it, and watchOS narrows for want of an interactor. + * exactly as `supportsAlertSurface` left it. */ test.each([ { appleOs: 'ios', kind: 'simulator', expected: true }, @@ -213,7 +200,6 @@ test.each([ { appleOs: 'visionos', kind: 'simulator', expected: true }, { appleOs: 'visionos', kind: 'device', expected: false }, { appleOs: 'macos', kind: 'device', expected: true }, - { appleOs: 'watchos', kind: 'simulator', expected: false }, ] as const)( 'alert on an Apple $appleOs $kind is available: $expected', ({ appleOs, kind, expected }) => { diff --git a/packages/platform-apple/src/system/runtime.ts b/packages/platform-apple/src/system/runtime.ts index 63c8e13f5f..393aa9e986 100644 --- a/packages/platform-apple/src/system/runtime.ts +++ b/packages/platform-apple/src/system/runtime.ts @@ -60,16 +60,6 @@ const clipboardLeafUnavailable = Object.freeze({ reason: 'unsupported-platform-leaf', hint: 'clipboard is supported on Apple simulators and the macOS host, not on physical devices of this OS.', } as const); -/** - * watchOS has no XCUITest-driveable UI (ADR-0009), so no Apple interactor can be constructed for - * it and every interactor-backed operation stays unavailable there — the same reading - * `appleBackFact` takes, and for the same reason: facts are the support authority, not a mirror - * of a capability table that never modeled interactor constructibility. - */ -const appleWatchOsUnavailable = Object.freeze({ - available: false, - reason: 'unsupported-platform-leaf', -} as const); /** * The one host-or-simulator reading `clipboard` and `settings` share, and sharing it is parity @@ -84,7 +74,6 @@ function appleHostOrSimulatorFact( ): RuntimeOperationFact { if (device.kind !== 'simulator' && device.kind !== 'device') return kindUnavailable; const os = resolveDeviceAppleOs(device); - if (os === 'watchos') return appleWatchOsUnavailable; if (device.kind === 'simulator') return available; return os === 'macos' ? available : leafUnavailable; } @@ -135,7 +124,6 @@ const alertLeafUnavailable = Object.freeze({ function appleAlertFact(device: DeviceInfo): RuntimeOperationFact { if (device.kind !== 'simulator' && device.kind !== 'device') return alertKindUnavailable; const os = resolveDeviceAppleOs(device); - if (os === 'watchos') return appleWatchOsUnavailable; if (device.kind === 'simulator' || os === 'ios' || os === 'macos') return available; return alertLeafUnavailable; } @@ -143,11 +131,11 @@ function appleAlertFact(device: DeviceInfo): RuntimeOperationFact { /** * No apple-family closure ever gated `trigger-app-event` beyond its capability bucket * (`{ simulator, device }`): the deep link opens through the same interactor `open` every Apple - * leaf drives. watchOS is the one narrowing, for want of a constructible interactor at all. + * leaf drives. */ function appleAppEventFact(device: DeviceInfo): RuntimeOperationFact { if (device.kind !== 'simulator' && device.kind !== 'device') return appEventKindUnavailable; - return resolveDeviceAppleOs(device) === 'watchos' ? appleWatchOsUnavailable : available; + return available; } /** diff --git a/src/__tests__/command-descriptor-shutdown-runtime-execution.test.ts b/src/__tests__/command-descriptor-shutdown-runtime-execution.test.ts index 2a35dd3152..265f440bfb 100644 --- a/src/__tests__/command-descriptor-shutdown-runtime-execution.test.ts +++ b/src/__tests__/command-descriptor-shutdown-runtime-execution.test.ts @@ -65,7 +65,7 @@ test('canonical shutdown and close parity share one concrete teardown mechanic', expect(sharedHostSource).not.toContain('shutdownAndroidEmulator'); expect(appleShutdownSource).toContain("tool: 'simctl'"); - expect(appleShutdownSource).toContain("device.appleOs !== 'watchos'"); + expect(appleShutdownSource).toContain("device.kind === 'simulator'"); expect(androidShutdownSource).toContain("executable: 'adb'"); expect(androidShutdownSource).toContain("device.platform === 'android'"); }); diff --git a/src/platform-runtime-gateway-gesture-admission.test.ts b/src/platform-runtime-gateway-gesture-admission.test.ts index c963d304a8..0e3bfac8c8 100644 --- a/src/platform-runtime-gateway-gesture-admission.test.ts +++ b/src/platform-runtime-gateway-gesture-admission.test.ts @@ -105,7 +105,8 @@ test('TV, spatial, watch, desktop, Linux, and web gesture policy stays explicit' }); expect(tvOs.operations.performMultiTouchGesturePlan.available).toBe(false); expect(visionOs.operations.performMultiTouchGesturePlan.available).toBe(false); - expect(watchOs.operations.performGesturePlan.available).toBe(false); + expect(watchOs.operations.performGesturePlan.available).toBe(true); + expect(watchOs.operations.performMultiTouchGesturePlan.available).toBe(false); expect(macOs.operations.performGesturePlan.available).toBe(true); expect(macOs.operations.performMultiTouchGesturePlan.available).toBe(false); expect(linux.operations.performGesturePlan.available).toBe(true); From d1e5e1e847861af91b6fcc6c30a6845cc74d0ca2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 14:39:16 +0100 Subject: [PATCH 03/20] docs: document watchOS simulators and amend ADR 0009 Co-Authored-By: Claude Opus 5.5 --- docs/adr/0009-apple-platform-consolidation.md | 18 ++++++++---- .../0019-request-bound-platform-runtime.md | 2 +- website/docs/docs/commands.md | 28 ++++++++++++++++++- website/docs/docs/introduction.md | 2 +- 4 files changed, 42 insertions(+), 8 deletions(-) diff --git a/docs/adr/0009-apple-platform-consolidation.md b/docs/adr/0009-apple-platform-consolidation.md index 47c08b9bbc..9082d6d59b 100644 --- a/docs/adr/0009-apple-platform-consolidation.md +++ b/docs/adr/0009-apple-platform-consolidation.md @@ -12,7 +12,7 @@ ADR 0019 owns the cutover and substrate transition rules. Completed migration hi Apple support shared an engine while presenting asymmetric iOS, tvOS, and macOS models. Inferring the OS from the target lost information, and the structure did not model iPadOS, visionOS, or watchOS. Distinguishing or adding an Apple OS therefore cost more than its implementation required. -The XCTest runner builds iOS, macOS, and tvOS from one project. +The XCTest runner builds iOS, macOS, tvOS, visionOS, and the watchOS simulator from one project. ## Decision @@ -25,8 +25,11 @@ This design composes with the daemon facet and descriptor `platformExecution` de Keep macOS as a distinct AppKit leaf with its helper binary and menubar and desktop surface model. Do not flatten the tvOS focus-only interaction contract, which has no coordinate `tap`, across OSes. -Keep watchOS as an unsupported sentinel: the Apple interactor, gesture admission, and supported-deployment check reject it, and discovery never produces it. -XCUITest cannot drive watchOS UI. +Support watchOS simulators through the shared XCUITest runner. +The runner's host app and UI-test targets build for the watchOS simulator SDK. A SwiftUI host replaces the UIKit host there. +The watchOS leaf (`os/watchos/facts.ts`) admits only operations with a watch meaning and refuses every other operation. +The Digital Crown is `scroll` (rotation) and `home` (press). One-finger swipe and pan are admitted. Multi-touch is refused. +Physical watches are out of scope: a watch reaches the Mac only through its paired iPhone. The public wire continues to emit `ios` and `macos` leaves through `PUBLIC_PLATFORMS`. Internal family ownership must not leak into that compatibility projection. @@ -36,6 +39,7 @@ Internal family ownership must not leak into that compatibility projection. - One `Platform` literal per Apple OS: `DeviceTarget` already spans platforms, and Android TV uses `target: 'tv'`, so a `tvos` literal would conflict with the form-factor axis. Every Apple branch site would need to enumerate six literals, and the single-bucket `apple` capability and selector model would break. - Keep the existing structure: it retains asymmetric and mislabeled support and lossy OS inference without a path to iPadOS or visionOS. +- A separate watchOS runner project or a watchOS plugin: both would fork the runner sources and the Apple engine. The watch differences are a few `os(watchOS)` guards and one fact leaf. - Exclude macOS: it shares the XCUITest project, and its code already lived in the shared Apple engine, so exclusion would keep the incorrect label. A distinct AppKit leaf normalizes macOS without making it the same as the other OSes. @@ -47,6 +51,10 @@ Snapshot fidelity is uneven, and the deep-RN AX-server fallback is iOS-simulator visionOS discovery and simulator deployment are supported. App deployment is also admitted for CoreDevice-backed physical devices; XCTest-backed physical deployment is unsupported. Push remains simulator-only. -As of 2026-08, no public-command coverage is claimed for visionOS or watchOS. -This record states the boundary without a command-coverage manifest for either leaf. +As of 2026-08, no public-command coverage is claimed for visionOS. +This record states the boundary without a command-coverage manifest for that leaf. +The watchOS command boundary is the leaf's admission set; its evidence is in #4735 and #4738. + +Decision history: until 2026-11 this record kept watchOS as an unsupported sentinel because "XCUITest cannot drive watchOS UI". +Spike #4735 showed that the watchOS simulator SDK ships XCUIAutomation and that the existing runner builds and runs there. Net-new visionOS spatial-input QA remains deferred. diff --git a/docs/adr/0019-request-bound-platform-runtime.md b/docs/adr/0019-request-bound-platform-runtime.md index 9c0c9d264f..2d7506909b 100644 --- a/docs/adr/0019-request-bound-platform-runtime.md +++ b/docs/adr/0019-request-bound-platform-runtime.md @@ -104,7 +104,7 @@ The handler must not silently use a path known to lose the observation. The registry owns each family exactly once. Support coverage is separate and must preserve legacy supported and unsupported cells and hints unless a separate decision changes behavior. -Apple coverage includes iOS simulator and physical differences, iPadOS, tvOS focus-only/no-coordinate behavior, macOS, visionOS deferred or supported cells, and the watchOS unsupported/discovery-absence sentinel. +Apple coverage includes iOS simulator and physical differences, iPadOS, tvOS focus-only/no-coordinate behavior, macOS, visionOS deferred or supported cells, and the watchOS simulator leaf, which admits only its listed operations. Each fixture matches one family; a generic Apple fixture does not prove leaf coverage. ### 3. Provider ownership is exact and fail-closed diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 9820ccd24d..38f0d6cf96 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -73,7 +73,7 @@ agent-device daemon status --json Boot and shut down: - `boot` gets the selected target ready without launching an app. It needs an active session or a device selector. You mainly need it when `open` fails because no simulator or emulator is booted. -- `boot --pick newest` boots one device when the request names none and several equally preferred devices match, all shut down. Without it, `boot` fails with `AMBIGUOUS_MATCH` and its hint names the option. Device ranking applies to ordinary selection and the `AMBIGUOUS_MATCH` count as well as this option: among Apple devices of the same kind, an iPhone ranks above an iPad, then tvOS, then visionOS. Among the tied devices, it prefers a mobile target over a TV, then the newest OS version, then the first name in name order. Name order compares numbers by value, so iPhone 9 comes before iPhone 17, but it is not device age: with equal OS versions, iPhone 16e comes before iPhone 17. Stopped Android AVDs report no OS version, so the name decides between them. It never picks between booted devices or provider devices. The response names the device and reports `selection.reason: newest-bootable-local`. +- `boot --pick newest` boots one device when the request names none and several equally preferred devices match, all shut down. Without it, `boot` fails with `AMBIGUOUS_MATCH` and its hint names the option. Device ranking applies to ordinary selection and the `AMBIGUOUS_MATCH` count as well as this option: among Apple devices of the same kind, an iPhone ranks above an iPad, then tvOS, then visionOS, then watchOS. Among the tied devices, it prefers a mobile target over a TV, then the newest OS version, then the first name in name order. Name order compares numbers by value, so iPhone 9 comes before iPhone 17, but it is not device age: with equal OS versions, iPhone 16e comes before iPhone 17. Stopped Android AVDs report no OS version, so the name decides between them. It never picks between booted devices or provider devices. The response names the device and reports `selection.reason: newest-bootable-local`. - Android: `boot --platform android --device ` launches that emulator with a window; add `--headless` to launch it without one. On macOS the window opens behind the focused app, which keeps focus (also when `open` boots a stopped AVD). This is best-effort: the emulator can still take focus if the focused app cannot be read, or if its window appears after the startup budget runs out. - `shutdown` turns off the selected local Apple simulator or Android emulator. On [Limrun](/docs/limrun#create-and-delete-an-instance), it deletes an instance that agent-device created or releases an attachment to an existing instance. It refuses a device used by an active session; use `close --shutdown` to end that session first. - `--timeout ` on `boot`, `open `, and `prepare ios-runner` is the startup budget for booting an iOS Simulator or Android emulator (for `prepare ios-runner`, shared with runner preparation). A never-booted iOS Simulator can take several minutes. When the budget runs out, the command fails with `error.details.reason: boot_timeout` and the device keeps booting, so a retry finds it further along. See [Sessions](/docs/sessions#wait-for-a-slow-or-busy-device). @@ -342,6 +342,32 @@ vega virtual-device stop - Samsung Tizen TVs run through the optional `@agent-device/tizen` plugin, which drives web apps over the Chrome DevTools Protocol. See [Samsung Tizen](/docs/tizen). - On Android TV and tvOS, use `screenshot --overlay-refs` for visual focus evidence, especially when focus metadata is missing or transient. +## watchOS simulators + +Apple Watch simulators use the same XCUITest runner as iOS. Select one with `--platform ios` and its `--udid` or `--device` name; a watch is never picked when another Apple simulator matches. + +```bash +agent-device open com.apple.NanoSettings --platform ios --device "Apple Watch Series 11 (46mm)" --session watch +agent-device snapshot -i --session watch +agent-device press 'label="Smart Stack"' --session watch --settle +agent-device scroll down --session watch +agent-device swipe 180 124 20 124 --session watch +agent-device back --session watch +agent-device close --session watch --shutdown +``` + +- Simulators only. A physical Apple Watch is refused with `reason: unsupported-device-kind`. The host needs the watchOS simulator runtime: `xcodebuild -downloadPlatform watchOS`. +- `scroll up|down` turns the Digital Crown. The amount is a fraction of the screen height, so `scroll down 1` moves about one screen. The crown also moves pickers and steppers that have crown focus. `scroll left|right` is refused; swipe instead. +- `swipe` and `gesture swipe|pan|fling` send one-finger touches to the session app: horizontal and vertical pages, row swipe actions, and pan in custom views. `gesture swipe right-edge` (from the left edge toward the right) goes back. +- Commands act on the session app and bring it back to the foreground first. The watch face and its overlays, such as Notification Center and the Smart Stack, are not reachable. +- `back` presses the navigation bar back button, or swipes in from the left edge when there is none. +- `home` presses the Digital Crown. From an app it shows the watch face; from the watch face it opens the app grid. +- `fill` and `type` type into the system input sheet that a text field opens, then press its Done button. The sheet is found by its English Done label. +- `action-button` presses the Action Button on Apple Watch Ultra; other models refuse with `hardware_control_unavailable`. +- `open`, `close`, `install`, `uninstall`, `boot`, `snapshot`, `find`, `wait`, `is`, `get`, `press`, `longpress`, `appstate`, and `screenshot` work as on iOS. +- Everything else is refused before dispatch with `reason: unsupported-platform-leaf`, including `orientation`, `keyboard`, `app-switcher`, `clipboard`, `settings`, `alert`, `record`, `logs`, `network`, `perf`, `push`, `apps`, and multi-touch gestures such as `gesture pinch`. watchOS apps have no pinch or rotate gestures, and the App Switcher opens on a crown double-click that XCUITest cannot press. +- Open apps by bundle ID. Without `apps`, there is no name lookup. + ## Desktop targets ```bash diff --git a/website/docs/docs/introduction.md b/website/docs/docs/introduction.md index 2b8c7f8bae..504908ee27 100644 --- a/website/docs/docs/introduction.md +++ b/website/docs/docs/introduction.md @@ -3,7 +3,7 @@ title: Introduction description: Learn what agent-device is, where it fits in agentic mobile, TV, desktop, and web development, and how agents use it for app verification, debugging, profiling, QA, and replay. --- -`agent-device` is an open source device layer for coding agents: a CLI, MCP server, and Node.js API that let agents verify and QA apps, locally or in device clouds, on iOS, Android, HarmonyOS, tvOS, Android TV, Fire TV devices running Fire OS, Amazon Vega OS TV apps in the Vega Virtual Device, macOS (including Electron apps), Linux desktop targets, and a limited managed web browser. Which interactions, structured UI, evidence, performance, and replay features you get depends on what each target supports. +`agent-device` is an open source device layer for coding agents: a CLI, MCP server, and Node.js API that let agents verify and QA apps, locally or in device clouds, on iOS, Android, HarmonyOS, tvOS, watchOS simulators, Android TV, Fire TV devices running Fire OS, Amazon Vega OS TV apps in the Vega Virtual Device, macOS (including Electron apps), Linux desktop targets, and a limited managed web browser. Which interactions, structured UI, evidence, performance, and replay features you get depends on what each target supports. Use it when an agent needs to inspect and operate a running app, not only reason about source code or screenshots. From 02d59dffa741a958aa7dd992ad8030307cb3b8f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 14:58:23 +0100 Subject: [PATCH 04/20] fix(apple): harden the watchOS runner paths and watch classification Review fixes: the input sheet's text view is read only when it exists, a planned gesture resolves the app window before synthesizing, a crown scroll waits for its deceleration, back presses only an unambiguous back button, and a screen-edge swipe starts on the edge as a coordinate drag. Watch simulators are classified from simctl identifiers only, never a user-chosen name, and rank below every other Apple device. The packaged SwiftPM manifest gets the same watchOS minimum. Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+SynthesizedInteraction.swift | 6 +++ .../RunnerTests+WatchInteraction.swift | 38 ++++++++++++++++--- .../Package.runner.swift | 1 + .../device-selection-resolver.test.ts | 35 +++++++++++++++++ packages/kernel/src/device.ts | 4 +- .../src/inventory-classification.ts | 7 +++- .../src/simulator-inventory.test.ts | 23 +++++++++++ 7 files changed, 105 insertions(+), 9 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift index fb31e6895c..090e934702 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift @@ -774,6 +774,12 @@ extension RunnerTests { if plan.contactOrigin == runnerScreenEdgeContactOrigin { return .screenEdgeTouch } +#elseif os(watchOS) + // The watchOS sampled path starts a screen-edge contact on the edge itself; a fast coordinate + // drag would start inside the plan's in-content margin and reach a row instead. + if plan.contactOrigin == runnerScreenEdgeContactOrigin { + return .sampled(schedule: nil) + } #endif guard plan.topology == "single" else { return .sampled(schedule: nil) } return plan.executionProfile == "endpoint-hold" ? .fastSwipe : .sampled(schedule: plan.executionProfile) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift index 83d5225ff7..24291dc21d 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift @@ -11,6 +11,9 @@ extension RunnerTests { static let watchInputSheetTimeout: TimeInterval = 3.0 /// The input sheet's commit button. The sheet exposes no identifier for it. static let watchInputSheetDoneLabel = "Done" + /// How long a crown scroll waits for its deceleration. A tap sent while the list still moves is + /// absorbed by the scroll view instead of reaching its target. + static let watchCrownSettleInterval: TimeInterval = 0.35 /// `scroll` on a watch turns the Digital Crown, the watch's scroll input. The crown is vertical, /// so a horizontal scroll is refused; horizontal pages answer `swipe`. @@ -41,6 +44,7 @@ extension RunnerTests { XCUIDevice.shared.rotateDigitalCrown(delta: direction == .down ? delta : -delta) } } + RunLoop.current.run(until: Date().addingTimeInterval(Self.watchCrownSettleInterval)) return gestureResponse(message: "scrolled", timing: timing) } @@ -48,8 +52,9 @@ extension RunnerTests { /// the two ways watchOS pops a navigation stack. @MainActor func performWatchBack(app: XCUIApplication) throws -> InAppBackOutcome { - let button = app.buttons[Self.navigationBarBackButtonIdentifier] - if button.exists, button.isHittable { + // A push transition can briefly show two back buttons; only an unambiguous one is pressed. + let buttons = app.buttons.matching(identifier: Self.navigationBarBackButtonIdentifier).allElementsBoundByIndex + if buttons.count == 1, let button = buttons.first, button.isHittable { let frame = button.frame _ = try tapAt(app: app, x: frame.midX, y: frame.midY) return .performed @@ -76,6 +81,27 @@ extension RunnerTests { hint: "watchOS apps have no multi-touch gestures. Use swipe, gesture pan, or scroll." ) } + guard let resolved = resolveRunnerWindowElement(app: app) else { + return .notDispatched(message: "gesture could not resolve the app window", hint: nil) + } + if plan.contactOrigin == runnerScreenEdgeContactOrigin, + let first = plan.pointers[0].samples.first, + let last = plan.pointers[0].samples.last + { + // watchOS starts an edge swipe (back) only from a touch on the screen edge itself, and only + // a drag with real travel time; a short synthesized path is read as a tap on a row. + let edgeX = first.point.x < Double(resolved.frame.midX) + ? Double(resolved.frame.minX) + 1 + : Double(resolved.frame.maxX) - 1 + return try dragAt( + app: app, + x: edgeX, + y: first.point.y, + x2: last.point.x, + y2: last.point.y, + holdDuration: coordinateDragHoldDuration() + ) + } let pointerSamples: [[[String: NSNumber]]] = plan.pointers.map { pointer in pointer.samples.map { sample in [ @@ -85,10 +111,11 @@ extension RunnerTests { ] } } + let window = resolved.window var dispatched: ObjCBool = false let failure = RunnerSynthesizedGesture.synthesizeGesture( withApplication: app, - resolvedWindow: app.windows.firstMatch, + resolvedWindow: window, interfaceOrientation: 1, pointerSamples: pointerSamples, dispatched: &dispatched @@ -120,8 +147,9 @@ extension RunnerTests { )) } withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .bothSkipped) { - if resolveTextEntryMode(command) == .replacement { - let existing = (activeApp.textViews.firstMatch.value as? String) ?? "" + let sheetText = activeApp.textViews.firstMatch + if resolveTextEntryMode(command) == .replacement, sheetText.exists { + let existing = (sheetText.value as? String) ?? "" if !existing.isEmpty { activeApp.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: existing.count)) } diff --git a/apple/snapshot-presentation/Package.runner.swift b/apple/snapshot-presentation/Package.runner.swift index fd6b3e59cc..200b12beda 100644 --- a/apple/snapshot-presentation/Package.runner.swift +++ b/apple/snapshot-presentation/Package.runner.swift @@ -8,6 +8,7 @@ let package = Package( .macOS(.v13), .tvOS(.v15), .visionOS(.v1), + .watchOS(.v10), ], products: [ .library( diff --git a/packages/device-selection/src/__tests__/device-selection-resolver.test.ts b/packages/device-selection/src/__tests__/device-selection-resolver.test.ts index 1e1cb0d9de..5cddbfb9f4 100644 --- a/packages/device-selection/src/__tests__/device-selection-resolver.test.ts +++ b/packages/device-selection/src/__tests__/device-selection-resolver.test.ts @@ -321,6 +321,41 @@ test('ordinary selection remains ambiguous between equally preferred iPhones alo ); }); +test('boot --pick newest prefers visionOS to a watch when no iPhone or iPad is available', async () => { + const selection = await resolveInventoryDeviceSelection({ + devices: [ + { ...shutDownSimulator('watch', 'Apple Watch Series 11 (46mm)', '27.0'), appleOs: 'watchos' }, + { ...shutDownSimulator('vision', 'Apple Vision Pro', '26.5'), appleOs: 'visionos' }, + ], + selector: { platform: 'ios' }, + source: 'local', + boot: { pick: 'newest' }, + }); + + assert.equal(selection.device.id, 'vision'); +}); + +test('a watch simulator answers --platform ios only alone or by explicit UDID', async () => { + const watch = { + ...shutDownSimulator('watch', 'Apple Watch Series 11 (46mm)', '27.0'), + appleOs: 'watchos' as const, + }; + const phone = shutDownSimulator('iphone', 'iPhone 17', '26.5'); + for (const [devices, selector, expected] of [ + [[watch], { platform: 'ios' as const }, 'watch'], + [[phone, watch], { platform: 'ios' as const }, 'iphone'], + [[phone, watch], { platform: 'ios' as const, udid: watch.id }, 'watch'], + ] as const) { + const selection = await resolveInventoryDeviceSelection({ + devices: [...devices], + selector, + source: 'local', + boot: { pick: 'newest' }, + }); + assert.equal(selection.device.id, expected); + } +}); + test('visionOS remains selectable alone and by explicit name or UDID', async () => { const vision = { ...shutDownSimulator('vision', 'Apple Vision Pro', '27.0'), diff --git a/packages/kernel/src/device.ts b/packages/kernel/src/device.ts index 98e02005ac..9ba9d4ddee 100644 --- a/packages/kernel/src/device.ts +++ b/packages/kernel/src/device.ts @@ -952,8 +952,8 @@ function compareAppleDevicesForSelection( } function appleDeviceSelectionRank(device: DeviceInfo): number { - // A watch answers `--platform ios` only when no other Apple simulator can. - if (device.kind === 'simulator' && device.appleOs === 'watchos') return 4; + // A watch answers `--platform ios` only when no other Apple device can. + if (device.appleOs === 'watchos') return 15; if (device.kind === 'simulator') return appleTargetSelectionRank(device, 0, 1, 2, 3); if (device.kind === 'device' && isApplePlatform(device.platform) && !isMacOs(device)) return appleTargetSelectionRank(device, 10, 11, 12, 13); diff --git a/packages/platform-apple/src/inventory-classification.ts b/packages/platform-apple/src/inventory-classification.ts index 7c572a86d6..934ec46061 100644 --- a/packages/platform-apple/src/inventory-classification.ts +++ b/packages/platform-apple/src/inventory-classification.ts @@ -4,7 +4,9 @@ import { isCoreDeviceReachable } from './core/physical-device-constants.ts'; const APPLE_PRODUCT_TYPE_PATTERN = /^(iphone|ipad|ipod|appletv|realitydevice)/i; const APPLE_IPAD_PATTERN = /ipad/i; const APPLE_VISION_PATTERN = /\b(apple vision|vision pro|xros|visionos|realitydevice)\b/i; -const APPLE_WATCH_PATTERN = /\b(apple watch|apple-watch|watchos)\b/i; +// Read from simctl's runtime and device-type identifiers only: a user can name any simulator +// "Apple Watch", and a physical device is never classified as a watch. +const APPLE_WATCH_SIMULATOR_PATTERN = /\bSimRuntime\.watchOS-|\bSimDeviceType\.Apple-Watch-/i; const APPLE_MOBILE_LABEL_PATTERN = /\b(iphone|ipad|ipod)\b/i; const APPLE_TV_PRODUCT_TYPE_PATTERN = /^appletv/i; const APPLE_TV_LABEL_HINTS = ['apple tv', 'appletv', 'tvos'] as const; @@ -72,7 +74,8 @@ export function resolveAppleTargetFromLabel(value: string): DeviceTarget | null export function resolveAppleOs(target: DeviceTarget, descriptors: string[]): AppleOS { if (target === 'tv') return 'tvos'; if (descriptors.some((descriptor) => APPLE_VISION_PATTERN.test(descriptor))) return 'visionos'; - if (descriptors.some((descriptor) => APPLE_WATCH_PATTERN.test(descriptor))) return 'watchos'; + if (descriptors.some((descriptor) => APPLE_WATCH_SIMULATOR_PATTERN.test(descriptor))) + return 'watchos'; if (descriptors.some((descriptor) => APPLE_IPAD_PATTERN.test(descriptor))) return 'ipados'; return 'ios'; } diff --git a/packages/platform-apple/src/simulator-inventory.test.ts b/packages/platform-apple/src/simulator-inventory.test.ts index 1bf9603d26..d0b5b878f5 100644 --- a/packages/platform-apple/src/simulator-inventory.test.ts +++ b/packages/platform-apple/src/simulator-inventory.test.ts @@ -74,6 +74,29 @@ test('simctl parser keeps available supported runtimes and their target semantic ]); }); +test('simctl parser classifies a watch from its runtime, never from a user-chosen name', () => { + const devices = parseSimctlAppleDevices( + { + devices: { + 'com.apple.CoreSimulator.SimRuntime.watchOS-27-0': [ + { name: 'wrist', udid: 'watch-1', state: 'Shutdown', isAvailable: true }, + ], + 'com.apple.CoreSimulator.SimRuntime.iOS-27-0': [ + { name: 'Apple Watch companion', udid: 'iphone-1', state: 'Shutdown', isAvailable: true }, + ], + }, + }, + undefined, + ); + assert.deepEqual( + devices.map((device) => [device.id, device.appleOs]), + [ + ['watch-1', 'watchos'], + ['iphone-1', 'ios'], + ], + ); +}); + test('simctl parser classifies visionOS from the runtime when the name is not descriptive', () => { const [device] = parseSimctlAppleDevices( { From 649f61b1c9f07fdfdc5779ab53d45aeeea2bdd8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 15:02:14 +0100 Subject: [PATCH 05/20] fix(apple): keep the snapshot-presentation manifests on SwiftPM's watchOS default The explicit watchOS minimum made the two package manifests a new native clone. The runner builds for watchOS without it. The ADR cites the watch leaf by its repository path. Co-Authored-By: Claude Opus 5.5 --- apple/snapshot-presentation/Package.runner.swift | 1 - apple/snapshot-presentation/Package.swift | 1 - docs/adr/0009-apple-platform-consolidation.md | 2 +- 3 files changed, 1 insertion(+), 3 deletions(-) diff --git a/apple/snapshot-presentation/Package.runner.swift b/apple/snapshot-presentation/Package.runner.swift index 200b12beda..fd6b3e59cc 100644 --- a/apple/snapshot-presentation/Package.runner.swift +++ b/apple/snapshot-presentation/Package.runner.swift @@ -8,7 +8,6 @@ let package = Package( .macOS(.v13), .tvOS(.v15), .visionOS(.v1), - .watchOS(.v10), ], products: [ .library( diff --git a/apple/snapshot-presentation/Package.swift b/apple/snapshot-presentation/Package.swift index d9c9f14cef..018a655709 100644 --- a/apple/snapshot-presentation/Package.swift +++ b/apple/snapshot-presentation/Package.swift @@ -8,7 +8,6 @@ let package = Package( .macOS(.v13), .tvOS(.v15), .visionOS(.v1), - .watchOS(.v10), ], products: [ .library( diff --git a/docs/adr/0009-apple-platform-consolidation.md b/docs/adr/0009-apple-platform-consolidation.md index 9082d6d59b..3f47ad7901 100644 --- a/docs/adr/0009-apple-platform-consolidation.md +++ b/docs/adr/0009-apple-platform-consolidation.md @@ -27,7 +27,7 @@ Keep macOS as a distinct AppKit leaf with its helper binary and menubar and desk Do not flatten the tvOS focus-only interaction contract, which has no coordinate `tap`, across OSes. Support watchOS simulators through the shared XCUITest runner. The runner's host app and UI-test targets build for the watchOS simulator SDK. A SwiftUI host replaces the UIKit host there. -The watchOS leaf (`os/watchos/facts.ts`) admits only operations with a watch meaning and refuses every other operation. +The watchOS leaf (`packages/platform-apple/src/os/watchos/facts.ts`) admits only operations with a watch meaning and refuses every other operation. The Digital Crown is `scroll` (rotation) and `home` (press). One-finger swipe and pan are admitted. Multi-touch is refused. Physical watches are out of scope: a watch reaches the Mac only through its paired iPhone. From 1f3c8cae6115c93d94295d7562fff07a2c2d1cf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 15:07:45 +0100 Subject: [PATCH 06/20] fix(command-surface): keep the watchOS scroll note in CLI help only The always-loaded MCP scroll description has a byte budget, so the Digital Crown note moves to the CLI detail. Co-Authored-By: Claude Opus 5.5 --- packages/command-surface/src/interaction/index.ts | 2 +- packages/command-surface/src/interaction/metadata.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/command-surface/src/interaction/index.ts b/packages/command-surface/src/interaction/index.ts index b7ef5c7f9f..e3d01be4ba 100644 --- a/packages/command-surface/src/interaction/index.ts +++ b/packages/command-surface/src/interaction/index.ts @@ -605,7 +605,7 @@ const scrollCommandFacet = defineCommandFacet({ summary: 'Scroll in a direction or to an edge', searchHint: 'swipe down list', cliDetail: - 'A caller that verifies the screen by polling can add --no-post-gesture-stabilization. The scroll then returns right after its gesture, with no movement field and no scroll_no_progress refusal, and the next read skips the stabilization wait. With --settle the settle observation already reports the outcome, and the option removes the same wait from its first capture.', + 'A caller that verifies the screen by polling can add --no-post-gesture-stabilization. The scroll then returns right after its gesture, with no movement field and no scroll_no_progress refusal, and the next read skips the stabilization wait. With --settle the settle observation already reports the outcome, and the option removes the same wait from its first capture. On watchOS, scroll turns the Digital Crown: up and down only, and the amount is a fraction of the screen height. Use swipe for horizontal pages.', }, metadata: metadata('scroll'), run: (client, input) => client.interactions.scroll(input as ScrollOptions), diff --git a/packages/command-surface/src/interaction/metadata.ts b/packages/command-surface/src/interaction/metadata.ts index 619a569789..68c04f406d 100644 --- a/packages/command-surface/src/interaction/metadata.ts +++ b/packages/command-surface/src/interaction/metadata.ts @@ -79,7 +79,7 @@ const interactionCommandDescriptions = { 'Move input focus to explicit screen coordinates without entering text. This command changes focus only and does not enter or replace text.', type: 'Append text to the currently focused input. This requires an active input and preserves its existing text.', scroll: - 'Scroll in a direction, or toward the top/bottom edge of scrollable content. The until input scrolls to an off-screen selector in one command. The optional amount is the finger-path fraction of the viewport axis, honored up to 0.8 of it; directional scrolls reduce release momentum, while app scroll physics determine the final content offset. A visible keyboard shortens the swiped band instead of being dismissed; when too little is left, the command refuses with scroll_keyboard_occludes_surface. A directional scroll also reports the movement it observed as movement: moved, at-edge, unchanged, or unobserved when the two reads could not back a claim either way; an unchanged surface inside a container that still hides content in that direction refuses with scroll_no_progress rather than repeating the requested distance. The movement field is absent where a tier verifies per pass (top/bottom, until), where the runtime cannot read a screen, where a settle observation or a replay already owns that observation, or where the operator opted out of it. On watchOS, scroll turns the Digital Crown: up and down only, and the amount is a fraction of the screen height. Use swipe for horizontal pages.', + 'Scroll in a direction, or toward the top/bottom edge of scrollable content. The until input scrolls to an off-screen selector in one command. The optional amount is the finger-path fraction of the viewport axis, honored up to 0.8 of it; directional scrolls reduce release momentum, while app scroll physics determine the final content offset. A visible keyboard shortens the swiped band instead of being dismissed; when too little is left, the command refuses with scroll_keyboard_occludes_surface. A directional scroll also reports the movement it observed as movement: moved, at-edge, unchanged, or unobserved when the two reads could not back a claim either way; an unchanged surface inside a container that still hides content in that direction refuses with scroll_no_progress rather than repeating the requested distance. The movement field is absent where a tier verifies per pass (top/bottom, until), where the runtime cannot read a screen, where a settle observation or a replay already owns that observation, or where the operator opted out of it.', get: 'Read text or accessibility attributes from a snapshot ref or selector without changing the app. The text format returns visible content; attrs returns the element attribute map.', is: 'Check whether a selector satisfies a UI predicate such as visible, hidden, exists, absent, editable, selected, checked, focused, or text. `absent` passes only when one readable, complete, settled, unscoped, full-depth accessibility capture has zero matches. This command checks the current condition without polling.', find: 'Find by text/label/value/role/id and run action; the action defaults to click. The role locator matches snapshot kind vocabulary (button, text, text-field, switch, ...); pre-reconciliation leaf spellings (statictext, edittext, textview) stay accepted on the nodes that carried them during a deprecation window. The focus and type actions aim at a text field: the match or the field holding it, even beside other fields, or else the one enabled on-screen field inside the match. Several enabled on-screen fields inside the match refuse with AMBIGUOUS_MATCH and the field candidates, and a disabled target refuses with reason target_disabled. Web text boxes are not recognized as text fields.', From 0f87feecbf76e775e6db53b8448ad9ced5d6c224 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 15:24:40 +0100 Subject: [PATCH 07/20] fix(apple): bind only the operations a watch admits The watch fact leaf narrowed facts but the binding still carried clipboard, alert, settings, and log operations from the modules' own facts. The binding now drops every operation the watch refuses, and a test pins facts and bindings together. The action-button CLI detail names Apple Watch Ultra. Co-Authored-By: Claude Opus 5.5 --- packages/command-surface/src/system/index.ts | 2 +- .../platform-apple/src/os/watchos/facts.test.ts | 17 +++++++++++++++++ packages/platform-apple/src/os/watchos/facts.ts | 15 +++++++++++++++ packages/platform-apple/src/runtime.ts | 6 ++++-- 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/packages/command-surface/src/system/index.ts b/packages/command-surface/src/system/index.ts index 26277da6fa..c1743d74b7 100644 --- a/packages/command-surface/src/system/index.ts +++ b/packages/command-surface/src/system/index.ts @@ -754,7 +754,7 @@ const actionButtonCommandFacet = defineParameterlessCommandFacet({ summary: 'Press the iPhone, iPad, or Apple Watch Ultra Action Button', searchHint: 'side switch', cliDetail: - 'iPhone, iPad, and Apple Watch simulators. The runner asks the device for the button and reports unsupported when that model has none.', + 'iPhone, iPad, and Apple Watch Ultra simulators. The runner asks the device for the button and reports unsupported when that model has none.', }, run: (client, input) => client.command.actionButton(input), }); diff --git a/packages/platform-apple/src/os/watchos/facts.test.ts b/packages/platform-apple/src/os/watchos/facts.test.ts index beb6f91e73..f711efc76d 100644 --- a/packages/platform-apple/src/os/watchos/facts.test.ts +++ b/packages/platform-apple/src/os/watchos/facts.test.ts @@ -86,6 +86,23 @@ test('a watchOS simulator names why it refuses multi-touch, the App Switcher, an }); }); +test('a watchOS simulator binds exactly the operations its facts admit', async () => { + const binding = await createApplePlatformRuntime(platformRuntimeHostFixture()).bind({ + device: watch(), + intent: { kind: 'ordinary' }, + scope: { + signal: new AbortController().signal, + diagnostics: { emit: () => {} }, + progress: { report: () => {} }, + }, + }); + for (const [operation, fact] of Object.entries(binding.facts.operations)) { + expect(typeof (binding.operations as Record)[operation], operation).toBe( + fact.available ? 'function' : 'undefined', + ); + } +}); + test('a physical Apple Watch is refused on every operation', async () => { expect(await availableOperations(watch('device'))).toEqual([]); }); diff --git a/packages/platform-apple/src/os/watchos/facts.ts b/packages/platform-apple/src/os/watchos/facts.ts index 1fe80c6fb0..dea03bf461 100644 --- a/packages/platform-apple/src/os/watchos/facts.ts +++ b/packages/platform-apple/src/os/watchos/facts.ts @@ -92,3 +92,18 @@ export function applyWatchOsOperationFacts( + device: DeviceInfo, + facts: Readonly>, + operations: T, +): T { + if (device.appleOs !== 'watchos') return operations; + return Object.fromEntries( + Object.entries(operations).filter(([operation]) => facts[operation]?.available !== false), + ) as T; +} diff --git a/packages/platform-apple/src/runtime.ts b/packages/platform-apple/src/runtime.ts index 8b918fb7d3..d19ae5763c 100644 --- a/packages/platform-apple/src/runtime.ts +++ b/packages/platform-apple/src/runtime.ts @@ -61,7 +61,7 @@ import { bindAppleQuerySelectorRuntime } from './runtime-selector-query.ts'; import { macOsHelperSurface, type MacOsAppBackend } from '@agent-device/contracts/session'; import { hostMacOsAppBackend } from './os/macos/app-backend.ts'; import { macOsNativeBackendFacts } from './os/macos/native-backend-facts.ts'; -import { applyWatchOsOperationFacts } from './os/watchos/facts.ts'; +import { applyWatchOsOperationFacts, bindWatchOsOperations } from './os/watchos/facts.ts'; import { createAppleSnapshotRoute } from './snapshot-route.ts'; const owner = localRuntimeOwner('apple'); @@ -411,7 +411,9 @@ export function createApplePlatformRuntime(host: PlatformRuntimeHost): PlatformR device: logs.device, owner, facts, - operations: Object.freeze(operations), + operations: Object.freeze( + bindWatchOsOperations(request.device, facts.operations, operations), + ), [Symbol.asyncDispose]: async () => await logs[Symbol.asyncDispose](), }) satisfies DeviceBinding; }, From be30bdac6f4babe5d82f84f693ac56d951a3f595 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 15:38:00 +0100 Subject: [PATCH 08/20] fix(apple): apply the watch admission to the runner seam and correct the physical-watch docs createAppleRunnerRuntime reports the same watch facts as the platform runtime. Device discovery never lists a physical Apple Watch, so the docs say that instead of promising a refusal. Co-Authored-By: Claude Opus 5.5 --- packages/platform-apple/src/os/watchos/facts.ts | 4 ++-- packages/platform-apple/src/runner-runtime.ts | 3 ++- website/docs/docs/commands.md | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/platform-apple/src/os/watchos/facts.ts b/packages/platform-apple/src/os/watchos/facts.ts index dea03bf461..6d11f4b837 100644 --- a/packages/platform-apple/src/os/watchos/facts.ts +++ b/packages/platform-apple/src/os/watchos/facts.ts @@ -72,8 +72,8 @@ function watchOsRefusal(operation: string): RuntimeOperationFact { /** * Applies the watchOS admission set to an Apple leaf's computed facts. An admitted operation, and a - * refused one its own module already refuses, keep the module's fact and hint. A physical watch is - * refused everywhere. + * refused one its own module already refuses, keep the module's fact and hint. Discovery never lists + * a physical watch; one that reaches here anyway is refused everywhere. */ export function applyWatchOsOperationFacts>( device: DeviceInfo, diff --git a/packages/platform-apple/src/runner-runtime.ts b/packages/platform-apple/src/runner-runtime.ts index f693e09aa3..3efe25142e 100644 --- a/packages/platform-apple/src/runner-runtime.ts +++ b/packages/platform-apple/src/runner-runtime.ts @@ -19,6 +19,7 @@ import { bindAppleApplicationLifecycleWithServices } from './lifecycle.ts'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; import { createAppleInteractor } from './interactor.ts'; import { appleRunnerInteractionFacts } from './runner-interaction-facts.ts'; +import { applyWatchOsOperationFacts } from './os/watchos/facts.ts'; import { bindAppleAppStateRuntime } from './app-state-runtime.ts'; import { bindAppleFindTextRuntime } from './runtime-snapshot.ts'; import { bindAppleQuerySelectorRuntime } from './runtime-selector-query.ts'; @@ -121,7 +122,7 @@ export function createAppleRunnerRuntime(options: { }); }; return { - facts: appleRunnerInteractionFacts(options.device), + facts: applyWatchOsOperationFacts(options.device, appleRunnerInteractionFacts(options.device)), bindDeployment: ( request: Omit[0], 'device'>, ) => createAppleAppDeploymentOperations({ ...request, device: options.device }), diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 38f0d6cf96..014846b04b 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -356,7 +356,7 @@ agent-device back --session watch agent-device close --session watch --shutdown ``` -- Simulators only. A physical Apple Watch is refused with `reason: unsupported-device-kind`. The host needs the watchOS simulator runtime: `xcodebuild -downloadPlatform watchOS`. +- Simulators only. Device discovery does not list a physical Apple Watch. The host needs the watchOS simulator runtime: `xcodebuild -downloadPlatform watchOS`. - `scroll up|down` turns the Digital Crown. The amount is a fraction of the screen height, so `scroll down 1` moves about one screen. The crown also moves pickers and steppers that have crown focus. `scroll left|right` is refused; swipe instead. - `swipe` and `gesture swipe|pan|fling` send one-finger touches to the session app: horizontal and vertical pages, row swipe actions, and pan in custom views. `gesture swipe right-edge` (from the left edge toward the right) goes back. - Commands act on the session app and bring it back to the foreground first. The watch face and its overlays, such as Notification Center and the Smart Stack, are not reachable. From e852f0b7987de7d07bdc007e9464d72a5721b44f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 16:21:24 +0100 Subject: [PATCH 09/20] ci(apple): compile the watchOS runner on runner-owning PRs The PR-time runner build job gains a watchOS leg beside tvOS and visionOS, with its own swift-runner-watchos gate, so a watchOS-only build break fails the PR instead of the release. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/apple.yml | 32 +++++++++++++++------ scripts/__tests__/apple-ci-impact.test.ts | 15 ++++++---- scripts/check-affected/checks.ts | 1 + scripts/check-affected/device-lanes.test.ts | 1 + scripts/check-affected/model.test.ts | 5 +++- scripts/check-affected/model.ts | 7 +++++ 6 files changed, 45 insertions(+), 16 deletions(-) diff --git a/.github/workflows/apple.yml b/.github/workflows/apple.yml index e13b5407bd..c2c5f9baf8 100644 --- a/.github/workflows/apple.yml +++ b/.github/workflows/apple.yml @@ -277,15 +277,15 @@ jobs: run: test "$RESULT" = success # PR-time compile guard for the runner platforms the smoke lanes never build. The iOS and - # macOS runners are compiled by smoke-apple-platform above, but tvOS and visionOS compiled - # only at release time (scripts/build-package-xcuitest.mjs), which let #4608 escape to - # release. This job runs the same xcodebuild build-for-testing compile for those two + # macOS runners are compiled by smoke-apple-platform above, but tvOS, visionOS, and watchOS + # compiled only at release time (scripts/build-package-xcuitest.mjs), which let #4608 escape + # to release. This job runs the same xcodebuild build-for-testing compile for those three # platforms, on the same PRs that own the runner sources, so a build break that only the # release would have caught fails the PR instead. - build-runner-tvos-visionos: - name: Runner Build (tvOS + visionOS) + build-runner-tvos-visionos-watchos: + name: Runner Build (tvOS + visionOS + watchOS) if: ${{ !github.event.pull_request.draft }} - # Same image as the smoke lane's runner build; its Xcode ships the tvOS and visionOS SDKs + # Same image as the smoke lane's runner build; its Xcode ships the tvOS, visionOS, and watchOS SDKs # alongside iOS, so no separate image or toolchain selection is needed. runs-on: blacksmith-6vcpu-macos-26 timeout-minutes: 60 @@ -293,6 +293,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} TVOS_DERIVED_PATH: ${{ github.workspace }}/.tmp/tvos-runner-derived VISIONOS_DERIVED_PATH: ${{ github.workspace }}/.tmp/visionos-runner-derived + WATCHOS_DERIVED_PATH: ${{ github.workspace }}/.tmp/watchos-runner-derived steps: - name: Checkout uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd @@ -310,11 +311,11 @@ jobs: # The same selector the iOS runner build rides on (scripts/device-lane-impact.ts over the # affected-check model): the job pays macOS minutes only on PRs that own the runner build # sources (apple/runner/** and the other own:swift trees), and fails open when the change - # set cannot be established. Pushes to main run both builds unconditionally. - - name: Select tvOS/visionOS runner builds + # set cannot be established. Pushes to main run every build unconditionally. + - name: Select tvOS/visionOS/watchOS runner builds id: runner-impact shell: bash - run: node --experimental-strip-types scripts/device-lane-impact.ts swift-runner-tvos swift-runner-visionos + run: node --experimental-strip-types scripts/device-lane-impact.ts swift-runner-tvos swift-runner-visionos swift-runner-watchos # One build per platform, mirroring the iOS runner build step: separate DerivedData and # cache key per platform, generic simulator destinations so no device or runtime boot is # needed, and the release package build's variant (no unit-test flag), which is the @@ -345,3 +346,16 @@ jobs: xcuitest-destination: generic/platform=visionOS Simulator env: AGENT_DEVICE_XCUITEST_ARCHS: arm64 + + - name: Restore and build watchOS XCTest runner + if: ${{ !cancelled() && steps.runner-impact.outputs.run != 'false' }} + uses: ./.github/actions/setup-apple-runner-build + with: + derived-path: ${{ env.WATCHOS_DERIVED_PATH }} + cache-key-prefix: watchos-runner-prebuilt + cache-key-suffix: -watchos-arm64 + gate: swift-runner-watchos + xcuitest-platform: watchos + xcuitest-destination: generic/platform=watchOS Simulator + env: + AGENT_DEVICE_XCUITEST_ARCHS: arm64 diff --git a/scripts/__tests__/apple-ci-impact.test.ts b/scripts/__tests__/apple-ci-impact.test.ts index 239b0e35a0..48b1be0ecd 100644 --- a/scripts/__tests__/apple-ci-impact.test.ts +++ b/scripts/__tests__/apple-ci-impact.test.ts @@ -81,14 +81,14 @@ test('Apple smoke gives each platform an independent runner and cleanup', () => } }); -test('the tvOS/visionOS runner build job compiles only on runner-owning PRs', () => { - const job = appleWorkflow().jobs['build-runner-tvos-visionos']!; +test('the tvOS/visionOS/watchOS runner build job compiles only on runner-owning PRs', () => { + const job = appleWorkflow().jobs['build-runner-tvos-visionos-watchos']!; expect(job.if).toBe('${{ !github.event.pull_request.draft }}'); expect(job['runs-on']).toBe('blacksmith-6vcpu-macos-26'); const steps = job.steps.flatMap((step) => [step, ...(step.parallel ?? [])]); const select = steps.find((step) => step.id === 'runner-impact')!; expect(select.run).toContain( - 'scripts/device-lane-impact.ts swift-runner-tvos swift-runner-visionos', + 'scripts/device-lane-impact.ts swift-runner-tvos swift-runner-visionos swift-runner-watchos', ); const builds = steps.filter((step) => step.uses === './.github/actions/setup-apple-runner-build'); expect( @@ -100,23 +100,26 @@ test('the tvOS/visionOS runner build job compiles only on runner-owning PRs', () ).toEqual([ ['swift-runner-tvos', 'tvos', 'generic/platform=tvOS Simulator'], ['swift-runner-visionos', 'visionos', 'generic/platform=visionOS Simulator'], + ['swift-runner-watchos', 'watchos', 'generic/platform=watchOS Simulator'], ]); for (const build of builds) { expect(build.if).toContain("steps.runner-impact.outputs.run != 'false'"); expect(build.with?.['derived-path']).toMatch(/^\$\{\{ env\.\w+_DERIVED_PATH \}\}$/); expect(build.env?.AGENT_DEVICE_XCUITEST_ARCHS).toBe('arm64'); } - for (const variable of ['TVOS_DERIVED_PATH', 'VISIONOS_DERIVED_PATH']) { + for (const variable of ['TVOS_DERIVED_PATH', 'VISIONOS_DERIVED_PATH', 'WATCHOS_DERIVED_PATH']) { expect(job.env?.[variable]).toContain('runner-derived'); } - // The selector behind the job's path filter: runner sources select both new checks, unrelated - // production TypeScript selects neither, so the macOS minutes are spent only on runner PRs. + // The selector behind the job's path filter: runner sources select the new checks, unrelated + // production TypeScript selects none of them, so the macOS minutes are spent only on runner PRs. const runnerPlan = selectChecks({ changedFiles: ['apple/runner/Sources/Runner/Main.swift'] }); expect(runnerPlan.checks).toContain('swift-runner-tvos'); expect(runnerPlan.checks).toContain('swift-runner-visionos'); + expect(runnerPlan.checks).toContain('swift-runner-watchos'); const tsPlan = selectChecks({ changedFiles: ['src/platform-runtime.ts'] }); expect(tsPlan.checks).not.toContain('swift-runner-tvos'); expect(tsPlan.checks).not.toContain('swift-runner-visionos'); + expect(tsPlan.checks).not.toContain('swift-runner-watchos'); }); test.each(['ios', 'macos'] as const)('the %s job selects only its own platform', (platform) => { diff --git a/scripts/check-affected/checks.ts b/scripts/check-affected/checks.ts index ebba138104..6a22eb9e09 100644 --- a/scripts/check-affected/checks.ts +++ b/scripts/check-affected/checks.ts @@ -96,6 +96,7 @@ export const CHECK_CATALOG: readonly CheckSpec[] = [ gate('swift-runner-macos', 'Swift runner build (macOS)', 'build:xcuitest:macos', false), gate('swift-runner-tvos', 'Swift runner build (tvOS)', 'build:xcuitest:tvos', false), gate('swift-runner-visionos', 'Swift runner build (visionOS)', 'build:xcuitest:visionos', false), + gate('swift-runner-watchos', 'Swift runner build (watchOS)', 'build:xcuitest:watchos', false), // `build:android`, not `build:android-snapshot-helper`: the Android lane needs both // helpers packaged into `android/*/dist` (what the replay host verifies), where the // build script writes only the snapshot helper into `.tmp/`. diff --git a/scripts/check-affected/device-lanes.test.ts b/scripts/check-affected/device-lanes.test.ts index 9b1ef0f092..a480ae2831 100644 --- a/scripts/check-affected/device-lanes.test.ts +++ b/scripts/check-affected/device-lanes.test.ts @@ -43,6 +43,7 @@ test('a Swift runner change selects every platform build and every Apple lane', 'swift-runner-macos', 'swift-runner-tvos', 'swift-runner-visionos', + 'swift-runner-watchos', 'replay-ios', 'replay-ios-device', 'replay-macos', diff --git a/scripts/check-affected/model.test.ts b/scripts/check-affected/model.test.ts index a193af0e89..e55b332eae 100644 --- a/scripts/check-affected/model.test.ts +++ b/scripts/check-affected/model.test.ts @@ -117,7 +117,7 @@ test('android-adb stub test delegates project ownership to Vitest', () => { }); test('Swift runner change selects every XCUITest platform build', () => { - // Each platform build is its own gate in its own lane, so a Swift change owns all four. + // Each platform build is its own gate in its own lane, so a Swift change owns all five. // (The Apple device lanes ride along: the runner is what those lanes boot — device-lanes.ts.) assert.deepEqual(ids(['apple/runner/Sources/Runner/Main.swift']), [ 'native-dupes', @@ -125,6 +125,7 @@ test('Swift runner change selects every XCUITest platform build', () => { 'swift-runner-macos', 'swift-runner-tvos', 'swift-runner-visionos', + 'swift-runner-watchos', 'packaged-runner-swift', 'replay-ios', 'replay-ios-device', @@ -145,6 +146,7 @@ test('a runner XCTest source also selects the test-list and package-source check 'swift-runner-macos', 'swift-runner-tvos', 'swift-runner-visionos', + 'swift-runner-watchos', 'xctest-selection', 'packaged-runner-swift', 'replay-ios', @@ -183,6 +185,7 @@ test('the shared foreground geometry header selects the Apple runner builds', () 'swift-runner-macos', 'swift-runner-tvos', 'swift-runner-visionos', + 'swift-runner-watchos', 'packaged-runner-swift', ] as const) { assert.ok( diff --git a/scripts/check-affected/model.ts b/scripts/check-affected/model.ts index c68102fdfd..db3939718a 100644 --- a/scripts/check-affected/model.ts +++ b/scripts/check-affected/model.ts @@ -60,6 +60,7 @@ export const ALL_CHECKS = [ 'swift-runner-macos', 'swift-runner-tvos', 'swift-runner-visionos', + 'swift-runner-watchos', 'android-helpers', 'macos-helper', 'web-smoke', @@ -474,6 +475,12 @@ const BUILD_OWNERSHIP: ReadonlyArray<{ detail: 'Swift runner sources require the visionOS XCUITest build', owns: ownsAppleRunnerBuildSource, }, + { + check: 'swift-runner-watchos', + rule: 'own:swift', + detail: 'Swift runner sources require the watchOS XCUITest build', + owns: ownsAppleRunnerBuildSource, + }, // The PR lane names each runner XCTest method it runs, so renaming or deleting one // silently shrinks that lane. Selected here so the drift shows up on the change that // causes it rather than on the next nightly. From 7a133ca65caff5f7ec9bd3d6702f890308ff84e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 16:23:47 +0100 Subject: [PATCH 10/20] fix(apple): refuse an undispatched watch back tap and test the runner seam watch facts A back-button tap the runner could not dispatch now refuses instead of reporting success; the edge-swipe fallback stays unverified and the docs say so. The runner seam has a watch-device test. The watchOS docs name watch bundle IDs and describe the input sheet detection and its locale limit. Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+WatchInteraction.swift | 9 +++++++-- .../platform-apple/src/runner-runtime.test.ts | 16 ++++++++++++++++ website/docs/docs/commands.md | 6 +++--- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift index 24291dc21d..216f3bebf8 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift @@ -56,9 +56,14 @@ extension RunnerTests { let buttons = app.buttons.matching(identifier: Self.navigationBarBackButtonIdentifier).allElementsBoundByIndex if buttons.count == 1, let button = buttons.first, button.isHittable { let frame = button.frame - _ = try tapAt(app: app, x: frame.midX, y: frame.midY) - return .performed + switch try tapAt(app: app, x: frame.midX, y: frame.midY) { + case .performed: + return .performed + case .unsupported(let message, let hint), .notDispatched(let message, let hint): + return .refused(ErrorPayload(code: RunnerWireErrorCode.backSwipeNotDispatched, message: message, hint: hint)) + } } + // The edge swipe is not verified: on a root screen it changes nothing and still reports success. let surface = try resolvedTouchReferenceFrame(app: app) _ = try dragAt( app: app, diff --git a/packages/platform-apple/src/runner-runtime.test.ts b/packages/platform-apple/src/runner-runtime.test.ts index f9bffd088b..c0d76bc956 100644 --- a/packages/platform-apple/src/runner-runtime.test.ts +++ b/packages/platform-apple/src/runner-runtime.test.ts @@ -149,3 +149,19 @@ test('an observe-only capture on a provider Simulator still fails closed and nev ).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION' }); expect(commands).toHaveLength(0); }); + +test('a watch device on the runner seam reports the watch admission', () => { + const runner = createAppleRunnerRuntime({ + device: { ...IOS_SIMULATOR, appleOs: 'watchos' }, + host: { env: {}, cwd: process.cwd() }, + provider: { + hasLiveSession: () => false, + runCommand: async () => ({}), + }, + }); + expect(runner.facts.writeClipboard).toMatchObject({ + available: false, + reason: 'unsupported-platform-leaf', + }); + expect(runner.facts.tapPoint).toEqual({ available: true }); +}); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 014846b04b..abcc9646ae 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -360,13 +360,13 @@ agent-device close --session watch --shutdown - `scroll up|down` turns the Digital Crown. The amount is a fraction of the screen height, so `scroll down 1` moves about one screen. The crown also moves pickers and steppers that have crown focus. `scroll left|right` is refused; swipe instead. - `swipe` and `gesture swipe|pan|fling` send one-finger touches to the session app: horizontal and vertical pages, row swipe actions, and pan in custom views. `gesture swipe right-edge` (from the left edge toward the right) goes back. - Commands act on the session app and bring it back to the foreground first. The watch face and its overlays, such as Notification Center and the Smart Stack, are not reachable. -- `back` presses the navigation bar back button, or swipes in from the left edge when there is none. +- `back` presses the navigation bar back button, or swipes in from the left edge when there is none. The edge swipe is not verified: on a root screen it changes nothing and `back` still succeeds. - `home` presses the Digital Crown. From an app it shows the watch face; from the watch face it opens the app grid. -- `fill` and `type` type into the system input sheet that a text field opens, then press its Done button. The sheet is found by its English Done label. +- `fill` and `type` wait for the system input sheet that a text field opens (its keyboard), type into it, then press the sheet's Done button. Done is found by its English label. On another system language the text stays in the open sheet and the command fails with `TEXT_INPUT_COMMIT_NOT_OBSERVED`; press the sheet's commit button by ref. - `action-button` presses the Action Button on Apple Watch Ultra; other models refuse with `hardware_control_unavailable`. - `open`, `close`, `install`, `uninstall`, `boot`, `snapshot`, `find`, `wait`, `is`, `get`, `press`, `longpress`, `appstate`, and `screenshot` work as on iOS. - Everything else is refused before dispatch with `reason: unsupported-platform-leaf`, including `orientation`, `keyboard`, `app-switcher`, `clipboard`, `settings`, `alert`, `record`, `logs`, `network`, `perf`, `push`, `apps`, and multi-touch gestures such as `gesture pinch`. watchOS apps have no pinch or rotate gestures, and the App Switcher opens on a crown double-click that XCUITest cannot press. -- Open apps by bundle ID. Without `apps`, there is no name lookup. +- Open apps by their watch bundle ID, such as `com.apple.NanoSettings`. Without `apps` there is no name lookup, and app aliases such as `settings` resolve to iPhone bundle IDs. ## Desktop targets From 4141dd9ada12148882bdfcb2d0293b2198fbb42d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 16:29:10 +0100 Subject: [PATCH 11/20] fix(apple): bound the idle wait of the watchOS edge-swipe drags A screen-edge swipe and the back fallback ran a coordinate drag that first waited for the app to idle, so on an animating screen the command hit the runner's main-thread watchdog even though the swipe landed. Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+WatchInteraction.swift | 46 ++++++++++++------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift index 216f3bebf8..9fea06618f 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift @@ -65,14 +65,20 @@ extension RunnerTests { } // The edge swipe is not verified: on a root screen it changes nothing and still reports success. let surface = try resolvedTouchReferenceFrame(app: app) - _ = try dragAt( - app: app, - x: surface.minX + 1, - y: surface.midY, - x2: surface.minX + surface.width * 0.8, - y2: surface.midY, - holdDuration: coordinateDragHoldDuration() - ) + var dragged: Result = .success(.performed) + withBoundedInteractionIdleTimeoutIfSupported(app, waits: .bothSkipped) { + dragged = Result { + try dragAt( + app: app, + x: surface.minX + 1, + y: surface.midY, + x2: surface.minX + surface.width * 0.8, + y2: surface.midY, + holdDuration: coordinateDragHoldDuration() + ) + } + } + _ = try dragged.get() return .performed } @@ -98,14 +104,22 @@ extension RunnerTests { let edgeX = first.point.x < Double(resolved.frame.midX) ? Double(resolved.frame.minX) + 1 : Double(resolved.frame.maxX) - 1 - return try dragAt( - app: app, - x: edgeX, - y: first.point.y, - x2: last.point.x, - y2: last.point.y, - holdDuration: coordinateDragHoldDuration() - ) + // The coordinate drag would otherwise wait for the app to idle first, which an animating + // screen never does inside the command's watchdog. + var outcome: Result = .success(.performed) + withBoundedInteractionIdleTimeoutIfSupported(app, waits: .bothSkipped) { + outcome = Result { + try dragAt( + app: app, + x: edgeX, + y: first.point.y, + x2: last.point.x, + y2: last.point.y, + holdDuration: coordinateDragHoldDuration() + ) + } + } + return try outcome.get() } let pointerSamples: [[[String: NSNumber]]] = plan.pointers.map { pointer in pointer.samples.map { sample in From 25a0267f19a969e0c3cbd9270db675d4d5fd8847 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 16:35:12 +0100 Subject: [PATCH 12/20] fix(apple): verify the watchOS back swipe and the input sheet commit The back edge-swipe fallback compares the screen before and after, and answers back_swipe_no_change when nothing popped. Typing waits for the input sheet to close after Done and reports TEXT_INPUT_COMMIT_NOT_OBSERVED when it stays open. Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+WatchInteraction.swift | 55 ++++++++++++++++++- website/docs/docs/commands.md | 4 +- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift index 9fea06618f..70bdf0d561 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift @@ -11,6 +11,8 @@ extension RunnerTests { static let watchInputSheetTimeout: TimeInterval = 3.0 /// The input sheet's commit button. The sheet exposes no identifier for it. static let watchInputSheetDoneLabel = "Done" + /// How long the back edge swipe's pop animation may run before the screen is compared. + static let watchBackSettleInterval: TimeInterval = 0.6 /// How long a crown scroll waits for its deceleration. A tap sent while the list still moves is /// absorbed by the scroll view instead of reaching its target. static let watchCrownSettleInterval: TimeInterval = 0.35 @@ -63,8 +65,8 @@ extension RunnerTests { return .refused(ErrorPayload(code: RunnerWireErrorCode.backSwipeNotDispatched, message: message, hint: hint)) } } - // The edge swipe is not verified: on a root screen it changes nothing and still reports success. let surface = try resolvedTouchReferenceFrame(app: app) + let before = watchScreenSignature(app: app) var dragged: Result = .success(.performed) withBoundedInteractionIdleTimeoutIfSupported(app, waits: .bothSkipped) { dragged = Result { @@ -78,7 +80,24 @@ extension RunnerTests { ) } } - _ = try dragged.get() + if case .unsupported(let message, let hint) = try dragged.get() { + return .refused(ErrorPayload(code: RunnerWireErrorCode.backSwipeNotDispatched, message: message, hint: hint)) + } + RunLoop.current.run(until: Date().addingTimeInterval(Self.watchBackSettleInterval)) + guard let before, let after = watchScreenSignature(app: app) else { + return .unconfirmed(ErrorPayload( + code: RunnerWireErrorCode.backSwipeUnverified, + message: "The back swipe was sent, but the screen could not be read to verify it.", + hint: "Check the screen with snapshot before you retry." + )) + } + guard before != after else { + return .unconfirmed(ErrorPayload( + code: RunnerWireErrorCode.backSwipeNoChange, + message: "The back swipe changed nothing.", + hint: "A root screen has nothing to go back to. Otherwise press the screen's close control by its ref from a fresh snapshot." + )) + } return .performed } @@ -186,6 +205,13 @@ extension RunnerTests { withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .bothSkipped) { done.tap() } + guard waitForWatchInputSheetToClose(app: activeApp) else { + return Response(ok: false, error: ErrorPayload( + code: TextEntryFailure.commitNotObserved.rawValue, + message: "the watchOS input sheet stayed open after Done", + hint: "Check the screen with snapshot; the text may still be in the open input sheet." + )) + } return Response(ok: true, data: DataPayload( message: "typed", x: point.map { Double($0.x) }, @@ -194,6 +220,31 @@ extension RunnerTests { )) } + /// A cheap identity of the visible screen: the navigation bar and the first texts, read from one + /// snapshot so a vanishing element cannot record an XCTest failure. `nil` when it cannot be read. + private func watchScreenSignature(app: XCUIApplication) -> [String]? { + guard let root = try? app.snapshot() else { return nil } + var labels: [String] = [] + func visit(_ node: any XCUIElementSnapshot) { + guard labels.count < 8 else { return } + if node.elementType == .navigationBar || node.elementType == .staticText { + labels.append(node.label) + } + node.children.forEach(visit) + } + visit(root) + return labels + } + + private func waitForWatchInputSheetToClose(app: XCUIApplication) -> Bool { + let deadline = Date().addingTimeInterval(Self.watchInputSheetTimeout) + repeat { + if !app.keyboards.firstMatch.exists { return true } + RunLoop.current.run(until: Date().addingTimeInterval(TextEntryTiming.pollInterval * 5)) + } while Date() < deadline + return false + } + private func waitForWatchInputSheet(app: XCUIApplication) -> Bool { let deadline = Date().addingTimeInterval(Self.watchInputSheetTimeout) repeat { diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index abcc9646ae..ba79f53b62 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -360,9 +360,9 @@ agent-device close --session watch --shutdown - `scroll up|down` turns the Digital Crown. The amount is a fraction of the screen height, so `scroll down 1` moves about one screen. The crown also moves pickers and steppers that have crown focus. `scroll left|right` is refused; swipe instead. - `swipe` and `gesture swipe|pan|fling` send one-finger touches to the session app: horizontal and vertical pages, row swipe actions, and pan in custom views. `gesture swipe right-edge` (from the left edge toward the right) goes back. - Commands act on the session app and bring it back to the foreground first. The watch face and its overlays, such as Notification Center and the Smart Stack, are not reachable. -- `back` presses the navigation bar back button, or swipes in from the left edge when there is none. The edge swipe is not verified: on a root screen it changes nothing and `back` still succeeds. +- `back` presses the navigation bar back button, or swipes in from the left edge when there is none. When the swipe changes nothing, for example on a root screen, `back` fails with `back_swipe_no_change` (`dispatched: unknown`); press the screen's close control by ref. - `home` presses the Digital Crown. From an app it shows the watch face; from the watch face it opens the app grid. -- `fill` and `type` wait for the system input sheet that a text field opens (its keyboard), type into it, then press the sheet's Done button. Done is found by its English label. On another system language the text stays in the open sheet and the command fails with `TEXT_INPUT_COMMIT_NOT_OBSERVED`; press the sheet's commit button by ref. +- `fill` and `type` wait for the system input sheet that a text field opens (its keyboard), type into it, press the sheet's Done button, and wait for the sheet to close. Done is found by its English label. On another system language, or when the sheet stays open, the command fails with `TEXT_INPUT_COMMIT_NOT_OBSERVED` and the text stays in the sheet; press its commit button by ref. - `action-button` presses the Action Button on Apple Watch Ultra; other models refuse with `hardware_control_unavailable`. - `open`, `close`, `install`, `uninstall`, `boot`, `snapshot`, `find`, `wait`, `is`, `get`, `press`, `longpress`, `appstate`, and `screenshot` work as on iOS. - Everything else is refused before dispatch with `reason: unsupported-platform-leaf`, including `orientation`, `keyboard`, `app-switcher`, `clipboard`, `settings`, `alert`, `record`, `logs`, `network`, `perf`, `push`, `apps`, and multi-touch gestures such as `gesture pinch`. watchOS apps have no pinch or rotate gestures, and the App Switcher opens on a crown double-click that XCUITest cannot press. From 9591e883d30b1ab7e743ea9e1cb28660706bea46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 16:46:46 +0100 Subject: [PATCH 13/20] fix(apple): compare the watchOS screen by structure when verifying back The back fallback compared the first eight labels, so a ticking clock or timer could read as a navigation on a root screen. It now compares each element's type, identifier, and child count. Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+WatchInteraction.swift | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift index 70bdf0d561..5938d0b49f 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift @@ -220,20 +220,19 @@ extension RunnerTests { )) } - /// A cheap identity of the visible screen: the navigation bar and the first texts, read from one - /// snapshot so a vanishing element cannot record an XCTest failure. `nil` when it cannot be read. + /// The visible screen's structure, read from one snapshot so a vanishing element cannot record an + /// XCTest failure: each element's type, identifier, and child count, in tree order. Labels and + /// frames are left out, so a ticking clock or timer cannot read as a navigation. `nil` when the + /// tree cannot be read. private func watchScreenSignature(app: XCUIApplication) -> [String]? { guard let root = try? app.snapshot() else { return nil } - var labels: [String] = [] + var structure: [String] = [] func visit(_ node: any XCUIElementSnapshot) { - guard labels.count < 8 else { return } - if node.elementType == .navigationBar || node.elementType == .staticText { - labels.append(node.label) - } + structure.append("\(node.elementType.rawValue)|\(node.identifier)|\(node.children.count)") node.children.forEach(visit) } visit(root) - return labels + return structure } private func waitForWatchInputSheetToClose(app: XCUIApplication) -> Bool { From 6806bc1f637530cdebb1326462ee189c471246e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 16:52:04 +0100 Subject: [PATCH 14/20] fix(apple): drop the watchOS back edge-swipe fallback On watchOS the interactive pop works only while the navigation back button is shown: hiding it (navigationBarBackButtonHidden or a hidden navigation bar) disables the edge swipe too. The fallback could never succeed, so back now presses the button or refuses with back_swipe_not_dispatched, sending nothing. gesture swipe right-edge stays available. Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+WatchInteraction.swift | 73 ++++--------------- .../platform-apple/src/navigation/runtime.ts | 5 +- website/docs/docs/commands.md | 2 +- 3 files changed, 18 insertions(+), 62 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift index 5938d0b49f..df735d546e 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift @@ -11,8 +11,6 @@ extension RunnerTests { static let watchInputSheetTimeout: TimeInterval = 3.0 /// The input sheet's commit button. The sheet exposes no identifier for it. static let watchInputSheetDoneLabel = "Done" - /// How long the back edge swipe's pop animation may run before the screen is compared. - static let watchBackSettleInterval: TimeInterval = 0.6 /// How long a crown scroll waits for its deceleration. A tap sent while the list still moves is /// absorbed by the scroll view instead of reaching its target. static let watchCrownSettleInterval: TimeInterval = 0.35 @@ -50,55 +48,27 @@ extension RunnerTests { return gestureResponse(message: "scrolled", timing: timing) } - /// Back on a watch presses the navigation bar's back button, else swipes in from the left edge, - /// the two ways watchOS pops a navigation stack. + /// Back on a watch presses the navigation bar's back button. watchOS pops a stack by edge swipe + /// only while that button is shown, so a screen without one has nothing back can do, and nothing + /// is sent. @MainActor func performWatchBack(app: XCUIApplication) throws -> InAppBackOutcome { // A push transition can briefly show two back buttons; only an unambiguous one is pressed. let buttons = app.buttons.matching(identifier: Self.navigationBarBackButtonIdentifier).allElementsBoundByIndex - if buttons.count == 1, let button = buttons.first, button.isHittable { - let frame = button.frame - switch try tapAt(app: app, x: frame.midX, y: frame.midY) { - case .performed: - return .performed - case .unsupported(let message, let hint), .notDispatched(let message, let hint): - return .refused(ErrorPayload(code: RunnerWireErrorCode.backSwipeNotDispatched, message: message, hint: hint)) - } - } - let surface = try resolvedTouchReferenceFrame(app: app) - let before = watchScreenSignature(app: app) - var dragged: Result = .success(.performed) - withBoundedInteractionIdleTimeoutIfSupported(app, waits: .bothSkipped) { - dragged = Result { - try dragAt( - app: app, - x: surface.minX + 1, - y: surface.midY, - x2: surface.minX + surface.width * 0.8, - y2: surface.midY, - holdDuration: coordinateDragHoldDuration() - ) - } - } - if case .unsupported(let message, let hint) = try dragged.get() { - return .refused(ErrorPayload(code: RunnerWireErrorCode.backSwipeNotDispatched, message: message, hint: hint)) - } - RunLoop.current.run(until: Date().addingTimeInterval(Self.watchBackSettleInterval)) - guard let before, let after = watchScreenSignature(app: app) else { - return .unconfirmed(ErrorPayload( - code: RunnerWireErrorCode.backSwipeUnverified, - message: "The back swipe was sent, but the screen could not be read to verify it.", - hint: "Check the screen with snapshot before you retry." - )) - } - guard before != after else { - return .unconfirmed(ErrorPayload( - code: RunnerWireErrorCode.backSwipeNoChange, - message: "The back swipe changed nothing.", + guard buttons.count == 1, let button = buttons.first, button.isHittable else { + return .refused(ErrorPayload( + code: RunnerWireErrorCode.backSwipeNotDispatched, + message: "This screen has no navigation back button.", hint: "A root screen has nothing to go back to. Otherwise press the screen's close control by its ref from a fresh snapshot." )) } - return .performed + let frame = button.frame + switch try tapAt(app: app, x: frame.midX, y: frame.midY) { + case .performed: + return .performed + case .unsupported(let message, let hint), .notDispatched(let message, let hint): + return .refused(ErrorPayload(code: RunnerWireErrorCode.backSwipeNotDispatched, message: message, hint: hint)) + } } /// A one-finger planned gesture through the private synthesizer, which keeps the plan's timing. A @@ -220,21 +190,6 @@ extension RunnerTests { )) } - /// The visible screen's structure, read from one snapshot so a vanishing element cannot record an - /// XCTest failure: each element's type, identifier, and child count, in tree order. Labels and - /// frames are left out, so a ticking clock or timer cannot read as a navigation. `nil` when the - /// tree cannot be read. - private func watchScreenSignature(app: XCUIApplication) -> [String]? { - guard let root = try? app.snapshot() else { return nil } - var structure: [String] = [] - func visit(_ node: any XCUIElementSnapshot) { - structure.append("\(node.elementType.rawValue)|\(node.identifier)|\(node.children.count)") - node.children.forEach(visit) - } - visit(root) - return structure - } - private func waitForWatchInputSheetToClose(app: XCUIApplication) -> Bool { let deadline = Date().addingTimeInterval(Self.watchInputSheetTimeout) repeat { diff --git a/packages/platform-apple/src/navigation/runtime.ts b/packages/platform-apple/src/navigation/runtime.ts index 8bd0708c27..bd59b4e76d 100644 --- a/packages/platform-apple/src/navigation/runtime.ts +++ b/packages/platform-apple/src/navigation/runtime.ts @@ -27,8 +27,9 @@ const backVisionOsUnavailable = Object.freeze({ reason: 'unsupported-platform-leaf', hint: 'visionOS has no back command. Press the visible back control by its ref.', } as const); -/** tvOS presses the remote's Menu button, macOS taps the window back control, and iOS and watchOS - * press the navigation bar back button or swipe from the left edge. visionOS has no back. */ +/** tvOS presses the remote's Menu button, macOS taps the window back control, iOS presses the + * navigation bar back button or swipes from the left edge, and watchOS presses the navigation bar + * back button. visionOS has no back. */ function appleBackFact(device: DeviceInfo): RuntimeOperationFact { if (device.kind !== 'simulator' && device.kind !== 'device') return backKindUnavailable; const os = resolveDeviceAppleOs(device); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index ba79f53b62..b315fd994c 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -360,7 +360,7 @@ agent-device close --session watch --shutdown - `scroll up|down` turns the Digital Crown. The amount is a fraction of the screen height, so `scroll down 1` moves about one screen. The crown also moves pickers and steppers that have crown focus. `scroll left|right` is refused; swipe instead. - `swipe` and `gesture swipe|pan|fling` send one-finger touches to the session app: horizontal and vertical pages, row swipe actions, and pan in custom views. `gesture swipe right-edge` (from the left edge toward the right) goes back. - Commands act on the session app and bring it back to the foreground first. The watch face and its overlays, such as Notification Center and the Smart Stack, are not reachable. -- `back` presses the navigation bar back button, or swipes in from the left edge when there is none. When the swipe changes nothing, for example on a root screen, `back` fails with `back_swipe_no_change` (`dispatched: unknown`); press the screen's close control by ref. +- `back` presses the navigation bar back button. A screen without one, such as a root screen, refuses with `back_swipe_not_dispatched` (`dispatched: no`): watchOS pops by edge swipe only while that button is shown. Press the screen's close control by ref instead. - `home` presses the Digital Crown. From an app it shows the watch face; from the watch face it opens the app grid. - `fill` and `type` wait for the system input sheet that a text field opens (its keyboard), type into it, press the sheet's Done button, and wait for the sheet to close. Done is found by its English label. On another system language, or when the sheet stays open, the command fails with `TEXT_INPUT_COMMIT_NOT_OBSERVED` and the text stays in the sheet; press its commit button by ref. - `action-button` presses the Action Button on Apple Watch Ultra; other models refuse with `hardware_control_unavailable`. From 03b1dbb29398352e7534e165babc6c30c579d4ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 17:14:36 +0100 Subject: [PATCH 15/20] fix(apple): refuse watch typing when the field tap was not dispatched Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+WatchInteraction.swift | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift index df735d546e..34710573c0 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift @@ -141,7 +141,10 @@ extension RunnerTests { func watchTypeCommandResponse(activeApp: XCUIApplication, command: Command, text: String) throws -> Response { var point: CGPoint? if let x = command.x, let y = command.y { - if case .unsupported(let message, let hint) = try tapAt(app: activeApp, x: x, y: y) { + switch try tapAt(app: activeApp, x: x, y: y) { + case .performed: + break + case .unsupported(let message, let hint), .notDispatched(let message, let hint): return Response(ok: false, error: ErrorPayload(message: message, hint: hint)) } point = CGPoint(x: x, y: y) From f1b279198af0c358f4902b6f9f690f0d092a1e5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 17:37:09 +0100 Subject: [PATCH 16/20] fix(apple-runner): press the watchOS Digital Crown without bringing the session app forward home on watchOS was an app mutation that may launch, so the runner reactivated the session app before every press and a second home returned to the face instead of opening the app grid. watchOS home now takes a no-app launch policy and keeps the recorded-failure conversion. Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+Models.swift | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift index dac001e918..6262e51194 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift @@ -199,6 +199,18 @@ fileprivate extension CommandTraits { isReadOnly: false ) +#if os(watchOS) + /// The Digital Crown press acts on whatever is on screen: from an app it shows the watch face, and + /// from the face it opens the app grid. Bringing the session app forward first would turn every + /// press into the first one. + static let watchCrownPress = CommandTraits( + launchPolicy: .noApp, + convertsRecordedFailure: true, + retainsJournalResponseJson: true, + isReadOnly: false + ) +#endif + /// `alert get` changes nothing, so it is the one alert action that may be replayed. static let presentedSurfaceQuery = CommandTraits( retryOnSessionLoss: true, @@ -338,7 +350,14 @@ extension Command { case .querySelector: return .selectorResolution - case .mouseClick, .home, .recordStart, .activate: + case .home: +#if os(watchOS) + return .watchCrownPress +#else + return .appMutation +#endif + + case .mouseClick, .recordStart, .activate: return .appMutation } } From 485ab86445623bdffb4210f2cdb171274849812f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 17:54:25 +0100 Subject: [PATCH 17/20] fix(apple-runner): keep watchOS hardware presses on the presented surface action-button (and home before it) reactivated the session app on watchOS, because only iOS skipped activation for presented-surface commands. watchOS now takes the same no-activation route, so home shares presentedSurfaceMutation with action-button and watchCrownPress is gone. Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+CommandDispatch.swift | 15 ++++++++------- .../RunnerTests+Models.swift | 17 ++++------------- website/docs/docs/commands.md | 2 +- 3 files changed, 13 insertions(+), 21 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift index 160f7c4103..3445f53a8f 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift @@ -546,15 +546,16 @@ extension RunnerTests { return .context(ActiveCommandContext(app: mainOwned.app ?? app)) case .presentedSurface: // The command is about the surface that already has focus; activating an app under it would - // cancel exactly what the command is about. -#if os(iOS) + // cancel exactly what the command is about. On watchOS that surface is often the watch face or + // the app grid a Digital Crown press left. +#if os(iOS) || os(watchOS) return .context(ActiveCommandContext(app: resolveAppWithoutActivation(command: command))) #else - // The platform exception, written once: `SystemSurfaceHostRegistry` registers no hosts off iOS, - // so nothing is ever served in place there and such a command keeps the activation route this - // axis found it on. The host never sends either command here on macOS — `alert` answers through - // the helper and `action-button` is refused by its owner fact before dispatch — so off iOS this - // route is reached only by the tvOS and visionOS runners. + // The platform exception, written once: `SystemSurfaceHostRegistry` registers no hosts on tvOS, + // visionOS, or macOS, so nothing is ever served in place there and such a command keeps the + // activation route this axis found it on. The host never sends either command here on macOS — + // `alert` answers through the helper and `action-button` is refused by its owner fact before + // dispatch — so this route is reached only by the tvOS and visionOS runners. return prepareActivatedTarget(command: command) #endif case .existingApp: diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift index 6262e51194..e425d9179c 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift @@ -199,18 +199,6 @@ fileprivate extension CommandTraits { isReadOnly: false ) -#if os(watchOS) - /// The Digital Crown press acts on whatever is on screen: from an app it shows the watch face, and - /// from the face it opens the app grid. Bringing the session app forward first would turn every - /// press into the first one. - static let watchCrownPress = CommandTraits( - launchPolicy: .noApp, - convertsRecordedFailure: true, - retainsJournalResponseJson: true, - isReadOnly: false - ) -#endif - /// `alert get` changes nothing, so it is the one alert action that may be replayed. static let presentedSurfaceQuery = CommandTraits( retryOnSessionLoss: true, @@ -350,9 +338,12 @@ extension Command { case .querySelector: return .selectorResolution + // The watchOS Digital Crown press acts on whatever is on screen: from an app it shows the watch + // face, and from the face it opens the app grid. Like the other hardware presses, it must not + // bring the session app forward first. case .home: #if os(watchOS) - return .watchCrownPress + return .presentedSurfaceMutation #else return .appMutation #endif diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index b315fd994c..53bc794605 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -359,7 +359,7 @@ agent-device close --session watch --shutdown - Simulators only. Device discovery does not list a physical Apple Watch. The host needs the watchOS simulator runtime: `xcodebuild -downloadPlatform watchOS`. - `scroll up|down` turns the Digital Crown. The amount is a fraction of the screen height, so `scroll down 1` moves about one screen. The crown also moves pickers and steppers that have crown focus. `scroll left|right` is refused; swipe instead. - `swipe` and `gesture swipe|pan|fling` send one-finger touches to the session app: horizontal and vertical pages, row swipe actions, and pan in custom views. `gesture swipe right-edge` (from the left edge toward the right) goes back. -- Commands act on the session app and bring it back to the foreground first. The watch face and its overlays, such as Notification Center and the Smart Stack, are not reachable. +- Commands act on the session app and bring it back to the foreground first, except the hardware presses `home` and `action-button`, which act on whatever is on screen. The watch face and its overlays, such as Notification Center and the Smart Stack, are not reachable. - `back` presses the navigation bar back button. A screen without one, such as a root screen, refuses with `back_swipe_not_dispatched` (`dispatched: no`): watchOS pops by edge swipe only while that button is shown. Press the screen's close control by ref instead. - `home` presses the Digital Crown. From an app it shows the watch face; from the watch face it opens the app grid. - `fill` and `type` wait for the system input sheet that a text field opens (its keyboard), type into it, press the sheet's Done button, and wait for the sheet to close. Done is found by its English label. On another system language, or when the sheet stays open, the command fails with `TEXT_INPUT_COMMIT_NOT_OBSERVED` and the text stays in the sheet; press its commit button by ref. From ac8d720d835202a4973970292cc9d11807d84659 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 17:58:33 +0100 Subject: [PATCH 18/20] fix(apple-runner): name Apple Watch Ultra in the watchOS action-button refusal Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+CommandExecution.swift | 2 +- .../AgentDeviceRunnerUITests/RunnerTests+Interaction.swift | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift index 741186b39b..703213a441 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift @@ -579,7 +579,7 @@ extension RunnerTests { error: ErrorPayload( code: RunnerWireErrorCode.hardwareControlUnavailable, message: "actionButton requires a device model with an Action Button", - hint: "The Action Button is on iPhone 15 Pro and later and iPad Pro (M4) and later. Assign a Shortcut or App Intent to it in Settings > Action Button." + hint: Self.actionButtonUnavailableHint ) ) } diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift index 714dc66743..4b10703c08 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift @@ -243,6 +243,12 @@ extension RunnerTests { #endif } +#if os(watchOS) + static let actionButtonUnavailableHint = "The Action Button is on Apple Watch Ultra. Open an Apple Watch Ultra simulator." +#else + static let actionButtonUnavailableHint = "The Action Button is on iPhone 15 Pro and later and iPad Pro (M4) and later. Assign a Shortcut or App Intent to it in Settings > Action Button." +#endif + /// Presses the iPhone Action Button, returning false when this device cannot express the press. /// /// `XCUIDevice.press(_:)` has no hold-duration overload, so a single press is the whole gesture From 47676bfe89ff5d704b4fa300747158f17e8c382b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 18:02:51 +0100 Subject: [PATCH 19/20] fix(apple-runner): confirm the watchOS back-button press changed the navigation bar A back-button tap that dispatched but did not pop reported success. back now waits up to 1 s for the navigation bar (its identity or the back button's presence) to change and otherwise answers back_swipe_unverified, as iOS does. Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+WatchInteraction.swift | 36 ++++++++++++++++++- website/docs/docs/commands.md | 2 +- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift index 34710573c0..86747220f0 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift @@ -11,6 +11,8 @@ extension RunnerTests { static let watchInputSheetTimeout: TimeInterval = 3.0 /// The input sheet's commit button. The sheet exposes no identifier for it. static let watchInputSheetDoneLabel = "Done" + /// How long a back-button press may take to change the navigation bar before it is unconfirmed. + static let watchBackConfirmationTimeout: TimeInterval = 1.0 /// How long a crown scroll waits for its deceleration. A tap sent while the list still moves is /// absorbed by the scroll view instead of reaching its target. static let watchCrownSettleInterval: TimeInterval = 0.35 @@ -62,13 +64,45 @@ extension RunnerTests { hint: "A root screen has nothing to go back to. Otherwise press the screen's close control by its ref from a fresh snapshot." )) } + let before = watchNavigationBarIdentity(app: app) let frame = button.frame switch try tapAt(app: app, x: frame.midX, y: frame.midY) { case .performed: - return .performed + break case .unsupported(let message, let hint), .notDispatched(let message, let hint): return .refused(ErrorPayload(code: RunnerWireErrorCode.backSwipeNotDispatched, message: message, hint: hint)) } + // A pop changes the navigation bar: its title, or the back button leaves at the root. + let deadline = Date().addingTimeInterval(Self.watchBackConfirmationTimeout) + repeat { + if let before, let after = watchNavigationBarIdentity(app: app), after != before { + return .performed + } + RunLoop.current.run(until: Date().addingTimeInterval(0.1)) + } while Date() < deadline + return .unconfirmed(ErrorPayload( + code: RunnerWireErrorCode.backSwipeUnverified, + message: "back pressed the navigation bar back button, but the navigation bar did not change within 1 s. This is an unknown outcome.", + hint: "Take a snapshot to see where the app is." + )) + } + + /// The navigation bars' identities and the back button's presence, read from one snapshot so a + /// vanishing element cannot record an XCTest failure. Free text is left out, so a ticking clock or + /// timer cannot read as a pop. `nil` when the tree cannot be read. + private func watchNavigationBarIdentity(app: XCUIApplication) -> [String]? { + guard let root = try? app.snapshot() else { return nil } + var identity: [String] = [] + func visit(_ node: any XCUIElementSnapshot) { + if node.elementType == .navigationBar { + identity.append("bar|\(node.identifier)|\(node.label)") + } else if node.identifier == Self.navigationBarBackButtonIdentifier { + identity.append("back") + } + node.children.forEach(visit) + } + visit(root) + return identity } /// A one-finger planned gesture through the private synthesizer, which keeps the plan's timing. A diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 53bc794605..040d91eb63 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -360,7 +360,7 @@ agent-device close --session watch --shutdown - `scroll up|down` turns the Digital Crown. The amount is a fraction of the screen height, so `scroll down 1` moves about one screen. The crown also moves pickers and steppers that have crown focus. `scroll left|right` is refused; swipe instead. - `swipe` and `gesture swipe|pan|fling` send one-finger touches to the session app: horizontal and vertical pages, row swipe actions, and pan in custom views. `gesture swipe right-edge` (from the left edge toward the right) goes back. - Commands act on the session app and bring it back to the foreground first, except the hardware presses `home` and `action-button`, which act on whatever is on screen. The watch face and its overlays, such as Notification Center and the Smart Stack, are not reachable. -- `back` presses the navigation bar back button. A screen without one, such as a root screen, refuses with `back_swipe_not_dispatched` (`dispatched: no`): watchOS pops by edge swipe only while that button is shown. Press the screen's close control by ref instead. +- `back` presses the navigation bar back button and waits up to 1 s for the navigation bar to change; if it does not, `back` fails with `back_swipe_unverified` (`dispatched: unknown`). A screen without a back button, such as a root screen, refuses with `back_swipe_not_dispatched` (`dispatched: no`): watchOS pops by edge swipe only while that button is shown. Press the screen's close control by ref instead. - `home` presses the Digital Crown. From an app it shows the watch face; from the watch face it opens the app grid. - `fill` and `type` wait for the system input sheet that a text field opens (its keyboard), type into it, press the sheet's Done button, and wait for the sheet to close. Done is found by its English label. On another system language, or when the sheet stays open, the command fails with `TEXT_INPUT_COMMIT_NOT_OBSERVED` and the text stays in the sheet; press its commit button by ref. - `action-button` presses the Action Button on Apple Watch Ultra; other models refuse with `hardware_control_unavailable`. From 4ae2e5663c73f3fd7b3a0adc053c2475e18f40a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 18:25:23 +0100 Subject: [PATCH 20/20] refactor(apple-runner): share synthesized sample dispatch with iOS and fold the watch polls The iOS and watchOS sampled gesture paths now hand their pointer samples to one dispatchSynthesizedPointerSamples helper, and the watch's three polling loops (input sheet open, sheet closed, back confirmation) share one helper. Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+SynthesizedInteraction.swift | 43 +++++++++++----- .../RunnerTests+WatchInteraction.swift | 49 ++++++------------- 2 files changed, 45 insertions(+), 47 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift index 090e934702..6e1a38847f 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift @@ -832,6 +832,32 @@ extension RunnerTests { } #endif +#if os(iOS) || os(watchOS) + /// Hands one planned gesture's `{ x, y, offsetMs }` pointer samples to the private synthesizer and + /// maps its result. The iOS and watchOS sampled paths differ only in how they build the samples. + @MainActor + func dispatchSynthesizedPointerSamples( + app: XCUIApplication, + window: XCUIElement?, + orientation: Int, + pointerSamples: [[[String: NSNumber]]] + ) throws -> RunnerInteractionOutcome { + var dispatched: ObjCBool = false + let failure = RunnerSynthesizedGesture.synthesizeGesture( + withApplication: app, + resolvedWindow: window, + interfaceOrientation: orientation, + pointerSamples: pointerSamples, + dispatched: &dispatched + ) + return try Self.synthesizedGestureOutcome( + failure: failure, + dispatched: dispatched.boolValue, + refusalHint: "This gesture uses private XCTest event-synthesis APIs; rebuild the runner with a supported Xcode if this persists." + ) + } +#endif + /// A synthesized gesture's result. A failure before its events reached XCTest sent nothing, so it /// is a `.notDispatched` refusal, which a policy may still answer with an XCTest fallback. A failure /// after may have run, so it throws `RunnerGestureOutcomeUnknown`, which no fallback repeats. @@ -859,18 +885,11 @@ extension RunnerTests { case .resolved(let resolved): planned = resolved case .refused(let outcome): return outcome } - var dispatched: ObjCBool = false - let failure = RunnerSynthesizedGesture.synthesizeGesture( - withApplication: app, - resolvedWindow: planned.context.resolvedWindow, - interfaceOrientation: planned.orientation, - pointerSamples: planned.pointerSamples, - dispatched: &dispatched - ) - return try Self.synthesizedGestureOutcome( - failure: failure, - dispatched: dispatched.boolValue, - refusalHint: "This gesture uses private XCTest event-synthesis APIs; rebuild the runner with a supported Xcode if this persists." + return try dispatchSynthesizedPointerSamples( + app: app, + window: planned.context.resolvedWindow, + orientation: planned.orientation, + pointerSamples: planned.pointerSamples ) #elseif os(tvOS) return .unsupported( diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift index 86747220f0..e01125638b 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+WatchInteraction.swift @@ -73,13 +73,11 @@ extension RunnerTests { return .refused(ErrorPayload(code: RunnerWireErrorCode.backSwipeNotDispatched, message: message, hint: hint)) } // A pop changes the navigation bar: its title, or the back button leaves at the root. - let deadline = Date().addingTimeInterval(Self.watchBackConfirmationTimeout) - repeat { - if let before, let after = watchNavigationBarIdentity(app: app), after != before { - return .performed - } - RunLoop.current.run(until: Date().addingTimeInterval(0.1)) - } while Date() < deadline + let popped = watchPoll(timeout: Self.watchBackConfirmationTimeout) { + guard let before, let after = watchNavigationBarIdentity(app: app) else { return false } + return after != before + } + if popped { return .performed } return .unconfirmed(ErrorPayload( code: RunnerWireErrorCode.backSwipeUnverified, message: "back pressed the navigation bar back button, but the navigation bar did not change within 1 s. This is an unknown outcome.", @@ -153,19 +151,8 @@ extension RunnerTests { ] } } - let window = resolved.window - var dispatched: ObjCBool = false - let failure = RunnerSynthesizedGesture.synthesizeGesture( - withApplication: app, - resolvedWindow: window, - interfaceOrientation: 1, - pointerSamples: pointerSamples, - dispatched: &dispatched - ) - return try Self.synthesizedGestureOutcome( - failure: failure, - dispatched: dispatched.boolValue, - refusalHint: "This gesture uses private XCTest event-synthesis APIs; rebuild the runner with a supported Xcode if this persists." + return try dispatchSynthesizedPointerSamples( + app: app, window: resolved.window, orientation: 1, pointerSamples: pointerSamples ) } @@ -183,7 +170,7 @@ extension RunnerTests { } point = CGPoint(x: x, y: y) } - guard waitForWatchInputSheet(app: activeApp) else { + guard watchPoll(timeout: Self.watchInputSheetTimeout, until: { activeApp.keyboards.firstMatch.exists }) else { let failure = TextEntryFailure.notFocused return Response(ok: false, error: ErrorPayload( code: failure.rawValue, @@ -212,7 +199,7 @@ extension RunnerTests { withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .bothSkipped) { done.tap() } - guard waitForWatchInputSheetToClose(app: activeApp) else { + guard watchPoll(timeout: Self.watchInputSheetTimeout, until: { !activeApp.keyboards.firstMatch.exists }) else { return Response(ok: false, error: ErrorPayload( code: TextEntryFailure.commitNotObserved.rawValue, message: "the watchOS input sheet stayed open after Done", @@ -227,20 +214,12 @@ extension RunnerTests { )) } - private func waitForWatchInputSheetToClose(app: XCUIApplication) -> Bool { - let deadline = Date().addingTimeInterval(Self.watchInputSheetTimeout) + /// Polls `condition` on the main run loop until it holds or `timeout` passes. + private func watchPoll(timeout: TimeInterval, until condition: () -> Bool) -> Bool { + let deadline = Date().addingTimeInterval(timeout) repeat { - if !app.keyboards.firstMatch.exists { return true } - RunLoop.current.run(until: Date().addingTimeInterval(TextEntryTiming.pollInterval * 5)) - } while Date() < deadline - return false - } - - private func waitForWatchInputSheet(app: XCUIApplication) -> Bool { - let deadline = Date().addingTimeInterval(Self.watchInputSheetTimeout) - repeat { - if app.keyboards.firstMatch.exists { return true } - RunLoop.current.run(until: Date().addingTimeInterval(TextEntryTiming.pollInterval * 5)) + if condition() { return true } + RunLoop.current.run(until: Date().addingTimeInterval(0.1)) } while Date() < deadline return false }