From 4b9223d981eb3beec920db84fd458677663e2c9b Mon Sep 17 00:00:00 2001 From: Lana Begunova <70295997+lana-20@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:15:14 -0800 Subject: [PATCH] Drive Mac apps through Accessibility, inside a macOS virtual machine Measured in a macOS 26.6.2 Tart guest on an M4 Pro host (macOS 26.7.3), on MobiumDesk (docs/checks/desktop-app.swift): desktop.sh passed 20 runs in 22, the last 8 in 8. Both failures were a launch that answered no accessibility (CHALLENGES 417). Before the driver, the Accessibility API was probed from a Swift helper and from Go through purego with cgo off. Trees were identical, about 145 ms warm. An XCTest-based server read in 93-179 ms, but clicked in 687 ms, relaunched the app per session, and needs Xcode on the machine under test. The host Mac was refused before any call: devices lists it as refused, and map --device macos exits 8. go.mod moves to 1.25 for purego v0.11.3. go/parser.ParseDir is deprecated there, so apisurface parses a directory itself. --- README.md | 38 +- THIRD_PARTY_NOTICES.md | 217 +++++- clients/dotnet/Mobium/Device.cs | 5 +- clients/go/mobium.go | 4 +- .../java/src/main/java/dev/mobium/Mobium.java | 7 +- clients/javascript/README.md | 2 +- clients/javascript/index.d.ts | 6 +- clients/javascript/index.js | 4 +- clients/python/README.md | 2 +- clients/python/mobium/_device.py | 6 +- cmd/mobium/main.go | 2 +- cmd/mobium/session.go | 2 +- docs/APP-TYPES.md | 1 + docs/ARCHITECTURE.md | 6 +- docs/CHALLENGES.md | 97 ++- docs/DEVELOPMENT.md | 3 +- docs/RELEASE-CHECKLIST.md | 2 +- docs/ROADMAP.md | 19 + docs/SETUP.md | 45 ++ docs/WINDOWS.md | 5 +- docs/checks/README.md | 1 + docs/checks/desktop-app.swift | 53 ++ docs/checks/desktop.sh | 112 +++ docs/checks/lib.sh | 7 +- docs/quickstart/README.md | 2 +- go.mod | 3 +- go.sum | 2 + internal/agent/backend.go | 59 +- internal/agent/handlers.go | 19 +- internal/agent/schema.go | 6 +- internal/agent/session.go | 11 +- internal/agent/tracing.go | 5 +- internal/apisurface/flags.go | 3 +- internal/apisurface/outputschema/main.go | 3 +- internal/apisurface/parsedir.go | 53 ++ internal/apisurface/surface.go | 4 +- internal/mobiumdriver/macos.go | 335 ++++++++ internal/mobiumdriver/macos_darwin.go | 716 ++++++++++++++++++ internal/mobiumdriver/macos_other.go | 35 + internal/uitree/locator.go | 4 + internal/uitree/parse.go | 3 + internal/uitree/parse_ax.go | 261 +++++++ internal/uitree/parse_ax_test.go | 153 ++++ internal/uitree/snapshot.go | 4 +- 44 files changed, 2265 insertions(+), 62 deletions(-) create mode 100644 docs/checks/desktop-app.swift create mode 100755 docs/checks/desktop.sh create mode 100644 internal/apisurface/parsedir.go create mode 100644 internal/mobiumdriver/macos.go create mode 100644 internal/mobiumdriver/macos_darwin.go create mode 100644 internal/mobiumdriver/macos_other.go create mode 100644 internal/uitree/parse_ax.go create mode 100644 internal/uitree/parse_ax_test.go diff --git a/README.md b/README.md index ae96e3b3..e903c8c3 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ *Mutatis mutandis.* **Mobile app automation for AI agents and people.** Android emulators, Android -phones, iOS simulators and iPhones — and TVs, Wear OS, Android Automotive and -Meta Quest's 2D app panels — driven through one tool layer from a single Go binary with no runtime -dependencies. +phones, iOS simulators and iPhones — and TVs, Wear OS, Android Automotive, +Meta Quest's 2D app panels and, inside a virtual machine, Mac apps — driven +through one tool layer from a single Go binary with no runtime dependencies. ```sh mobium launch com.example.shop && mobium map && mobium tap @e5 && mobium map @@ -39,7 +39,7 @@ Requirements: - **A prebuilt binary** for macOS, Linux or Windows, amd64 or arm64, from a release — v0.1.0-rc1 is the first, a release candidate - ([SETUP.md](docs/SETUP.md#installing-a-release)) — or **Go 1.24+** to + ([SETUP.md](docs/SETUP.md#installing-a-release)) — or **Go 1.25+** to install it with `go install` - **Android:** platform-tools on `PATH` (or `ANDROID_HOME`, or `MOBIUM_ADB_PATH`), and an emulator or a phone with USB debugging on @@ -173,14 +173,14 @@ are below. The end-to-end flows in [docs/checks/](docs/checks/) each drive a real device and assert on what happened rather than on an exit code. -| | `uiautomator2` | `uiautomator` | `wda` | -| --- | --- | --- | --- | -| platform | Android (default) | Android | iOS simulator and iPhone | -| installs on the device | two APKs, once | nothing | one runner, once | -| `map` on an emulator | 0.04s | 1.96s | — | -| type into an element | yes | no | yes | -| two fingers, drag, double tap | yes | no | yes | -| a screen that never stops moving | fine | cannot read it | fine | +| | `uiautomator2` | `uiautomator` | `wda` | `macos` | +| --- | --- | --- | --- | --- | +| platform | Android (default) | Android | iOS simulator and iPhone | Mac apps, in a VM | +| installs on the device | two APKs, once | nothing | one runner, once | nothing | +| `map` on an emulator | 0.04s | 1.96s | — | — | +| type into an element | yes | no | yes | yes | +| two fingers, drag, double tap | yes | no | yes | not yet | +| a screen that never stops moving | fine | cannot read it | fine | not measured | **Android** uses the [UiAutomator2 server](https://github.com/appium/appium-uiautomator2-server) directly over HTTP, with no Node in between. Pick `--driver uiautomator` when you cannot install anything on the @@ -225,6 +225,16 @@ emulator, where every app is a panel and every panel stays open. Not yet a real headset, and not immersive apps, which publish no accessibility tree ([docs/HORIZON-OS.md](docs/HORIZON-OS.md)). +**Mac apps** are driven through Accessibility, from Go with no cgo, since +2026-11-27 on a SwiftUI app in a macOS 26.6.2 virtual machine +([docs/checks/desktop.sh](docs/checks/desktop.sh)): `map`, taps, typing +read back, a sheet treated as a dialog, and the front window's screenshot. +Mobium refuses to drive a Mac that is not a virtual machine unless +`MOBIUM_DESKTOP_HOST=1` is set, because it moves the real pointer and +keyboard. The process that runs it needs Accessibility and, for screenshots, +Screen Recording. Not yet: scrolling, gestures, menus, Electron apps, or any +app but the check's own ([docs/SETUP.md](docs/SETUP.md#a-mac-in-a-virtual-machine)). + **Windows is not declared supported yet.** Everything that needs no device, the named-pipe daemon transport included, passes in CI on a Windows runner; since 2026-10-22 an Android emulator and a phone have been @@ -371,8 +381,8 @@ JSON so a test harness forces no library version onto the app under test. See ## Drivers for other platforms -Anything Mobium does not drive itself — a TV, a desktop app, a platform nobody -has written yet — is a **driver**: an executable named `mobium-driver-` +Anything Mobium does not drive itself — a Roku, a Windows or Linux desktop +app, a platform nobody has written yet — is a **driver**: an executable named `mobium-driver-` on your `PATH`, in any language, speaking JSON-RPC on stdio. ```sh diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 0d81414e..48faa015 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -10,12 +10,13 @@ The client libraries under `clients/` have no third-party dependencies. | Component | Version | License | Linked on | | --- | --- | --- | --- | -| [Go standard library and runtime](https://go.dev/LICENSE) | Go 1.24+ | BSD-3-Clause | all | +| [Go standard library and runtime](https://go.dev/LICENSE) | Go 1.25+ | BSD-3-Clause | all | | [github.com/spf13/cobra](https://github.com/spf13/cobra) | v1.10.2 | Apache-2.0 | all | | [github.com/spf13/pflag](https://github.com/spf13/pflag) | v1.0.9 | BSD-3-Clause | all | | [github.com/gorilla/websocket](https://github.com/gorilla/websocket) | v1.5.3 | BSD-2-Clause | all | | [github.com/Microsoft/go-winio](https://github.com/microsoft/go-winio) | v0.6.2 | MIT | Windows | -| [golang.org/x/sys](https://cs.opensource.google/go/x/sys) | v0.41.0 | BSD-3-Clause | Windows | +| [golang.org/x/sys](https://cs.opensource.google/go/x/sys) | v0.41.0 | BSD-3-Clause | Windows, macOS | +| [github.com/ebitengine/purego](https://github.com/ebitengine/purego) | v0.11.3 | Apache-2.0 | macOS | | [github.com/inconshreveable/mousetrap](https://github.com/inconshreveable/mousetrap) | v1.1.0 | Apache-2.0 | Windows | Not bundled: [appium-uiautomator2-server](https://github.com/appium/appium-uiautomator2-server) @@ -54,7 +55,7 @@ done --- -## Go standard library and runtime Go 1.24+ +## Go standard library and runtime Go 1.25+ License: BSD-3-Clause @@ -614,3 +615,213 @@ License: Apache-2.0 See the License for the specific language governing permissions and limitations under the License. ``` + +## github.com/ebitengine/purego v0.11.3 + +License: Apache-2.0. Its `internal/fakecgo` is adapted from the Go runtime and +carries the Go authors' BSD-3-Clause notice, reproduced above under the Go +standard library. + +```text + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +``` diff --git a/clients/dotnet/Mobium/Device.cs b/clients/dotnet/Mobium/Device.cs index a1021b28..de7ae798 100644 --- a/clients/dotnet/Mobium/Device.cs +++ b/clients/dotnet/Mobium/Device.cs @@ -1633,8 +1633,9 @@ public DeviceBuilder CallTimeout(TimeSpan timeout) public DeviceBuilder Session(string name) { _session = name ?? ""; return this; } /// - /// The platform for : android or ios. - /// ios picks the wda driver, so none need be named. + /// The platform for : android, ios or + /// macos. ios picks the wda driver and macos the macos + /// driver, so none need be named. /// public DeviceBuilder Platform(string name) { _platform = name ?? ""; return this; } diff --git a/clients/go/mobium.go b/clients/go/mobium.go index 367f1f0a..a346120f 100644 --- a/clients/go/mobium.go +++ b/clients/go/mobium.go @@ -148,8 +148,8 @@ func WithDevice(serial string) Option { return func(s *settings) { s.serial = se // (iOS simulators and iPhones). func WithDriver(name string) Option { return func(s *settings) { s.driver = name } } -// WithPlatform names the platform for Start: "android" or "ios". "ios" picks -// wda, so the driver need not be named. +// WithPlatform names the platform for Start: "android", "ios" or "macos". +// "ios" picks wda and "macos" picks macos, so the driver need not be named. func WithPlatform(name string) Option { return func(s *settings) { s.platform = name } } // WithSession gives this connection a daemon of its own, named name, as diff --git a/clients/java/src/main/java/dev/mobium/Mobium.java b/clients/java/src/main/java/dev/mobium/Mobium.java index 6235243e..f0f3598f 100644 --- a/clients/java/src/main/java/dev/mobium/Mobium.java +++ b/clients/java/src/main/java/dev/mobium/Mobium.java @@ -81,10 +81,11 @@ private Builder() { } private String session; /** - * The platform for {@link #start()}: {@code "android"} or {@code "ios"}. - * {@code "ios"} picks the wda driver, so none need be named. + * The platform for {@link #start()}: {@code "android"}, {@code "ios"} or + * {@code "macos"}. {@code "ios"} picks the wda driver and {@code "macos"} + * the macos driver, so none need be named. * - * @param name {@code "android"} or {@code "ios"} + * @param name {@code "android"}, {@code "ios"} or {@code "macos"} * @return this builder */ public Builder platform(String name) { this.platform = name; return this; } diff --git a/clients/javascript/README.md b/clients/javascript/README.md index f46c87aa..7955f176 100644 --- a/clients/javascript/README.md +++ b/clients/javascript/README.md @@ -28,7 +28,7 @@ simulator or iPhone the same way. - Node.js 18 or later. - **The `mobium` binary**, on your `PATH` or named by `MOBIUM_BIN_PATH`. This - package is a client for it. Install it with Go 1.24+: + package is a client for it. Install it with Go 1.25+: ```sh go install github.com/mobiumdev/mobium/cmd/mobium@latest diff --git a/clients/javascript/index.d.ts b/clients/javascript/index.d.ts index e21c6a99..17bb2865 100644 --- a/clients/javascript/index.d.ts +++ b/clients/javascript/index.d.ts @@ -181,9 +181,9 @@ export interface ConnectOptions { } export interface StartOptions extends ConnectOptions { - /** `"android"` or `"ios"`; `"ios"` picks the wda driver. */ - platform?: 'android' | 'ios' - /** A package name (Android) or bundle id (iOS) to launch fresh once the session is up. */ + /** `"android"`, `"ios"` or `"macos"`; `"ios"` picks the wda driver and `"macos"` the macos driver. */ + platform?: 'android' | 'ios' | 'macos' + /** A package name (Android) or bundle id (iOS, macOS) to launch fresh once the session is up. */ app?: string } diff --git a/clients/javascript/index.js b/clients/javascript/index.js index ec9fce8f..20b822da 100644 --- a/clients/javascript/index.js +++ b/clients/javascript/index.js @@ -237,8 +237,8 @@ function toElements(data) { * Connect and open the session on the device: the device-side server is started now and, given an app, it is launched and * in front when this resolves. End it with `quit()`. * - * `platform` is "android" or "ios"; "ios" picks the wda driver, so none need - * be named. `device`, `driver`, `binary` and `callTimeoutMs` are as for + * `platform` is "android", "ios" or "macos"; "ios" picks the wda driver and + * "macos" the macos driver, so none need be named. `device`, `driver`, `binary` and `callTimeoutMs` are as for * `connect()`. Nothing requires it — every call opens a session on first use — * but it puts the slow first start (installing UiAutomator2, building * WebDriverAgent on an iPhone) where it was asked for. diff --git a/clients/python/README.md b/clients/python/README.md index eda124d6..70db0530 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -26,7 +26,7 @@ with start(platform="android", app="com.android.settings") as device: - Python 3.9 or later. - **The `mobium` binary**, on your `PATH` or named by `MOBIUM_BIN_PATH`. This - package is a client for it. Install it with Go 1.24+: + package is a client for it. Install it with Go 1.25+: ```sh go install github.com/mobiumdev/mobium/cmd/mobium@latest diff --git a/clients/python/mobium/_device.py b/clients/python/mobium/_device.py index a65f099c..7c3042dc 100644 --- a/clients/python/mobium/_device.py +++ b/clients/python/mobium/_device.py @@ -142,10 +142,10 @@ def start( ) -> "Device": """Connect and open the session on the device. - platform: "android" or "ios"; "ios" picks wda, so the driver - need not be named. + platform: "android", "ios" or "macos"; "ios" picks wda and "macos" + picks macos, so the driver need not be named. device: serial or UDID, when more than one is running. - app: a package name (Android) or bundle id (iOS) to launch once the + app: a package name (Android) or bundle id (iOS, macOS) to launch once the session is up; start returns when it is in front. driver, binary, call_timeout, session: as for connect(). diff --git a/cmd/mobium/main.go b/cmd/mobium/main.go index 427fb6c2..d78b7f0f 100644 --- a/cmd/mobium/main.go +++ b/cmd/mobium/main.go @@ -67,7 +67,7 @@ func main() { "Target device serial or UDID (default: the only running device — an Android one, when any is connected)") root.PersistentFlags().StringVar(&backendName, "driver", "", "Driver: uiautomator2 (default, Android), uiautomator (Android, installs nothing), "+ - "wda (WebDriverAgent: iOS simulators and iPhones), or the name of a third-party driver "+ + "wda (WebDriverAgent: iOS simulators and iPhones), macos (apps on this Mac), or the name of a third-party driver "+ "installed as mobium-driver-") root.PersistentFlags().BoolVar(&jsonOutput, "json", false, "Emit JSON instead of text") root.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Log what mobium is doing to stderr") diff --git a/cmd/mobium/session.go b/cmd/mobium/session.go index 2d291eda..ed61fd2c 100644 --- a/cmd/mobium/session.go +++ b/cmd/mobium/session.go @@ -45,7 +45,7 @@ func newSessionCmd() *cobra.Command { return runTool("app_session", call) }, } - cmd.Flags().String("platform", "", `"android" or "ios"; with start, "ios" picks wda`) + cmd.Flags().String("platform", "", `"android", "ios" or "macos"; with start, "ios" picks wda and "macos" picks macos`) cmd.Flags().String("app", "", "with start: a package name or bundle id to launch once the session is up") return cmd } diff --git a/docs/APP-TYPES.md b/docs/APP-TYPES.md index c73f5827..53aaad0b 100644 --- a/docs/APP-TYPES.md +++ b/docs/APP-TYPES.md @@ -30,6 +30,7 @@ it was driven once, with the result written down below, and nothing re-runs it. | Type | Driven | Where | | --- | --- | --- | | Native | Android: Settings, Calculator, Clock, Wikipedia, F-Droid, Aegis, and Seal (Jetpack Compose). iOS: Settings; Wikipedia from the App Store on an iPhone; NetNewsWire, Ice Cubes (SwiftUI), Pocket Casts and Kiwix on a simulator and an iPhone | checked in — most of [checks/](checks/); `third-party-app.sh`, `compose-app.sh`, `third-party-app-ios.sh`, `netnewswire-ios.sh`, `icecubes-ios.sh`, `pocketcasts-ios.sh` and `kiwix-ios.sh` for the apps nobody at Google or Apple wrote | +| | macOS: MobiumDesk, a SwiftUI app, in a macOS 26.6.2 virtual machine; TextEdit read, not driven | checked in — `desktop.sh` ([SETUP](SETUP.md#a-mac-in-a-virtual-machine)) | | Hybrid | Wikipedia's articles, and MobiumApp's WebView screens, on both platforms and on real phones | checked in — `third-party-app.sh`, `mobium-app.sh`, `web-type.sh`, `web-actionability.sh`, `web-storage.sh` | | Mobile web | Safari on iOS; Chrome on Android, emulator and the Pixel 8 Pro | checked in — `chrome.sh` (read, a tap counted by the page, a link followed), `ios-webview.sh`, `orientation.sh`, `shake.sh` | | Progressive web app | Squoosh, installed to the home screen on both platforms, and as a WebAPK on the Pixel 8 Pro; OYO Lite, a Trusted Web Activity from the Play Store, on the Pixel 8 Pro | checked in — `pwa.sh`: installed if absent, launched, standalone, and a tap counted by the page — or, on an emulator's shortcut, refused with the reason; `twa.sh`: a Play Store PWA launched, tapped, and backed through | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index dcf82e93..4cd9c51b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -48,10 +48,11 @@ flowchart TB uia2["uiautomator2
Android default"] dump["uiautomator
Android, installs nothing"] wda["wda
iOS simulator and iPhone"] + mac["macos
apps on this Mac, in a VM"] ext["external driver
mobium-driver-NAME"] end - tools --> uia2 & dump & wda & ext + tools --> uia2 & dump & wda & mac & ext subgraph devicepkg["internal/device — finding and readying devices"] adb["adb"] @@ -65,7 +66,8 @@ flowchart TB dump -- "uiautomator dump" --> adb wda -- "HTTP" --> wdarunner["WebDriverAgent runner
on the simulator or phone"] wda --> simctl & devicectl - ext -- "JSON-RPC on stdio" --> other["any platform:
a TV, a desktop app, …"] + mac -- "Accessibility · Quartz events, through purego" --> macapps["the Mac's own apps"] + ext -- "JSON-RPC on stdio" --> other["any platform:
a Roku, a Windows app, …"] web -- "Android: devtools socket" --> adb web -- "iPhone: com.apple.webinspector" --> lockdown ``` diff --git a/docs/CHALLENGES.md b/docs/CHALLENGES.md index 361901af..355961a4 100644 --- a/docs/CHALLENGES.md +++ b/docs/CHALLENGES.md @@ -7,7 +7,7 @@ the source. The pattern across them is the reason the document exists: **almost nothing here was found by reading code or by a test written from imagination.** Of -410 defects, 328 were found only by running against a real device. Eighteen +417 defects, 335 were found only by running against a real device. Eighteen more — 255, 280, 282, 327, 329, 353, 355, 356, 359, 371, 375, 380, 382, 384, 386, 387, 388 and 406 — were met while running against one, though the fault lay in a check, the host or Mobium's own design rather than in the platform. The other sixty-two — 4, 5, 6, 14, 23, @@ -8927,6 +8927,92 @@ speakers. The Linux and headless commands in `SETUP.md` passed `-no-snapshot-save`, which 186 there warns brings an old snapshot back; they pass `-no-snapshot-load` and `-no-audio`, as `mobium boot` does. +### 411. The app in front of a Mac could not be asked for + +**Found by:** running `map` through the daemon in a macOS 26.6.2 virtual +machine. `AXFocusedApplication` on the system-wide element failed with +kAXErrorCannotComplete (-25204), in the daemon and in a fresh Swift script +alike. `NSWorkspace`'s `frontmostApplication` answered, but only a process +with a run loop keeps it current, and the daemon has none. + +**Fixed:** the app in front is the owner of the frontmost window in Quartz's +window list, which is ordered front to back. Across six switches between +three apps it agreed with `lsappinfo front` every time. + +### 412. ⌘A left Command held, and typing became shortcuts + +**Found by:** `fill` reading back an empty field in the virtual machine after +it had worked. The system's modifier state showed Command down (flags +0x20100000) with no key held. Select-all was one key event carrying the +Command flag. The system took the flag as the key being held, and every +character typed after it arrived as a shortcut. Releasing Command by its +key-up made typing work again. + +**Fixed:** a modifier is pressed and released as a key of its own around the +key it modifies, and typed text carries no modifier flags. `desktop.sh` fills +twice in a row; the second fill fails while a modifier is held. + +### 413. A system alert over a Mac app was not in front + +**Found by:** typing lost while `map` listed the app's fields. An Automation +prompt ("… wants access to control …") was up at window level 8, and the app +in front was taken from level 0 only. The prompt held the keyboard. + +**Fixed:** the app in front owns the frontmost window below the Dock's level. +Measured levels: an app's windows 0, a modal alert 8, the Dock 20, +Notification Center 21, the menu bar 24, its status items 25. `map` then +listed the prompt's buttons, and a tap on Don't Allow answered it. The prompt +came from `osascript` in the test itself (Environment traps). + +### 414. A tap under a Mac sheet was swallowed and reported done + +**Found by:** Sign In tapped and "Signed out" still showing. SwiftUI's +password AutoFill had put a "Passwords Is Locked" sheet over the window. +AppKit reports a sheet inside its window, nested in a zero-size `AXSheet`, +and keeps the rest of the window in the tree with real frames. A click +elsewhere in the window is swallowed while the sheet is up. The hit test +named the app's own window, so nothing refused the tap. + +**Fixed:** an `AXSheet` with a size is a dialog, as an iOS sheet is. A +locator under it is refused, naming it. `map` lists only what is on it, +`app_alert` reads it and presses its buttons by caption, and `app_dialogs` +rules answer it. `desktop.sh` asserts the refused tap is not counted. + +### 415. A Mac field was found again by a path the AutoFill popup had moved + +**Found by:** `fill` focusing an element that was not the field. The driver +found a mapped element again by its child indices. Focusing a password field +adds an AutoFill window to the app's children, and losing focus removes it, +so between the read and the action every index after it moved. + +**Fixed:** an element is found again by its role, its identifier and a point +inside its frame. + +### 416. The first Mac screenshot put a prompt in front of the app + +**Found by:** `app_launch` timing out after a screenshot. `screencapture`, run +by a process without Screen Recording permission, raised "mobium is +requesting to bypass the system private window picker", which stayed in front +of every app until answered. + +**Fixed:** the driver asks `CGPreflightScreenCaptureAccess`, which never +prompts, and refuses the screenshot naming the setting to change. + +### 417. A Mac app that answered no accessibility mapped as an empty screen + +**Found by:** `desktop.sh` failing at its first step, 2 runs in 22. MobiumDesk's +window was up and drawn, and every attribute of its application element, +asked from the probe or from Mobium, failed with kAXErrorAPIDisabled +(-25211). TextEdit answered at the same moment, and MobiumDesk answered +again once relaunched. Why that launch did not answer is not known. `map` +said "No actionable elements found", which reads as a screen with nothing +on it. + +**Fixed:** the driver asks the application element for its role before +reading the tree, and refuses with the AXError, naming the app and the +remedy of relaunching it. The refusal has not yet been seen on a device: no +run since has reproduced the launch. + ## Findings that were not defects Worth recording because each one closed off an approach that looked obvious. @@ -9387,4 +9473,13 @@ its cause. fails on any other missing prompt. A real iPhone is not measured: its clipboard cannot be seeded from outside, and the step is skipped there. +- **Overwriting a binary in place on macOS gets it killed.** Copying a new + `mobium` over the old file in a macOS virtual machine made the next launch + exit 137: the kernel's cached code signature no longer matched, and the + crash report said "Code Signature Invalid". Remove the file, then copy. +- **`osascript` driving another app over SSH waits for a prompt nobody sees.** + "sshd-keygen-wrapper wants access to control TextEdit" came up on the + virtual machine's screen, `osascript` waited on it with no timeout, and the + prompt took the keyboard (413). `desktop.sh` sends no Apple Events. + --- diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 3b8ca347..0f047187 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -22,7 +22,8 @@ Every command here was run from a fresh clone of `main`: `make build`, | For | You need | CI uses | | --- | --- | --- | -| the binary and the Go client | Go 1.24 or later | the version in `go.mod` | +| the binary | Go 1.25 or later | the version in `go.mod` | +| the Go client | Go 1.24 or later | the version in `clients/go/go.mod` | | linting | golangci-lint 2.13.2 — `make lint-install` fetches it and checks its checksum | the same | | the JavaScript client | Node.js 18 or later | 22 | | the Python client | Python 3.9 or later | the runner's | diff --git a/docs/RELEASE-CHECKLIST.md b/docs/RELEASE-CHECKLIST.md index 04e688da..c42a5174 100644 --- a/docs/RELEASE-CHECKLIST.md +++ b/docs/RELEASE-CHECKLIST.md @@ -4,7 +4,7 @@ [CI workflow](../.github/workflows/ci.yml) runs on every push — formatting, vet, both modules' tests, the four non-Go clients' own tests, and six cross-compile targets. This file is the rest, and the rest is where most -serious defects in this project have come from: 328 of 410 were found only by +serious defects in this project have come from: 335 of 417 were found only by running against a real device. Work through it before tagging a release, on three substrates: an Android diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 616044b8..a368a01f 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -6,6 +6,25 @@ this is what is not. ## Next +- **Desktop apps.** The `macos` driver drives a SwiftUI app in a macOS + virtual machine since 2026-11-27 (`desktop.sh`, CHALLENGES 411–417). In + order, what is left: + 1. Scrolling and `scroll-to`. A row out of view is hidden and cannot yet + be brought into view. + 2. Menus: the menu bar's items are mapped, but an open menu has not been + driven, nor a context menu, right-click, hover or a shortcut. + 3. Electron apps, through the CDP path WebViews use: launch with a + debugging port, read over CDP, click natively. + 4. A third-party native app and a third-party Electron app. + 5. Gestures: drag, double click, scroll wheel. Refused until built. + 6. `doctor` naming the Accessibility and Screen Recording grants. + 7. Windows, through UI Automation, on the Windows laptop and the ARM VM. + Unexplained, each seen and not reproduced: in the probe before the driver, + the first three clicks of a session landed nowhere (15 later clicks all + did); a launch of MobiumDesk answered no accessibility (417, twice); and the + daemon closed a connection without answering, twice, not reproduced in + five restarts under a foreground daemon or three redeploys. + - **Found reviewing the docs evaluation's golden set** (written down 2026-10-12, read from the code, not yet run on a device): 1. ~~**On an Apple TV, a dialog of three or more buttons named a remedy diff --git a/docs/SETUP.md b/docs/SETUP.md index b5f1b1a3..edb8daf0 100644 --- a/docs/SETUP.md +++ b/docs/SETUP.md @@ -33,6 +33,7 @@ no Xcode on a machine doing Android work is normal, not a problem. - [Android real device](#android-real-device) - [iOS simulator](#ios-simulator) — and [an Apple TV simulator](#an-apple-tv-simulator) - [iOS real device](#ios-real-device) — native screens, WebViews and Safari +- [A Mac in a virtual machine](#a-mac-in-a-virtual-machine) — Mac apps - [Parallel runs](#parallel-runs) — one daemon for each - [Driving another machine's devices](#driving-another-machines-devices) — `--remote`, and a grid - [What Mobium installs, and removing it](#what-mobium-installs-and-removing-it) @@ -685,6 +686,50 @@ such warning, so after one, a slow first read is that and not a hang. --- +## A Mac in a virtual machine + +Mobium drives the apps of the Mac it runs on, through Accessibility. That +moves the real pointer and types on the real keyboard, so it refuses a Mac +that is not a virtual machine unless `MOBIUM_DESKTOP_HOST=1` is set. +`mobium devices` lists the Mac as `macos`: `ready`, `refused` or +`no accessibility`. + +Verified on 2026-11-27 with [Tart](https://tart.run) 2.42.0 on an M4 Pro +running macOS 26.7.3, and a macOS 26.6.2 guest. A guest MUST be no newer than +its host. + +```sh +brew trust --formula openai/tools/tart +brew trust --formula openai/tools/softnet +brew install openai/tools/tart +tart clone ghcr.io/cirruslabs/macos-tahoe-base:latest mobium-desktop +tart set mobium-desktop --disk-size 100 --memory 16384 --cpu 6 +tart run --no-graphics mobium-desktop & +ssh admin@$(tart ip --wait 120 mobium-desktop) # password: admin +``` + +Inside the guest: + +- **Accessibility** for the process that runs `mobium`. The base image + already grants it to `sshd-keygen-wrapper`, so `mobium` started over SSH + has it. Otherwise: System Settings > Privacy & Security > Accessibility. +- **Screen Recording**, for `screenshot` only. Without it the screenshot is + refused, naming the setting; Mobium does not ask, because the prompt would + take the front of the screen (CHALLENGES 416). Run the guest with a window + (`tart run mobium-desktop`) to change the setting. +- **Xcode or its command-line tools**, for `swiftc`, only to build the app + [checks/desktop.sh](checks/desktop.sh) drives. A copy of the host's + `Xcode.app` works when the guest meets its minimum macOS. + +The guest's disk is 50 GB until `tart set --disk-size` grows it; then grow +the container inside: `sudo diskutil apfs resizeContainer disk0s2 0`. + +Copy a new `mobium` into the guest by removing the old file first. A file +overwritten in place is killed at launch (Environment traps in +[CHALLENGES](CHALLENGES.md)). Do not script other apps with `osascript` over +SSH: macOS answers with a permission prompt nobody sees, and it takes the +keyboard (CHALLENGES 413). + ## Parallel runs **Give each run that drives a device at the same time as another its own diff --git a/docs/WINDOWS.md b/docs/WINDOWS.md index ef4208f5..6b524c1c 100644 --- a/docs/WINDOWS.md +++ b/docs/WINDOWS.md @@ -194,8 +194,7 @@ starting point, not a complete inventory. A named pipe through `github.com/Microsoft/go-winio`, as Vibium does it. It adds the project's second and third dependencies after `gorilla/websocket`: go-winio and `golang.org/x/sys`, both pure Go, so the single-binary property -survives. `x/sys` is held at v0.41.0, the last release that asks for Go 1.24; -anything newer raises the module's `go` line. +survives. `x/sys` is at v0.41.0. Three things differ from the sketch this document used to carry: @@ -368,7 +367,7 @@ emulator, so it is not a substitute. ```powershell winget install GoLang.Go Git.Git -go version # needs 1.24+ +go version # needs 1.25+ ``` ### 2. Android diff --git a/docs/checks/README.md b/docs/checks/README.md index 8ef86ba7..aff6d57a 100644 --- a/docs/checks/README.md +++ b/docs/checks/README.md @@ -66,6 +66,7 @@ checks do not: `clean-stop.sh`, which stops the caller's daemon, and | [tv-app.sh](tv-app.sh) | **A TV app driven with a remote** — mobium-app's `tv/` app, MobiumTV — on any Android device: a D-pad press says where focus went and the app agrees; select and a tap arrive as select and as touch; a tap on a tile that opens on focus reaches it as focus, not a click; nine presses right scroll a row to Card 10; `app_alert` sees a dialog, accept is its positive button and back cancels it; play-pause, fast-forward and stop arrive as the app counts them. Passed 2026-10-08 on the Android TV emulator (API 34) and on a Fire TV (Fire OS 7.7.1.7) over Wi-Fi, in 2 minutes 9 seconds; the TV found that a read can land before the screen it expects, so every screen and line is waited for | | [wear-os.sh](wear-os.sh) | **A watch** — Wear OS's own Settings, by locator: `text="Gestures"` is one match though a chip repeats its title's text; map lists a toggle chip's switch once, not three times; `app_alert` reads Wear's ✓/✕ dialog, dismiss leaves Tilt-to-wake off and accept presses OK; swiping right goes back. Refuses anything that is not a watch. Passed 2026-10-13 three times in three on a Wear OS 5.1 emulator (API 35, round 454×454), about 20 seconds; on `main` it failed at its first tap (CHALLENGES 315–317) | | [automotive.sh](automotive.sh) | **A car** — Android Automotive, its screen of system bars, app and keyboard windows, its apps run as user 10: `map` lists the bars and the launcher; a tap in the bottom bar moves the temperature, read back and put back, pressed again if the car drops the press; an untargeted swipe; each app tile mapped once and car-ui's marker not read as text; `devices` says car bars and a back gesture is refused; the car's back button mapped, and a tap on it goes back; letterboxed MobiumApp is the app in front and no dialog; `app_alert` quotes the app's dialog from its own words, not the instrument cluster, and the car's permission prompt by its named buttons, `dismiss` refused and `--button` pressing; with the keyboard up no key is mapped and nothing reads as a dialog; `grant`, `logs --app` and `clear-data` act for user 10, each read back from the device or the app. Refuses anything that is not a car, or a car in front for user 0. Passed 2026-11-11 on the Android Automotive 15 emulator (1024×768); on `main` it failed at its first step (CHALLENGES 393–404) | +| [desktop.sh](desktop.sh) | **A Mac** — the `macos` driver, inside a macOS virtual machine, on MobiumDesk ([desktop-app.swift](desktop-app.swift), built with `swiftc`): `map` lists the login and the window's own buttons and no row the list has scrolled out of view; two taps counted by the app; `fill` read back, a password by its caret, a wrong password refused by the app and the right one signing in after a second fill; under a sheet a tap refused naming it and not counted, `app_alert` reading and answering it, and a dialog rule answering it on the way; the front window's screenshot. Takes `macos`. Passed 2026-11-27 on a macOS 26.6.2 guest, about 15 seconds: 20 runs in 22, and the last 8 in 8 as committed; the two failures were a launch of the app that answered no accessibility (CHALLENGES 417) | | [twa.sh](twa.sh) | **A PWA from the Play Store** — a Trusted Web Activity, OYO Lite by default, installed by hand — on an Android phone: checked to be a TWA by its task, `launch` saying so, its page attached by the site's host and standalone, a tap counted by the page, and back through a tapped link's history and then out, each naming the app. Passed on the Pixel 8 Pro on 2026-10-01 ([CHALLENGES 205](../CHALLENGES.md)) | | [chrome.sh](chrome.sh) | **A page in Chrome on Android**, on an emulator or a phone, with the network: listed by its title and URL, `text`, `eval` and `map` answered by the page, a tap on a ref counted by a button put on the page, and the page's own link followed to iana.org. On an emulator it starts Chrome fresh first ([CHALLENGES 200](../CHALLENGES.md)); on a phone it leaves Chrome running, prints no listing, and closes its tab | | [pwa.sh](pwa.sh) | **A progressive web app**, Squoosh, on an emulator, an Android phone or a simulator, with the network: installed through Chrome's menu or Safari's share sheet when its icon is absent, launched from the icon, running standalone with an active service worker, its context found by its start URL. iOS: a tap in the web context, placed from text the page and the native tree both report, and one from `NATIVE_APP`, each counted by the page ([CHALLENGES 248, 290](../CHALLENGES.md)). Android phone: installed as a WebAPK, launched by its package with `app_launch` saying so ([CHALLENGES 202](../CHALLENGES.md)), the tap counted by the page, and the WebAPK and the tabs removed afterwards. Emulator: the tap counted, or refused because Chrome stopped reporting its WebView and the page counted nothing ([CHALLENGES 200](../CHALLENGES.md)). An iPhone refused | diff --git a/docs/checks/desktop-app.swift b/docs/checks/desktop-app.swift new file mode 100644 index 00000000..48d5ac37 --- /dev/null +++ b/docs/checks/desktop-app.swift @@ -0,0 +1,53 @@ +// MobiumDesk: the macOS app desktop.sh drives. A login (mobium / hunter2), +// a counter, a sheet, a 40-row list and a menu command. desktop.sh builds it +// with swiftc; it needs no Xcode project. +import SwiftUI + +@main +struct MobiumDesk: App { + @State private var count = 0 + var body: some Scene { + WindowGroup("MobiumDesk") { + Root(count: $count) + .frame(minWidth: 480, minHeight: 420) + } + .commands { + CommandMenu("Probe") { + Button("Reset Counter") { count = 0 }.keyboardShortcut("r", modifiers: [.command, .shift]) + } + } + } +} + +struct Root: View { + @Binding var count: Int + @State private var user = "" + @State private var pass = "" + @State private var status = "Signed out" + @State private var showSheet = false + var body: some View { + VStack(alignment: .leading, spacing: 10) { + TextField("Username", text: $user).accessibilityIdentifier("username") + SecureField("Password", text: $pass).accessibilityIdentifier("password") + Button("Sign In") { + status = (user == "mobium" && pass == "hunter2") ? "Signed in as \(user)" : "Wrong username or password" + }.accessibilityIdentifier("signin") + Text(status).accessibilityIdentifier("status") + Button("Show Sheet") { showSheet = true }.accessibilityIdentifier("show-sheet") + HStack { + Button("Increment") { count += 1 }.accessibilityIdentifier("increment") + Text("Count: \(count)").accessibilityIdentifier("count") + } + List(1...40, id: \.self) { i in + Text("Row \(i)").accessibilityIdentifier("row-\(i)") + }.accessibilityIdentifier("rows") + } + .padding() + .sheet(isPresented: $showSheet) { + VStack(spacing: 12) { + Text("A sheet").accessibilityIdentifier("sheet-title") + Button("Dismiss") { showSheet = false }.accessibilityIdentifier("dismiss") + }.padding(40) + } + } +} diff --git a/docs/checks/desktop.sh b/docs/checks/desktop.sh new file mode 100755 index 00000000..aef6da77 --- /dev/null +++ b/docs/checks/desktop.sh @@ -0,0 +1,112 @@ +#!/bin/sh +# macOS: the macos driver on a SwiftUI app, inside a macOS virtual machine. +# +# Builds MobiumDesk (desktop-app.swift) with swiftc, then drives it through +# every path the driver adds. Each step has its control: +# - map lists the login and the window's own buttons, and not a row the +# list has scrolled out of view; +# - a tap is counted by the app, twice; +# - fill is read back, and a password by its caret; a second fill after +# the first proves no modifier was left held (CHALLENGES 412); +# - a wrong password is refused by the app before the right one passes; +# - under a sheet a tap is refused and the counter does not move, then +# app_alert and a dialog rule answer it (CHALLENGES 414); +# - a screenshot is the window's PNG. +# +# The Mac MUST be a virtual machine, or MOBIUM_DESKTOP_HOST=1 must be set: +# this moves the real pointer and types on the real keyboard. +# +# docs/checks/desktop.sh macos +set -e +DEV="$1" +if [ -z "$DEV" ]; then echo "usage: $0 macos" >&2; exit 2; fi +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +. "$ROOT/docs/checks/lib.sh" +check_platform macos "$DEV" +check_lock "$DEV" +M="$ROOT/bin/mobium --device $DEV" +APP=dev.mobium.desk + +fail() { echo "FAIL: $*" >&2; exit 1; } +row() { printf " %-10s ok — %s\n" "$1" "$2"; } +count() { $M text | sed -n 's/^Count: //p'; } + +WORK="$CHECK_TMP" +BUNDLE="$WORK/MobiumDesk.app" +mkdir -p "$BUNDLE/Contents/MacOS" +swiftc -O -parse-as-library -o "$BUNDLE/Contents/MacOS/MobiumDesk" "$ROOT/docs/checks/desktop-app.swift" +cat > "$BUNDLE/Contents/Info.plist" < + + +CFBundleIdentifier$APP +CFBundleNameMobiumDesk +CFBundleExecutableMobiumDesk +CFBundlePackageTypeAPPL +NSPrincipalClassNSApplication + +EOF +codesign -s - --force "$BUNDLE" 2>/dev/null + +echo "--- $DEV" +$M terminate $APP >/dev/null 2>&1 || true +# The first open registers the bundle, so app_launch can find it by id. +open "$BUNDLE" +$M wait 'testid=username' --timeout 15s >/dev/null || fail "MobiumDesk did not show its login: +$($M map 2>&1)" + +out=$($M map) || fail "map: $out" +for want in "Username (input" "password (password" "Sign In (button)" "Close (button)" "Row 1 (button)"; do + echo "$out" | grep -qF "$want" || fail "map has no \"$want\": +$out" +done +echo "$out" | grep -qF "Row 30" && fail "map lists Row 30, which the list has not scrolled to: +$out" +row "map" "the login, the window's buttons, rows in view and none out of it" + +before=$(count) +[ -n "$before" ] || fail "no count to compare" +$M tap testid=increment >/dev/null +$M tap testid=increment >/dev/null +[ "$(count)" = "$((before + 2))" ] || fail "two taps on Increment moved Count from $before to $(count)" +row "tap" "two taps, counted by the app" + +$M fill testid=username mobium >/dev/null || fail "fill username was not confirmed" +$M fill testid=password wrong >/dev/null || fail "fill password was not confirmed" +$M tap 'label=Sign In,role=button' >/dev/null +$M wait 'text=Wrong username or password' --timeout 5s >/dev/null || fail "a wrong password was not refused by the app" +$M fill testid=password hunter2 >/dev/null || fail "a second fill of the password was not confirmed" +$M tap 'label=Sign In,role=button' >/dev/null +$M wait 'text=Signed in as mobium' --timeout 5s >/dev/null || fail "the right password did not sign in" +row "fill" "read back, the password by its caret; wrong refused, right signed in" + +# While the sheet is up, text reads only the sheet, so the count is read +# before it opens and after it closes. +before=$(count) +[ -n "$before" ] || fail "no count to compare" +$M tap testid=show-sheet >/dev/null +$M wait 'testid=dismiss' --timeout 5s >/dev/null || fail "the sheet did not open" +if out=$($M tap testid=increment 2>&1); then fail "a tap under the sheet was not refused: $out"; fi +echo "$out" | grep -qF '"A sheet"' || fail "the refusal does not name the sheet: $out" +$M alert | grep -qF '"Dismiss"' || fail "app_alert does not list the sheet's Dismiss" +$M alert --button Dismiss >/dev/null || fail "app_alert could not press Dismiss" +$M alert | grep -qF "no dialog" || fail "the sheet is still up after Dismiss" +[ "$(count)" = "$before" ] || fail "a refused tap moved Count from $before to $(count)" +row "sheet" "a tap under it refused and not counted; app_alert read and answered it" + +before=$(count) +$M tap testid=show-sheet >/dev/null +$M wait 'testid=dismiss' --timeout 5s >/dev/null || fail "the sheet did not open again" +$M dialogs --when "A sheet" --press Dismiss >/dev/null +out=$($M tap testid=increment) || fail "the rule did not clear the way: $out" +$M dialogs --clear >/dev/null +echo "$out" | grep -qF 'pressed "Dismiss"' || fail "the tap does not say the rule answered: $out" +[ "$(count)" = "$((before + 1))" ] || fail "the tap after the rule moved Count from $before to $(count)" +row "rule" "a dialog rule answered the sheet on the way, and the tap counted" + +$M screenshot -o "$WORK/shot.png" >/dev/null || fail "screenshot was refused" +file "$WORK/shot.png" | grep -q "PNG image data" || fail "the screenshot is not a PNG" +row "shot" "the window, as a PNG" + +$M terminate $APP >/dev/null || fail "terminate was refused" +echo "PASS" diff --git a/docs/checks/lib.sh b/docs/checks/lib.sh index a8e858a4..8c9219f4 100644 --- a/docs/checks/lib.sh +++ b/docs/checks/lib.sh @@ -149,10 +149,15 @@ kill_matching() { check_platform() { case "$2" in ????????-????????????????|*-*-*-*-*) _check_kind=ios ;; + macos) _check_kind=macos ;; *) _check_kind=android ;; esac [ "$_check_kind" = "$1" ] && return 0 - if [ "$1" = ios ]; then _check_want="an iOS device"; else _check_want="an Android device"; fi + case "$1" in + ios) _check_want="an iOS device" ;; + macos) _check_want="this Mac (macos)" ;; + *) _check_want="an Android device" ;; + esac echo "$(basename "$0") is for $_check_want, and $2 is not one" >&2 exit 2 } diff --git a/docs/quickstart/README.md b/docs/quickstart/README.md index 971c156b..104c0172 100644 --- a/docs/quickstart/README.md +++ b/docs/quickstart/README.md @@ -62,7 +62,7 @@ On macOS, download with `curl`, not a browser: the binaries are not notarized, and macOS blocks one a browser saved. [SETUP.md](../SETUP.md#installing-a-release) has that in full, and Windows. -Or install it with **Go 1.24 or later** ([go.dev/dl](https://go.dev/dl/)): +Or install it with **Go 1.25 or later** ([go.dev/dl](https://go.dev/dl/)): ```sh go install github.com/mobiumdev/mobium/cmd/mobium@latest diff --git a/go.mod b/go.mod index b522db33..281b6f58 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/mobiumdev/mobium -go 1.24.0 +go 1.25.0 require ( github.com/Microsoft/go-winio v0.6.2 @@ -13,6 +13,7 @@ require ( require ( github.com/bahlo/generic-list-go v0.2.0 // indirect github.com/buger/jsonparser v1.1.2 // indirect + github.com/ebitengine/purego v0.11.3 // indirect github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect diff --git a/go.sum b/go.sum index a62d48a2..fb5140a8 100644 --- a/go.sum +++ b/go.sum @@ -45,6 +45,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/ebitengine/purego v0.11.3 h1:OB+JLpdm7ioymhyA+6s5kbb/uOuYycAgL8NNTFc5MLg= +github.com/ebitengine/purego v0.11.3/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= diff --git a/internal/agent/backend.go b/internal/agent/backend.go index cf1e2058..31992cd8 100644 --- a/internal/agent/backend.go +++ b/internal/agent/backend.go @@ -27,6 +27,8 @@ const ( BackendDump Backend = "uiautomator" // BackendWDA is WebDriverAgent on an iOS simulator or a real iPhone. BackendWDA Backend = "wda" + // BackendMac is Accessibility on the Mac mobium runs on. + BackendMac Backend = "macos" ) // DefaultBackend is UiAutomator2, on the same reasoning as vibium downloading @@ -37,7 +39,7 @@ const DefaultBackend = BackendUIA2 // builtinBackends is every backend compiled into this binary. Any other name // is looked for on PATH as `mobium-driver-`, which is how a third party // adds a platform without forking — see examples/drivers/PROTOCOL.md. -var builtinBackends = []Backend{BackendUIA2, BackendDump, BackendWDA} +var builtinBackends = []Backend{BackendUIA2, BackendDump, BackendWDA, BackendMac} // ParseBackend validates a backend name. // @@ -71,8 +73,8 @@ func ParseBackend(s string) (Backend, error) { return "", mobiumerr.New(mobiumerr.InvalidArgument, "the iOS driver is called %q (WebDriverAgent)", BackendWDA) } if strings.ContainsAny(string(name), " /\\") { - return "", mobiumerr.New(mobiumerr.InvalidArgument, "%q is not a driver name (want %q, %q, %q, or the name of a "+ - "driver installed as mobium-driver-)", s, BackendUIA2, BackendDump, BackendWDA) + return "", mobiumerr.New(mobiumerr.InvalidArgument, "%q is not a driver name (want %q, %q, %q, %q, or the name of a "+ + "driver installed as mobium-driver-)", s, BackendUIA2, BackendDump, BackendWDA, BackendMac) } return name, nil } @@ -344,6 +346,9 @@ func (h *Handlers) resolveSession(ctx context.Context, args map[string]interface s, err := h.iosSessionFor(ctx, serial) return s, onOtherPlatform(ctx, serial, err, false) } + if backend == BackendMac || serial == macSerial { + return h.macSessionFor(ctx) + } if !backend.isBuiltin() { // Before adb: an external driver may be for a platform adb has never // heard of, and requiring a connected Android device to use one would @@ -362,8 +367,16 @@ func (h *Handlers) resolveSession(ctx context.Context, args map[string]interface return h.iosSessionFor(ctx, serial) } if s, ok, ierr := h.onlyIOS(ctx, args, serial, err); ok { + if mobiumerr.CodeOf(ierr) == mobiumerr.NoDevice { + if ms, mok, merr := h.onlyMac(ctx, args, serial); mok { + return ms, merr + } + } return s, ierr } + if ms, mok, merr := h.onlyMac(ctx, args, serial); mok { + return ms, merr + } return nil, onOtherPlatform(ctx, serial, err, true) } @@ -493,6 +506,27 @@ func (h *Handlers) externalSessionFor(ctx context.Context, backend Backend, ref return s, nil } +// macSerial is the device name of the Mac mobium runs on. +const macSerial = "macos" + +// macSessionFor opens the session for this Mac's apps. +func (h *Handlers) macSessionFor(ctx context.Context) (*session, error) { + if s, ok := h.sessions[macSerial]; ok && s.healthy(ctx) { + return s, nil + } + d := mobiumdriver.NewMac() + if err := d.Start(ctx, h.progress); err != nil { + return nil, err + } + s := &session{ + dev: &device.Device{Serial: macSerial, Model: "Mac"}, + driver: d, + backend: BackendMac, + } + h.adopt(macSerial, s) + return s, nil +} + // closeSessions tears down every cached driver. func (h *Handlers) closeSessions() { for serial, s := range h.sessions { @@ -599,6 +633,25 @@ func (h *Handlers) onlyIOS(ctx context.Context, args map[string]interface{}, ser } } +// onlyMac opens this Mac's session when nothing was named and the Mac is the +// only device: in a macOS virtual machine there is no adb and no simulator. +func (h *Handlers) onlyMac(ctx context.Context, args map[string]interface{}, serial string) (*session, bool, error) { + if serial != "" || stringArg(args, "driver") != "" || h.backend != DefaultBackend || runtime.GOOS != "darwin" { + return nil, false, nil + } + if state, _ := macState(); state != "ready" { + return nil, false, nil + } + if _, err := selectIOSDevice(ctx, ""); mobiumerr.CodeOf(err) != mobiumerr.NoDevice { + return nil, false, nil + } + s, err := h.macSessionFor(ctx) + return s, true, err +} + +// macState is mobiumdriver.MacState, replaceable in tests. +var macState = mobiumdriver.MacState + // selectIOSDevice is device.SelectIOS, replaceable in tests, which have no // simulators or phones to list. var selectIOSDevice = device.SelectIOS diff --git a/internal/agent/handlers.go b/internal/agent/handlers.go index 8c421cfb..0af81d63 100644 --- a/internal/agent/handlers.go +++ b/internal/agent/handlers.go @@ -652,6 +652,14 @@ func (h *Handlers) devices(ctx context.Context) (*ToolsCallResult, error) { Model: p.Model, Runtime: "iOS " + p.OSVersion, }) } + if state, ok := macState(); ok { + note := "this Mac, driven through Accessibility" + if state == "refused" { + note = "this Mac is not a virtual machine; set " + mobiumdriver.HostOptIn + "=1 to drive it" + } + lines = append(lines, fmt.Sprintf("%-38s %-10s (macos, %s)", macSerial, state, note)) + view.Devices = append(view.Devices, DeviceView{ID: macSerial, Platform: "macos", State: state, Model: "Mac"}) + } view.Notes = notes if len(lines) == 0 { @@ -1372,6 +1380,15 @@ func dialogOver(dialog string, loc uitree.Locator, covered bool) error { WithDetail("dialog", dialog) } +// dialogName is what a dialog is called in a refusal: its label, or its first +// words when it has none, as a Mac sheet does not. +func dialogName(d *uitree.Node) string { + if d.Label != "" { + return d.Label + } + return strings.SplitN(uitree.DialogWords(d), "\n", 2)[0] +} + // screenOver refuses a target on a screen of the app that another screen is // in front of. There is no dialog to answer, so the remedy is what closes // the screen in front: one of its own controls, which map lists — or, for @@ -1605,7 +1622,7 @@ func pickOne(loc uitree.Locator, tree *uitree.Tree) (*uitree.Node, error) { // for: the tap lands on the dialog. iOS keeps the covered screen in // the tree, so this is the only way a locator finds out. if d := tree.Dialog(); d != nil && !matches[0].Within(d) { - return nil, dialogOver(d.Label, loc, true) + return nil, dialogOver(dialogName(d), loc, true) } // The keyboard is the same case one layer over: on iOS what it covers // stays in the tree, marked not visible, and a locator resolved it — diff --git a/internal/agent/schema.go b/internal/agent/schema.go index 2e47189e..aa9c1546 100644 --- a/internal/agent/schema.go +++ b/internal/agent/schema.go @@ -1495,9 +1495,9 @@ func GetToolSchemas() []Tool { }, "platform": map[string]interface{}{ "type": "string", - "description": "\"android\" or \"ios\". With start, \"ios\" picks " + - "wda, so a driver need not be named.", - "enum": []string{"android", "ios"}, + "description": "\"android\", \"ios\" or \"macos\". With start, \"ios\" picks " + + "wda and \"macos\" picks macos, so a driver need not be named.", + "enum": []string{"android", "ios", "macos"}, }, "app": map[string]interface{}{ "type": "string", diff --git a/internal/agent/session.go b/internal/agent/session.go index ef9c5bcd..98c4ed7c 100644 --- a/internal/agent/session.go +++ b/internal/agent/session.go @@ -90,6 +90,13 @@ func platformBackend(args map[string]interface{}) (map[string]interface{}, error return nil, mobiumerr.New(mobiumerr.InvalidArgument, "platform \"ios\" and driver %q disagree: %s drives Android", backend, backend) } + case "macos": + if backend == "" { + out["driver"] = string(BackendMac) + } else if Backend(backend) != BackendMac { + return nil, mobiumerr.New(mobiumerr.InvalidArgument, + "platform \"macos\" and driver %q disagree: the macOS driver is %q", backend, BackendMac) + } case "android": if Backend(backend) == BackendWDA { return nil, mobiumerr.New(mobiumerr.InvalidArgument, @@ -97,7 +104,7 @@ func platformBackend(args map[string]interface{}) (map[string]interface{}, error } default: return nil, mobiumerr.New(mobiumerr.InvalidArgument, - "unknown platform %q (want \"android\" or \"ios\")", platform) + "unknown platform %q (want \"android\", \"ios\" or \"macos\")", platform) } return out, nil } @@ -365,6 +372,8 @@ func sessionPlatform(s *session) string { switch s.backend { case BackendWDA: return "ios" + case BackendMac: + return "macos" case BackendUIA2, BackendDump: return "android" default: diff --git a/internal/agent/tracing.go b/internal/agent/tracing.go index ed11e8a5..7bb53728 100644 --- a/internal/agent/tracing.go +++ b/internal/agent/tracing.go @@ -142,8 +142,11 @@ func TraceSavedMessage(path string, v TraceView) string { } func platformOf(s *session) string { - if s.backend == BackendWDA { + switch s.backend { + case BackendWDA: return "ios" + case BackendMac: + return "macos" } return "android" } diff --git a/internal/apisurface/flags.go b/internal/apisurface/flags.go index 2ea90195..7ee92500 100644 --- a/internal/apisurface/flags.go +++ b/internal/apisurface/flags.go @@ -2,7 +2,6 @@ package apisurface import ( "go/ast" - "go/parser" "go/token" "sort" "strconv" @@ -163,7 +162,7 @@ func dedupe(in []string) []string { // argument keys it sends. func collectCommandFlags(dir string) ([]CommandFlags, error) { fset := token.NewFileSet() - pkgs, err := parser.ParseDir(fset, dir, nil, 0) + pkgs, err := ParseDir(fset, dir, nil, 0) if err != nil { return nil, err } diff --git a/internal/apisurface/outputschema/main.go b/internal/apisurface/outputschema/main.go index 0f5a3292..1b2de1fe 100644 --- a/internal/apisurface/outputschema/main.go +++ b/internal/apisurface/outputschema/main.go @@ -20,6 +20,7 @@ import ( "bytes" "encoding/json" "fmt" + "github.com/mobiumdev/mobium/internal/apisurface" "go/ast" "go/format" "go/importer" @@ -40,7 +41,7 @@ func main() { } dir := filepath.Join(root, "internal", "agent") fset := token.NewFileSet() - pkgs, err := parser.ParseDir(fset, dir, func(fi os.FileInfo) bool { + pkgs, err := apisurface.ParseDir(fset, dir, func(fi os.FileInfo) bool { return !strings.HasSuffix(fi.Name(), "_test.go") && fi.Name() != "outputschema_gen.go" }, parser.ParseComments) check(err) diff --git a/internal/apisurface/parsedir.go b/internal/apisurface/parsedir.go new file mode 100644 index 00000000..b726dfee --- /dev/null +++ b/internal/apisurface/parsedir.go @@ -0,0 +1,53 @@ +package apisurface + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" +) + +// Package is one package's parsed files, keyed by file path. +type Package struct { + Files map[string]*ast.File +} + +// ParseDir parses the .go files in dir that keep accepts (all, when nil), +// grouped by package name. It is go/parser's ParseDir, deprecated in Go 1.25. +// Build tags are not consulted, as they were not there: the surface is read +// from every file. +func ParseDir(fset *token.FileSet, dir string, keep func(os.FileInfo) bool, mode parser.Mode) (map[string]*Package, error) { + entries, err := os.ReadDir(dir) + if err != nil { + return nil, err + } + pkgs := map[string]*Package{} + for _, e := range entries { + if e.IsDir() || !strings.HasSuffix(e.Name(), ".go") { + continue + } + if keep != nil { + info, err := e.Info() + if err != nil { + return nil, err + } + if !keep(info) { + continue + } + } + path := filepath.Join(dir, e.Name()) + f, err := parser.ParseFile(fset, path, nil, mode) + if err != nil { + return nil, err + } + p := pkgs[f.Name.Name] + if p == nil { + p = &Package{Files: map[string]*ast.File{}} + pkgs[f.Name.Name] = p + } + p.Files[path] = f + } + return pkgs, nil +} diff --git a/internal/apisurface/surface.go b/internal/apisurface/surface.go index 13f5b0d3..864154b0 100644 --- a/internal/apisurface/surface.go +++ b/internal/apisurface/surface.go @@ -218,7 +218,7 @@ func Collect(root string) (*Surface, error) { // the tool it dispatches. func collectCLI(dir string) (map[string]string, ExtraCommands, int, error) { fset := token.NewFileSet() - pkgs, err := parser.ParseDir(fset, dir, nil, 0) + pkgs, err := ParseDir(fset, dir, nil, 0) if err != nil { return nil, nil, 0, err } @@ -327,7 +327,7 @@ func collectTopLevel(path string) (int, error) { // collectHidden names the commands registered but not shown in help. func collectHidden(dir string) ([]string, error) { fset := token.NewFileSet() - pkgs, err := parser.ParseDir(fset, dir, nil, 0) + pkgs, err := ParseDir(fset, dir, nil, 0) if err != nil { return nil, err } diff --git a/internal/mobiumdriver/macos.go b/internal/mobiumdriver/macos.go new file mode 100644 index 00000000..1a0079fe --- /dev/null +++ b/internal/mobiumdriver/macos.go @@ -0,0 +1,335 @@ +package mobiumdriver + +import ( + "context" + "os" + "time" + + "github.com/mobiumdev/mobium/internal/mobiumerr" + "github.com/mobiumdev/mobium/internal/uitree" +) + +// HostOptIn names the environment variable that lets the macOS driver act on +// a Mac that is not a virtual machine. Driving a desktop moves the real +// pointer and keyboard of whoever sits at it. +const HostOptIn = "MOBIUM_DESKTOP_HOST" + +// macSystem is what the macOS driver needs from the platform. The darwin build +// talks to Accessibility and Quartz; every other build refuses. +type macSystem interface { + Trusted() bool + InVM() (bool, error) + // Front is the app with keyboard focus. + Front() (pid int32, bundle string, err error) + Tree(pid int32) (*uitree.AXElement, error) + // ElementAt is the process and role of what a click at a point would reach. + ElementAt(x, y float64) (pid int32, role string, err error) + Click(x, y float64) error + // Key sends one key with modifiers; text sends characters to the focus. + Key(code uint16, flags uint64) error + Text(s string) error + Focus(pid int32, t axTarget) error + Value(pid int32, t axTarget) (string, error) + // Caret is where the insertion point is, which a password field still + // reports while it hides its value: after typing, the text's length. + Caret(pid int32, t axTarget) (int, error) + Scale() float64 + Screen() (w, h float64) + Screenshot(pid int32) ([]byte, error) + Open(args ...string) error + Quit(bundle string) error +} + +// axTarget finds a mapped element again in the live tree: its role, its +// identifier if it has one, and the center of its frame in points. A path +// does not survive a window coming or going, and the AutoFill popup does +// whenever a password field gains or loses focus. +type axTarget struct { + Role, ID string + X, Y float64 +} + +// Mac drives the apps of the Mac it runs on, through Accessibility. +type Mac struct { + sys macSystem +} + +// NewMac returns the macOS driver. +func NewMac() *Mac { return &Mac{sys: newMacSystem()} } + +// Name identifies the backend. +func (m *Mac) Name() string { return "macos" } + +// Start refuses a Mac that is not a virtual machine unless HostOptIn is set, +// and a process without the Accessibility grant. +func (m *Mac) Start(_ context.Context, _ func(string)) error { + vm, err := m.sys.InVM() + if err != nil { + return err + } + if !vm && os.Getenv(HostOptIn) != "1" { + return mobiumerr.New(mobiumerr.NotPermitted, "this Mac is not a virtual machine, and the macOS driver "+ + "moves its real pointer and keyboard"). + WithRemedy("run mobium inside a macOS virtual machine, or set " + HostOptIn + "=1 to drive this Mac") + } + if !m.sys.Trusted() { + return mobiumerr.New(mobiumerr.NotPermitted, "this process has no Accessibility permission, so it "+ + "cannot read or drive other apps"). + WithRemedy("System Settings > Privacy & Security > Accessibility: allow the app that runs mobium " + + "(the terminal, or sshd-keygen-wrapper over SSH), then start mobium again") + } + return nil +} + +// Close holds nothing. +func (m *Mac) Close() error { return nil } + +// Healthy asks for the front app. +func (m *Mac) Healthy(context.Context) bool { + _, _, err := m.sys.Front() + return err == nil +} + +// PointScale is the display's pixels per point. +func (m *Mac) PointScale() float64 { return m.sys.Scale() } + +func (m *Mac) screen() uitree.Rect { + w, h := m.sys.Screen() + s := m.sys.Scale() + return uitree.Rect{X2: int(w * s), Y2: int(h * s)} +} + +// Snapshot reads the app in front. +func (m *Mac) Snapshot(context.Context) (*uitree.Tree, error) { + pid, bundle, err := m.sys.Front() + if err != nil { + return nil, err + } + root, err := m.sys.Tree(pid) + if err != nil { + return nil, err + } + return uitree.ParseMac(root, bundle, m.sys.Scale(), m.screen()), nil +} + +// Screenshot captures the front app's front window, never the whole desktop. +func (m *Mac) Screenshot(context.Context) ([]byte, error) { + pid, _, err := m.sys.Front() + if err != nil { + return nil, err + } + return m.sys.Screenshot(pid) +} + +// Tap clicks at a point in pixels. A click reaches the window on top, so it +// is refused when another app's window is there. +func (m *Mac) Tap(_ context.Context, x, y int) error { + s := m.sys.Scale() + px, py := float64(x)/s, float64(y)/s + front, bundle, err := m.sys.Front() + if err != nil { + return err + } + pid, role, err := m.sys.ElementAt(px, py) + if err != nil { + return err + } + if pid != front { + return mobiumerr.New(mobiumerr.ElementNotReachable, "a click at (%d, %d) would reach another app's %s, "+ + "not %s", x, y, role, bundle). + WithRemedy("app_launch the app to bring its window to the front, then try again"). + WithDetail("role", role) + } + return m.sys.Click(px, py) +} + +const ( + keyA = 0x00 + keyDelete = 0x33 + flagCommand = 0x100000 + readBackWait = 2 * time.Second +) + +// SetText replaces a field's text with real keystrokes: focus, select all, +// type. The text is read back; a password, whose value macOS hides, by its +// caret. +func (m *Mac) SetText(ctx context.Context, n *uitree.Node, text string) error { + pid, t, err := m.target(n) + if err != nil { + return err + } + if err := m.sys.Focus(pid, t); err != nil { + return err + } + if err := m.sys.Key(keyA, flagCommand); err != nil { + return err + } + if err := m.sys.Text(text); err != nil { + return err + } + if n.Password { + return m.caretBack(ctx, pid, t, len([]rune(text))) + } + return m.readBack(ctx, pid, t, text) +} + +// caretBack confirms a password by where its caret is after typing, the one +// thing macOS tells about it: AXValue is empty and AXNumberOfCharacters is +// absent on a SwiftUI SecureField. +func (m *Mac) caretBack(ctx context.Context, pid int32, t axTarget, want int) error { + deadline := time.Now().Add(readBackWait) + got := -1 + for { + n, err := m.sys.Caret(pid, t) + if err != nil { + return err + } + if got = n; got == want { + return nil + } + if time.Now().After(deadline) || ctx.Err() != nil { + break + } + time.Sleep(100 * time.Millisecond) + } + if got < 0 { + return mobiumerr.New(mobiumerr.NotConfirmed, "the password field reports no caret, so typing %d "+ + "characters cannot be confirmed", want) + } + return mobiumerr.New(mobiumerr.NotConfirmed, "the password field's caret is at %d after typing %d characters", + got, want) +} + +// Clear empties a field: focus, select all, delete. +func (m *Mac) Clear(ctx context.Context, n *uitree.Node) error { + pid, t, err := m.target(n) + if err != nil { + return err + } + if err := m.sys.Focus(pid, t); err != nil { + return err + } + if err := m.sys.Key(keyA, flagCommand); err != nil { + return err + } + if err := m.sys.Key(keyDelete, 0); err != nil { + return err + } + if n.Password { + return m.caretBack(ctx, pid, t, 0) + } + return m.readBack(ctx, pid, t, "") +} + +func (m *Mac) readBack(ctx context.Context, pid int32, t axTarget, want string) error { + deadline := time.Now().Add(readBackWait) + var got string + for { + v, err := m.sys.Value(pid, t) + if err != nil { + return err + } + if got = v; got == want { + return nil + } + if time.Now().After(deadline) || ctx.Err() != nil { + break + } + time.Sleep(100 * time.Millisecond) + } + return mobiumerr.New(mobiumerr.NotConfirmed, "the field holds %q after typing %q", got, want) +} + +// target is the node's process and how to find it again. +func (m *Mac) target(n *uitree.Node) (int32, axTarget, error) { + pid, bundle, err := m.sys.Front() + if err != nil { + return 0, axTarget{}, err + } + if n.Package != "" && n.Package != bundle { + return 0, axTarget{}, mobiumerr.New(mobiumerr.ElementNotReachable, "%s is no longer the app in front (%s is)", + n.Package, bundle).WithRemedy("app_launch " + n.Package) + } + s := m.sys.Scale() + x, y := n.Bounds.Center() + return pid, axTarget{Role: n.Class, ID: n.TestID, X: float64(x) / s, Y: float64(y) / s}, nil +} + +// Launch opens an app by bundle id and waits for it to be in front. +func (m *Mac) Launch(ctx context.Context, appID string) error { + if err := m.sys.Open("-b", appID); err != nil { + return err + } + return m.waitFront(ctx, appID, true) +} + +// Terminate quits an app and waits for it to leave the front. +func (m *Mac) Terminate(ctx context.Context, appID string) error { + if err := m.sys.Quit(appID); err != nil { + return err + } + return m.waitFront(ctx, appID, false) +} + +func (m *Mac) waitFront(ctx context.Context, appID string, want bool) error { + deadline := time.Now().Add(10 * time.Second) + for { + _, bundle, err := m.sys.Front() + if err == nil && (bundle == appID) == want { + return nil + } + if time.Now().After(deadline) || ctx.Err() != nil { + verb := "come to the front" + if !want { + verb = "quit" + } + return mobiumerr.New(mobiumerr.Timeout, "%s did not %s within 10s", appID, verb) + } + time.Sleep(100 * time.Millisecond) + } +} + +// Install refuses: a Mac app is installed by copying its bundle, which +// mobium leaves to the caller. +func (m *Mac) Install(context.Context, string) error { + return mobiumerr.New(mobiumerr.Unsupported, "the macOS driver does not install apps"). + WithRemedy("copy the .app into /Applications or ~/Applications, then app_launch its bundle id") +} + +// OpenURL opens a URL with its default app. +func (m *Mac) OpenURL(_ context.Context, url string) error { return m.sys.Open(url) } + +// MacState says how the device list shows this Mac: "ready", "refused" (not +// a virtual machine and no opt-in) or "no accessibility". listed is false off +// macOS. +func MacState() (state string, listed bool) { + sys := newMacSystem() + vm, err := sys.InVM() + if err != nil { + return "", false + } + switch { + case !vm && os.Getenv(HostOptIn) != "1": + return "refused", true + case !sys.Trusted(): + return "no accessibility", true + } + return "ready", true +} + +// AlertText has no platform alert to read: a Mac's dialogs are sheets and +// windows in the tree, which app_alert reads and presses by caption. +func (m *Mac) AlertText(context.Context) (string, error) { return "", ErrNoAlert } + +// AnswerAlert refuses: AppKit marks no button as accept or dismiss that +// Mobium reads, and a position is not an answer (CHALLENGES 106). +func (m *Mac) AnswerAlert(context.Context, bool) error { + return mobiumerr.New(mobiumerr.Unsupported, "a Mac dialog is answered by pressing one of its buttons"). + WithRemedy("app_alert with button and the button's caption") +} + +// SendAlertText refuses: a Mac dialog's field is an ordinary field. +func (m *Mac) SendAlertText(context.Context, string) error { + return mobiumerr.New(mobiumerr.Unsupported, "a Mac dialog's field is an ordinary text field"). + WithRemedy("app_type into the field, by its ref from app_map") +} diff --git a/internal/mobiumdriver/macos_darwin.go b/internal/mobiumdriver/macos_darwin.go new file mode 100644 index 00000000..854fefb8 --- /dev/null +++ b/internal/mobiumdriver/macos_darwin.go @@ -0,0 +1,716 @@ +package mobiumdriver + +import ( + "os" + "os/exec" + "path/filepath" + "strconv" + "sync" + "time" + "unicode/utf16" + "unsafe" + + "github.com/ebitengine/purego" + "github.com/ebitengine/purego/objc" + "golang.org/x/sys/unix" + + "github.com/mobiumdev/mobium/internal/mobiumerr" + "github.com/mobiumdev/mobium/internal/uitree" +) + +type cgPoint struct{ X, Y float64 } +type cgSize struct{ W, H float64 } + +// darwinMac binds Accessibility, Quartz and CoreFoundation with purego, so +// the binary keeps CGO_ENABLED=0. +type darwinMac struct { + mu sync.Mutex + strs map[string]uintptr + err error + + cfStringCreateWithCString func(alloc uintptr, s string, enc uint32) uintptr + cfStringGetLength func(s uintptr) int64 + cfStringGetMaxSize func(n int64, enc uint32) int64 + cfStringGetCString func(s uintptr, buf *byte, size int64, enc uint32) bool + cfGetTypeID func(v uintptr) uint64 + cfStringGetTypeID func() uint64 + cfArrayGetTypeID func() uint64 + cfBooleanGetTypeID func() uint64 + cfNumberGetTypeID func() uint64 + cfArrayGetCount func(a uintptr) int64 + cfArrayGetValueAtIndex func(a uintptr, i int64) uintptr + cfBooleanGetValue func(b uintptr) bool + cfNumberGetValue func(n uintptr, typ int64, out unsafe.Pointer) bool + cfDictionaryGetValue func(d, key uintptr) uintptr + cfRelease func(v uintptr) + cfRetain func(v uintptr) uintptr + cfBooleanTrue uintptr + + axIsProcessTrusted func() bool + axUIElementCreateApplication func(pid int32) uintptr + axUIElementCreateSystemWide func() uintptr + axUIElementCopyAttributeValue func(e, name uintptr, out *uintptr) int32 + axUIElementSetAttributeValue func(e, name, value uintptr) int32 + axUIElementCopyElementAtPosition func(e uintptr, x, y float32, out *uintptr) int32 + axUIElementGetPid func(e uintptr, pid *int32) int32 + axValueGetValue func(v uintptr, typ uint32, out unsafe.Pointer) bool + + cgMainDisplayID func() uint32 + cgDisplayPixelsWide func(id uint32) uint64 + cgDisplayPixelsHigh func(id uint32) uint64 + cgWindowListCopyWindowInfo func(opt, rel uint32) uintptr + cgEventCreateMouseEvent func(src uintptr, typ uint32, p cgPoint, button uint32) uintptr + cgEventCreateKeyboardEvent func(src uintptr, key uint16, down bool) uintptr + cgEventKeyboardSetUnicodeString func(ev uintptr, n uint64, s *uint16) + cgEventSetIntegerValueField func(ev uintptr, field uint32, v int64) + cgEventSetFlags func(ev uintptr, flags uint64) + cgEventPost func(tap uint32, ev uintptr) + cgPreflightScreenCaptureAccess func() bool +} + +const ( + cfUTF8 = 0x08000100 + cfNumberF64 = 13 + cfNumberI32 = 3 + axValuePoint = 1 + axValueSize = 2 + axValueRange = 4 + maxAXDepth = 60 +) + +func newMacSystem() macSystem { + d := &darwinMac{strs: map[string]uintptr{}} + d.err = d.load() + return d +} + +func (d *darwinMac) load() error { + open := func(path string) (uintptr, error) { return purego.Dlopen(path, purego.RTLD_GLOBAL|purego.RTLD_NOW) } + cf, err := open("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation") + if err != nil { + return mobiumerr.New(mobiumerr.Internal, "load CoreFoundation: %v", err) + } + as, err := open("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices") + if err != nil { + return mobiumerr.New(mobiumerr.Internal, "load ApplicationServices: %v", err) + } + if _, err := open("/System/Library/Frameworks/AppKit.framework/AppKit"); err != nil { + return mobiumerr.New(mobiumerr.Internal, "load AppKit: %v", err) + } + for _, f := range []struct { + lib uintptr + fn any + name string + }{ + {cf, &d.cfStringCreateWithCString, "CFStringCreateWithCString"}, + {cf, &d.cfStringGetLength, "CFStringGetLength"}, + {cf, &d.cfStringGetMaxSize, "CFStringGetMaximumSizeForEncoding"}, + {cf, &d.cfStringGetCString, "CFStringGetCString"}, + {cf, &d.cfGetTypeID, "CFGetTypeID"}, + {cf, &d.cfStringGetTypeID, "CFStringGetTypeID"}, + {cf, &d.cfArrayGetTypeID, "CFArrayGetTypeID"}, + {cf, &d.cfBooleanGetTypeID, "CFBooleanGetTypeID"}, + {cf, &d.cfNumberGetTypeID, "CFNumberGetTypeID"}, + {cf, &d.cfArrayGetCount, "CFArrayGetCount"}, + {cf, &d.cfArrayGetValueAtIndex, "CFArrayGetValueAtIndex"}, + {cf, &d.cfBooleanGetValue, "CFBooleanGetValue"}, + {cf, &d.cfNumberGetValue, "CFNumberGetValue"}, + {cf, &d.cfDictionaryGetValue, "CFDictionaryGetValue"}, + {cf, &d.cfRelease, "CFRelease"}, + {cf, &d.cfRetain, "CFRetain"}, + {as, &d.axIsProcessTrusted, "AXIsProcessTrusted"}, + {as, &d.axUIElementCreateApplication, "AXUIElementCreateApplication"}, + {as, &d.axUIElementCreateSystemWide, "AXUIElementCreateSystemWide"}, + {as, &d.axUIElementCopyAttributeValue, "AXUIElementCopyAttributeValue"}, + {as, &d.axUIElementSetAttributeValue, "AXUIElementSetAttributeValue"}, + {as, &d.axUIElementCopyElementAtPosition, "AXUIElementCopyElementAtPosition"}, + {as, &d.axUIElementGetPid, "AXUIElementGetPid"}, + {as, &d.axValueGetValue, "AXValueGetValue"}, + {as, &d.cgMainDisplayID, "CGMainDisplayID"}, + {as, &d.cgDisplayPixelsWide, "CGDisplayPixelsWide"}, + {as, &d.cgDisplayPixelsHigh, "CGDisplayPixelsHigh"}, + {as, &d.cgWindowListCopyWindowInfo, "CGWindowListCopyWindowInfo"}, + {as, &d.cgEventCreateMouseEvent, "CGEventCreateMouseEvent"}, + {as, &d.cgEventCreateKeyboardEvent, "CGEventCreateKeyboardEvent"}, + {as, &d.cgEventKeyboardSetUnicodeString, "CGEventKeyboardSetUnicodeString"}, + {as, &d.cgEventSetIntegerValueField, "CGEventSetIntegerValueField"}, + {as, &d.cgEventSetFlags, "CGEventSetFlags"}, + {as, &d.cgEventPost, "CGEventPost"}, + {as, &d.cgPreflightScreenCaptureAccess, "CGPreflightScreenCaptureAccess"}, + } { + purego.RegisterLibFunc(f.fn, f.lib, f.name) + } + sym, err := purego.Dlsym(cf, "kCFBooleanTrue") + if err != nil { + return mobiumerr.New(mobiumerr.Internal, "load kCFBooleanTrue: %v", err) + } + d.cfBooleanTrue = **(**uintptr)(unsafe.Pointer(&sym)) + return nil +} + +func (d *darwinMac) cfstr(s string) uintptr { + if r, ok := d.strs[s]; ok { + return r + } + r := d.cfStringCreateWithCString(0, s, cfUTF8) + d.strs[s] = r + return r +} + +func (d *darwinMac) gostr(s uintptr) string { + n := d.cfStringGetMaxSize(d.cfStringGetLength(s), cfUTF8) + 1 + buf := make([]byte, n) + if !d.cfStringGetCString(s, &buf[0], n, cfUTF8) { + return "" + } + for i, b := range buf { + if b == 0 { + return string(buf[:i]) + } + } + return string(buf) +} + +// copyAttr returns a reference the caller releases, or 0. +func (d *darwinMac) copyAttr(e uintptr, name string) uintptr { + var v uintptr + if d.axUIElementCopyAttributeValue(e, d.cfstr(name), &v) != 0 { + return 0 + } + return v +} + +func (d *darwinMac) strAttr(e uintptr, name string) string { + v := d.copyAttr(e, name) + if v == 0 { + return "" + } + defer d.cfRelease(v) + switch d.cfGetTypeID(v) { + case d.cfStringGetTypeID(): + return d.gostr(v) + case d.cfNumberGetTypeID(): + var f float64 + d.cfNumberGetValue(v, cfNumberF64, unsafe.Pointer(&f)) + return strconv.FormatFloat(f, 'f', -1, 64) + case d.cfBooleanGetTypeID(): + if d.cfBooleanGetValue(v) { + return "1" + } + return "0" + } + return "" +} + +func (d *darwinMac) boolAttr(e uintptr, name string, absent bool) bool { + v := d.copyAttr(e, name) + if v == 0 { + return absent + } + defer d.cfRelease(v) + if d.cfGetTypeID(v) != d.cfBooleanGetTypeID() { + return absent + } + return d.cfBooleanGetValue(v) +} + +func (d *darwinMac) frame(e uintptr) []float64 { + p, s := d.copyAttr(e, "AXPosition"), d.copyAttr(e, "AXSize") + if p != 0 { + defer d.cfRelease(p) + } + if s != 0 { + defer d.cfRelease(s) + } + if p == 0 || s == 0 { + return nil + } + var pt cgPoint + var sz cgSize + if !d.axValueGetValue(p, axValuePoint, unsafe.Pointer(&pt)) || !d.axValueGetValue(s, axValueSize, unsafe.Pointer(&sz)) { + return nil + } + return []float64{pt.X, pt.Y, sz.W, sz.H} +} + +func (d *darwinMac) element(e uintptr, depth int) *uitree.AXElement { + n := &uitree.AXElement{ + Role: d.strAttr(e, "AXRole"), + Subrole: d.strAttr(e, "AXSubrole"), + Title: d.strAttr(e, "AXTitle"), + Description: d.strAttr(e, "AXDescription"), + Value: d.strAttr(e, "AXValue"), + Identifier: d.strAttr(e, "AXIdentifier"), + Placeholder: d.strAttr(e, "AXPlaceholderValue"), + Frame: d.frame(e), + Enabled: d.boolAttr(e, "AXEnabled", true), + Selected: d.boolAttr(e, "AXSelected", false), + } + if macInputRole(n.Role) { + n.Focused = d.boolAttr(e, "AXFocused", false) + } + if depth >= maxAXDepth { + return n + } + kids := d.copyAttr(e, "AXChildren") + if kids == 0 { + return n + } + defer d.cfRelease(kids) + if d.cfGetTypeID(kids) != d.cfArrayGetTypeID() { + return n + } + for i := int64(0); i < d.cfArrayGetCount(kids); i++ { + n.Children = append(n.Children, d.element(d.cfArrayGetValueAtIndex(kids, i), depth+1)) + } + return n +} + +func macInputRole(role string) bool { + return role == "AXTextField" || role == "AXTextArea" || role == "AXComboBox" +} + +func (d *darwinMac) lock() error { + d.mu.Lock() + if d.err != nil { + d.mu.Unlock() + return d.err + } + return nil +} + +// pool runs f inside an autorelease pool: the daemon has no run loop to +// drain one, and every Objective-C call below autoreleases. +func pool(f func()) { + p := objc.ID(objc.GetClass("NSAutoreleasePool")).Send(objc.RegisterName("new")) + defer p.Send(objc.RegisterName("drain")) + f() +} + +func (d *darwinMac) Trusted() bool { + if d.lock() != nil { + return false + } + defer d.mu.Unlock() + return d.axIsProcessTrusted() +} + +func (d *darwinMac) InVM() (bool, error) { + v, err := unix.SysctlUint32("kern.hv_vmm_present") + if err != nil { + return false, mobiumerr.New(mobiumerr.Internal, "read kern.hv_vmm_present: %v", err) + } + return v == 1, nil +} + +// Front is the owner of the frontmost window below the Dock's level, so a +// system alert (level 8) is in front of the app it covers. AXFocusedApplication +// fails with kAXErrorCannotComplete in a macOS 26.6 guest, and NSWorkspace +// is updated only by a run loop, which the daemon has none of. +func (d *darwinMac) Front() (int32, string, error) { + if err := d.lock(); err != nil { + return 0, "", err + } + defer d.mu.Unlock() + pid, ok := d.frontPID() + if !ok { + return 0, "", mobiumerr.New(mobiumerr.DeviceNotReady, "no app has a window on screen") + } + return pid, d.bundleOf(pid), nil +} + +func (d *darwinMac) bundleOf(pid int32) string { + var out string + pool(func() { + app := objc.ID(objc.GetClass("NSRunningApplication")).Send( + objc.RegisterName("runningApplicationWithProcessIdentifier:"), pid) + if app == 0 { + return + } + s := app.Send(objc.RegisterName("bundleIdentifier")) + if s == 0 { + return + } + out = goCString(objc.Send[*byte](s, objc.RegisterName("UTF8String"))) + }) + return out +} + +func goCString(p *byte) string { + if p == nil { + return "" + } + n := 0 + for *(*byte)(unsafe.Add(unsafe.Pointer(p), n)) != 0 { + n++ + } + return string(unsafe.Slice(p, n)) +} + +func (d *darwinMac) Tree(pid int32) (*uitree.AXElement, error) { + if err := d.lock(); err != nil { + return nil, err + } + defer d.mu.Unlock() + app := d.axUIElementCreateApplication(pid) + defer d.cfRelease(app) + // An app that does not answer would read as an empty screen. One + // MobiumDesk launch answered kAXErrorAPIDisabled to every attribute + // while its window was up; the next launch answered. + var role uintptr + if r := d.axUIElementCopyAttributeValue(app, d.cfstr("AXRole"), &role); r != 0 { + return nil, mobiumerr.New(mobiumerr.DeviceNotReady, "%s does not answer accessibility (AXError %d)", + d.bundleOf(pid), r). + WithRemedy("app_terminate it and app_launch it again"). + WithDetail("axerror", r) + } + d.cfRelease(role) + return d.element(app, 0), nil +} + +func (d *darwinMac) ElementAt(x, y float64) (int32, string, error) { + if err := d.lock(); err != nil { + return 0, "", err + } + defer d.mu.Unlock() + sys := d.axUIElementCreateSystemWide() + defer d.cfRelease(sys) + var e uintptr + if r := d.axUIElementCopyElementAtPosition(sys, float32(x), float32(y), &e); r != 0 || e == 0 { + return 0, "", mobiumerr.New(mobiumerr.ElementNotReachable, "nothing at (%.0f, %.0f) points answers "+ + "accessibility (AXError %d)", x, y, r) + } + defer d.cfRelease(e) + var pid int32 + d.axUIElementGetPid(e, &pid) + return pid, d.strAttr(e, "AXRole"), nil +} + +func (d *darwinMac) post(ev uintptr) { + d.cgEventPost(0, ev) // kCGHIDEventTap + d.cfRelease(ev) +} + +func (d *darwinMac) Click(x, y float64) error { + if err := d.lock(); err != nil { + return err + } + defer d.mu.Unlock() + p := cgPoint{x, y} + d.post(d.cgEventCreateMouseEvent(0, 5, p, 0)) // mouseMoved + time.Sleep(30 * time.Millisecond) + for _, t := range []uint32{1, 2} { // leftMouseDown, leftMouseUp + ev := d.cgEventCreateMouseEvent(0, t, p, 0) + d.cgEventSetIntegerValueField(ev, 1, 1) // kCGMouseEventClickState + d.post(ev) + time.Sleep(50 * time.Millisecond) + } + return nil +} + +// macModifiers are the modifier keys and their flags, in the order they are +// pressed. +var macModifiers = []struct { + code uint16 + flag uint64 +}{ + {0x3B, 0x40000}, // control + {0x3A, 0x80000}, // option + {0x38, 0x20000}, // shift + {0x37, 0x100000}, // command +} + +// Key presses each modifier in flags as a key of its own, then the key, then +// releases the modifiers. A key event that only carries a modifier's flag +// leaves the system holding that modifier: Command stayed down after ⌘A, +// and every letter typed after it arrived as a shortcut. +func (d *darwinMac) Key(code uint16, flags uint64) error { + if err := d.lock(); err != nil { + return err + } + defer d.mu.Unlock() + key := func(c uint16, down bool, f uint64) { + ev := d.cgEventCreateKeyboardEvent(0, c, down) + d.cgEventSetFlags(ev, f) + d.post(ev) + } + var held uint64 + var pressed []uint16 + for _, m := range macModifiers { + if flags&m.flag != 0 { + held |= m.flag + key(m.code, true, held) + pressed = append(pressed, m.code) + } + } + key(code, true, held) + key(code, false, held) + for i := len(pressed) - 1; i >= 0; i-- { + for _, m := range macModifiers { + if m.code == pressed[i] { + held &^= m.flag + } + } + key(pressed[i], false, held) + } + time.Sleep(30 * time.Millisecond) + return nil +} + +func (d *darwinMac) Text(s string) error { + if err := d.lock(); err != nil { + return err + } + defer d.mu.Unlock() + for _, r := range s { + u := utf16.Encode([]rune{r}) + for _, down := range []bool{true, false} { + ev := d.cgEventCreateKeyboardEvent(0, 0, down) + d.cgEventKeyboardSetUnicodeString(ev, uint64(len(u)), &u[0]) + // Text, never a shortcut, whatever modifier the system holds. + d.cgEventSetFlags(ev, 0) + d.post(ev) + } + time.Sleep(15 * time.Millisecond) + } + return nil +} + +// find is the first element in pid's tree with t's role and identifier +// whose frame holds t's point. The caller releases it. +func (d *darwinMac) find(pid int32, t axTarget) (uintptr, error) { + app := d.axUIElementCreateApplication(pid) + defer d.cfRelease(app) + if e := d.search(app, t, 0); e != 0 { + return e, nil + } + return 0, mobiumerr.New(mobiumerr.NoSuchElement, "the element is gone: the screen changed since it was read"). + WithDetail("role", t.Role).WithDetail("testid", t.ID) +} + +func (d *darwinMac) search(e uintptr, t axTarget, depth int) uintptr { + if d.strAttr(e, "AXRole") == t.Role && d.strAttr(e, "AXIdentifier") == t.ID { + if f := d.frame(e); f != nil && t.X >= f[0] && t.X < f[0]+f[2] && t.Y >= f[1] && t.Y < f[1]+f[3] { + return d.cfRetain(e) + } + } + if depth >= maxAXDepth { + return 0 + } + kids := d.copyAttr(e, "AXChildren") + if kids == 0 { + return 0 + } + defer d.cfRelease(kids) + if d.cfGetTypeID(kids) != d.cfArrayGetTypeID() { + return 0 + } + for i := int64(0); i < d.cfArrayGetCount(kids); i++ { + if f := d.search(d.cfArrayGetValueAtIndex(kids, i), t, depth+1); f != 0 { + return f + } + } + return 0 +} + +func (d *darwinMac) Focus(pid int32, t axTarget) error { + if err := d.lock(); err != nil { + return err + } + defer d.mu.Unlock() + e, err := d.find(pid, t) + if err != nil { + return err + } + defer d.cfRelease(e) + if r := d.axUIElementSetAttributeValue(e, d.cfstr("AXFocused"), d.cfBooleanTrue); r != 0 { + return mobiumerr.New(mobiumerr.ElementNotReachable, "the field refused focus (AXError %d)", r) + } + deadline := time.Now().Add(time.Second) + for !d.boolAttr(e, "AXFocused", false) { + if time.Now().After(deadline) { + return mobiumerr.New(mobiumerr.NotConfirmed, "the field did not take focus within 1s") + } + time.Sleep(50 * time.Millisecond) + } + return nil +} + +func (d *darwinMac) Value(pid int32, t axTarget) (string, error) { + if err := d.lock(); err != nil { + return "", err + } + defer d.mu.Unlock() + e, err := d.find(pid, t) + if err != nil { + return "", err + } + defer d.cfRelease(e) + return d.strAttr(e, "AXValue"), nil +} + +func (d *darwinMac) Caret(pid int32, t axTarget) (int, error) { + if err := d.lock(); err != nil { + return 0, err + } + defer d.mu.Unlock() + e, err := d.find(pid, t) + if err != nil { + return 0, err + } + defer d.cfRelease(e) + v := d.copyAttr(e, "AXSelectedTextRange") + if v == 0 { + return -1, nil + } + defer d.cfRelease(v) + var r struct{ Loc, Len int64 } + if !d.axValueGetValue(v, axValueRange, unsafe.Pointer(&r)) { + return -1, nil + } + return int(r.Loc + r.Len), nil +} + +func (d *darwinMac) Scale() float64 { + var s float64 = 1 + if d.lock() != nil { + return s + } + defer d.mu.Unlock() + pool(func() { + scr := objc.ID(objc.GetClass("NSScreen")).Send(objc.RegisterName("mainScreen")) + if scr != 0 { + if v := objc.Send[float64](scr, objc.RegisterName("backingScaleFactor")); v > 0 { + s = v + } + } + }) + return s +} + +func (d *darwinMac) Screen() (float64, float64) { + if d.lock() != nil { + return 0, 0 + } + defer d.mu.Unlock() + id := d.cgMainDisplayID() + return float64(d.cgDisplayPixelsWide(id)), float64(d.cgDisplayPixelsHigh(id)) +} + +// windows calls f for each on-screen window below the Dock's level (20), +// front to back, until f returns false. The Dock, Notification Center, the +// menu bar and its status items are above it. +func (d *darwinMac) windows(f func(owner int32, id int64) bool) { + list := d.cgWindowListCopyWindowInfo(1|16, 0) // on screen only, excluding the desktop + if list == 0 { + return + } + defer d.cfRelease(list) + num := func(dict uintptr, key string) (int64, bool) { + v := d.cfDictionaryGetValue(dict, d.cfstr(key)) + if v == 0 { + return 0, false + } + var i int32 + if !d.cfNumberGetValue(v, cfNumberI32, unsafe.Pointer(&i)) { + return 0, false + } + return int64(i), true + } + for i := int64(0); i < d.cfArrayGetCount(list); i++ { + w := d.cfArrayGetValueAtIndex(list, i) + layer, _ := num(w, "kCGWindowLayer") + owner, ok1 := num(w, "kCGWindowOwnerPID") + id, ok2 := num(w, "kCGWindowNumber") + if layer >= 0 && layer < 20 && ok1 && ok2 && !f(int32(owner), id) { + return + } + } +} + +func (d *darwinMac) frontPID() (pid int32, ok bool) { + d.windows(func(owner int32, _ int64) bool { + pid, ok = owner, true + return false + }) + return pid, ok +} + +func (d *darwinMac) windowOf(pid int32) (id int64, ok bool) { + d.windows(func(owner int32, w int64) bool { + if owner == pid { + id, ok = w, true + return false + } + return true + }) + return id, ok +} + +func (d *darwinMac) Screenshot(pid int32) ([]byte, error) { + if err := d.lock(); err != nil { + return nil, err + } + allowed := d.cgPreflightScreenCaptureAccess() + id, ok := d.windowOf(pid) + d.mu.Unlock() + // Capturing without the grant raises a prompt that takes the front of + // the screen and stops every later action until someone answers it. + if !allowed { + return nil, mobiumerr.New(mobiumerr.NotPermitted, "the process that runs mobium has no Screen Recording "+ + "permission, and asking for it would put a prompt in front of the app"). + WithRemedy("System Settings > Privacy & Security > Screen & System Audio Recording: allow it, then " + + "start mobium again") + } + if !ok { + return nil, mobiumerr.New(mobiumerr.NoSuchElement, "the app in front has no window on screen") + } + dir, err := os.MkdirTemp("", "mobium-shot") + if err != nil { + return nil, mobiumerr.New(mobiumerr.Internal, "screenshot: %v", err) + } + defer func() { _ = os.RemoveAll(dir) }() + file := filepath.Join(dir, "w.png") + out, err := exec.Command("screencapture", "-x", "-o", "-t", "png", "-l", strconv.FormatInt(id, 10), file).CombinedOutput() + if err != nil { + return nil, mobiumerr.New(mobiumerr.DeviceServer, "screencapture: %v: %s", err, out) + } + b, err := os.ReadFile(file) + if err != nil || len(b) == 0 { + return nil, mobiumerr.New(mobiumerr.NotPermitted, "screencapture wrote no image: the process that runs "+ + "mobium needs Screen Recording permission"). + WithRemedy("System Settings > Privacy & Security > Screen & System Audio Recording: allow it") + } + return b, nil +} + +func (d *darwinMac) Open(args ...string) error { + out, err := exec.Command("open", args...).CombinedOutput() + if err != nil { + return mobiumerr.New(mobiumerr.InvalidArgument, "open %v: %s", args, out) + } + return nil +} + +func (d *darwinMac) Quit(bundle string) error { + if err := d.lock(); err != nil { + return err + } + defer d.mu.Unlock() + found := false + pool(func() { + id := objc.ID(objc.GetClass("NSString")).Send(objc.RegisterName("stringWithUTF8String:"), bundle) + apps := objc.ID(objc.GetClass("NSRunningApplication")).Send( + objc.RegisterName("runningApplicationsWithBundleIdentifier:"), id) + n := objc.Send[uint64](apps, objc.RegisterName("count")) + for i := uint64(0); i < n; i++ { + app := apps.Send(objc.RegisterName("objectAtIndex:"), i) + app.Send(objc.RegisterName("terminate")) + found = true + } + }) + if !found { + return mobiumerr.New(mobiumerr.InvalidArgument, "%s is not running", bundle) + } + return nil +} diff --git a/internal/mobiumdriver/macos_other.go b/internal/mobiumdriver/macos_other.go new file mode 100644 index 00000000..04c48cf9 --- /dev/null +++ b/internal/mobiumdriver/macos_other.go @@ -0,0 +1,35 @@ +//go:build !darwin + +package mobiumdriver + +import ( + "github.com/mobiumdev/mobium/internal/mobiumerr" + "github.com/mobiumdev/mobium/internal/uitree" +) + +// otherMac refuses everything: Accessibility exists only on macOS. +type otherMac struct{} + +func newMacSystem() macSystem { return otherMac{} } + +func errNotMac() error { + return mobiumerr.New(mobiumerr.Unsupported, "the macOS driver runs only on macOS"). + WithRemedy("run mobium on the Mac whose apps it drives, or reach one with --remote") +} + +func (otherMac) Trusted() bool { return false } +func (otherMac) InVM() (bool, error) { return false, errNotMac() } +func (otherMac) Front() (int32, string, error) { return 0, "", errNotMac() } +func (otherMac) Tree(int32) (*uitree.AXElement, error) { return nil, errNotMac() } +func (otherMac) ElementAt(float64, float64) (int32, string, error) { return 0, "", errNotMac() } +func (otherMac) Click(float64, float64) error { return errNotMac() } +func (otherMac) Key(uint16, uint64) error { return errNotMac() } +func (otherMac) Text(string) error { return errNotMac() } +func (otherMac) Focus(int32, axTarget) error { return errNotMac() } +func (otherMac) Value(int32, axTarget) (string, error) { return "", errNotMac() } +func (otherMac) Caret(int32, axTarget) (int, error) { return 0, errNotMac() } +func (otherMac) Scale() float64 { return 1 } +func (otherMac) Screen() (float64, float64) { return 0, 0 } +func (otherMac) Screenshot(int32) ([]byte, error) { return nil, errNotMac() } +func (otherMac) Open(...string) error { return errNotMac() } +func (otherMac) Quit(string) error { return errNotMac() } diff --git a/internal/uitree/locator.go b/internal/uitree/locator.go index 186c1e15..d0e8e0a8 100644 --- a/internal/uitree/locator.go +++ b/internal/uitree/locator.go @@ -419,6 +419,10 @@ func hasNamedRole(n *Node, role string, clickableFallback bool) bool { return true } + if IsMac(n) { + return macHasRole(n, role) + } + if IsIOS(n) { // iOS types are exact, not a hierarchy of subclasses, so the type // name after the prefix is compared directly. No clickable-fallback diff --git a/internal/uitree/parse.go b/internal/uitree/parse.go index f5091d00..b7eb2758 100644 --- a/internal/uitree/parse.go +++ b/internal/uitree/parse.go @@ -540,6 +540,9 @@ func (n *Node) ShortClass() string { if s, ok := strings.CutPrefix(n.Class, "XCUIElementType"); ok && s != "" { return s } + if s, ok := strings.CutPrefix(n.Class, "AX"); ok && s != "" { + return s + } if i := strings.LastIndexByte(n.Class, '.'); i >= 0 { return n.Class[i+1:] } diff --git a/internal/uitree/parse_ax.go b/internal/uitree/parse_ax.go new file mode 100644 index 00000000..a80e7eba --- /dev/null +++ b/internal/uitree/parse_ax.go @@ -0,0 +1,261 @@ +package uitree + +import ( + "strconv" + "strings" +) + +// AXElement is one element of a macOS app's accessibility tree, as the +// macOS driver reads it: the AX attributes Mobium uses, in points. +type AXElement struct { + Role string + Subrole string + Title string + Description string + // Value is AXValue when it is a string or a number, as text. + Value string + Identifier string + Placeholder string + // Frame is AXPosition and AXSize in screen points; nil when the element + // has no geometry. + Frame []float64 + Enabled bool + Focused bool + Selected bool + Children []*AXElement +} + +// macClickable are the AX roles a click presses. A list's row is; the cell +// inside it is the row's content, and listing both named every row twice. AXPress is not read from +// each element's action list: that is one more round trip per node. +var macClickable = map[string]bool{ + "AXButton": true, "AXCheckBox": true, "AXRadioButton": true, "AXPopUpButton": true, + "AXMenuButton": true, "AXMenuItem": true, "AXMenuBarItem": true, "AXLink": true, + "AXDisclosureTriangle": true, "AXRow": true, "AXIncrementor": true, + "AXComboBox": true, "AXColorWell": true, +} + +// macButtonNames name a window's own buttons, which carry no title. +var macButtonNames = map[string]string{ + "AXCloseButton": "Close", "AXMinimizeButton": "Minimize", "AXZoomButton": "Zoom", + "AXFullScreenButton": "Full Screen", +} + +// macInput are the AX roles that take typing. +var macInput = map[string]bool{"AXTextField": true, "AXTextArea": true, "AXComboBox": true} + +// ParseMac turns a macOS app's accessibility tree into a Tree. scale is the +// display's pixels per point; Mobium's coordinates are pixels everywhere. +// bundle is the app's bundle id, set as every node's Package. +func ParseMac(app *AXElement, bundle string, scale float64, screen Rect) *Tree { + if scale <= 0 { + scale = 1 + } + root := &Node{Class: "hierarchy", Enabled: true, Displayed: true, Bounds: screen} + tree := &Tree{Root: root, Screen: screen} + if app != nil { + n := macNodeFrom(app, root, 0, bundle, scale, screen, screen) + root.Children = []*Node{n} + } + return tree +} + +// clip is what of the screen the parent's window and scroll areas show. +func macNodeFrom(e *AXElement, parent *Node, sibling int, bundle string, scale float64, screen, clip Rect) *Node { + path := strconv.Itoa(sibling) + if parent.Parent != nil || parent.Path != "" { + path = parent.Path + "/" + path + } + n := &Node{ + Class: e.Role, + Package: bundle, + TestID: macTestID(e.Identifier), + Label: firstNonEmpty(e.Description, e.Title), + Hint: e.Placeholder, + Enabled: e.Enabled, + Focused: e.Focused, + Selected: e.Selected, + Clickable: macClickable[e.Role], + Focusable: macInput[e.Role], + Password: e.Subrole == "AXSecureTextField", + Window: e.Role == "AXWindow", + Depth: parent.Depth + 1, + Index: sibling, + Parent: parent, + Path: path, + } + if parent.Parent == nil { + n.Depth = 0 + } + if n.Label == "" { + n.Label = macButtonNames[e.Subrole] + } + switch e.Subrole { + case "AXSwitch": + n.DeclaredRole = "switch" + case "AXTabButton": + n.DeclaredRole = "tab" + case "AXSearchField": + n.DeclaredRole = "input" + } + switch e.Role { + case "AXCheckBox", "AXRadioButton": + // Their AXValue is 0, 1 or 2 (mixed), never text. + n.Checkable = true + n.Checked = e.Value == "1" + case "AXSlider", "AXProgressIndicator", "AXScrollBar", "AXValueIndicator", "AXLevelIndicator": + n.Value = e.Value + case "AXScrollArea": + n.Scrollable = true + default: + // A password's AXValue is empty already: macOS hides it from + // accessibility, measured on a SwiftUI SecureField. + if !n.Password { + n.Text = e.Value + } + } + if n.Text == "" && !macInput[e.Role] && !n.Password { + n.Text = e.Title + } + if n.Text != "" && n.Text == e.Placeholder { + n.ShowingHint = true + } + // An element with no frame, the application itself, is as shown as its + // parent. What a hidden element holds is hidden too. + n.Displayed = parent.Displayed + // AppKit nests a sheet in a zero-size sheet; the outer one hides nothing. + if e.Frame != nil && !(e.Role == "AXSheet" && macEmpty(e.Frame)) { + var on bool + n.Bounds, on = macBounds(e.Frame, scale, screen) + x, y := n.Bounds.Center() + n.Displayed = n.Displayed && on && contains(clip, x, y) + } + switch { + case e.Role == "AXSheet" && !n.Bounds.Empty(): + // A sheet may run past its window's edge. + clip = macIntersect(screen, n.Bounds) + case e.Role == "AXWindow" || e.Role == "AXScrollArea": + clip = macIntersect(clip, n.Bounds) + } + // A scroll bar's arrows and pages are driven by scrolling, not by name. + if e.Role == "AXScrollBar" || parent.Class == "AXScrollBar" { + n.Clickable = false + } + for i, c := range e.Children { + n.Children = append(n.Children, macNodeFrom(c, n, i, bundle, scale, screen, clip)) + } + if n.Window { + blockBehindSheet(n) + } + return n +} + +// blockBehindSheet hides what a window shows outside its sheet. A sheet is +// modal: a click elsewhere in the window is swallowed, and was reported done. +func blockBehindSheet(w *Node) { + var sheet *Node + for _, c := range w.Children { + if c.Class == "AXSheet" && hasShownSheet(c) { + sheet = c + } + } + if sheet == nil { + return + } + for _, c := range w.Children { + if c != sheet { + hide(c) + } + } +} + +func hasShownSheet(n *Node) bool { + if n.Class == "AXSheet" && n.Displayed && !n.Bounds.Empty() { + return true + } + for _, c := range n.Children { + if hasShownSheet(c) { + return true + } + } + return false +} + +func hide(n *Node) { + n.Displayed = false + for _, c := range n.Children { + hide(c) + } +} + +func macEmpty(f []float64) bool { return len(f) == 4 && (f[2] <= 0 || f[3] <= 0) } + +// macBounds converts a frame in points to pixels and says whether any of it +// is on screen. A row scrolled out of a SwiftUI list reports a zero-size +// frame at the screen's bottom edge, [0, 768, 0, 0] on a 768-point display, +// so a frame with no area is never shown. +func macBounds(f []float64, scale float64, screen Rect) (Rect, bool) { + if len(f) != 4 { + return Rect{}, false + } + r := Rect{ + X1: int(f[0] * scale), Y1: int(f[1] * scale), + X2: int((f[0] + f[2]) * scale), Y2: int((f[1] + f[3]) * scale), + } + if r.X2 <= r.X1 || r.Y2 <= r.Y1 { + return r, false + } + if screen.X2 > screen.X1 && (r.X2 <= screen.X1 || r.X1 >= screen.X2 || r.Y2 <= screen.Y1 || r.Y1 >= screen.Y2) { + return r, false + } + return r, true +} + +// macTestID drops identifiers an app never chose. SwiftUI names a window by +// its view's Swift type ("SwiftUI.ModifiedContent<…>-1-AppWindow-1"), and +// AppKit names a menu item by its action's selector ("_aboutThisMacRequested:"). +// AppKit numbers views it names itself ("_NS:8"). None of them is a test id. +func macTestID(id string) string { + if strings.HasPrefix(id, "_NS:") || strings.HasSuffix(id, ":") || strings.Contains(id, "SwiftUI.") || strings.ContainsAny(id, "<>") { + return "" + } + return id +} + +// IsMac reports whether a node came from a macOS accessibility tree. +func IsMac(n *Node) bool { return strings.HasPrefix(n.Class, "AX") } + +// macRoleTypes maps a neutral role onto the AX roles that satisfy it. Roles +// an element states by its subrole (switch, tab, search field) are in +// DeclaredRole instead. +var macRoleTypes = map[string][]string{ + "button": {"AXButton", "AXPopUpButton", "AXMenuButton", "AXDisclosureTriangle"}, + "input": {"AXTextField", "AXTextArea", "AXComboBox"}, + "checkbox": {"AXCheckBox"}, + "radio": {"AXRadioButton"}, + "slider": {"AXSlider"}, + "progressbar": {"AXProgressIndicator", "AXBusyIndicator"}, + "image": {"AXImage"}, + "text": {"AXStaticText"}, + "link": {"AXLink"}, + "list": {"AXScrollArea", "AXList", "AXOutline", "AXTable"}, + "tab": {"AXTabGroup"}, + "cell": {"AXCell", "AXRow"}, +} + +func macHasRole(n *Node, role string) bool { + if role == "checkbox" && n.DeclaredRole == "switch" { + // A switch is an AXCheckBox to AppKit; it is not a checkbox to a user. + return false + } + for _, want := range macRoleTypes[role] { + if n.Class == want { + return true + } + } + return false +} + +func macIntersect(a, b Rect) Rect { + return Rect{X1: max(a.X1, b.X1), Y1: max(a.Y1, b.Y1), X2: min(a.X2, b.X2), Y2: min(a.Y2, b.Y2)} +} diff --git a/internal/uitree/parse_ax_test.go b/internal/uitree/parse_ax_test.go new file mode 100644 index 00000000..07209638 --- /dev/null +++ b/internal/uitree/parse_ax_test.go @@ -0,0 +1,153 @@ +package uitree + +import "testing" + +func macFixture() *AXElement { + return &AXElement{Role: "AXApplication", Title: "MobiumDesk", Enabled: true, Children: []*AXElement{ + {Role: "AXWindow", Identifier: "SwiftUI.ModifiedContent-1-AppWindow-1", Title: "MobiumDesk", + Frame: []float64{62, 143, 900, 452}, Enabled: true, Children: []*AXElement{ + {Role: "AXButton", Subrole: "AXCloseButton", Frame: []float64{70, 151, 16, 16}, Enabled: true}, + {Role: "AXTextField", Identifier: "username", Frame: []float64{78, 191, 868, 24}, Enabled: true}, + {Role: "AXTextField", Subrole: "AXSecureTextField", Identifier: "password", Frame: []float64{78, 225, 868, 24}, Enabled: true}, + {Role: "AXButton", Identifier: "signin", Title: "Sign In", Frame: []float64{78, 259, 65.5, 24}, Enabled: true}, + {Role: "AXStaticText", Identifier: "status", Value: "Signed out", Frame: []float64{78, 293, 65.5, 16}, Enabled: true}, + {Role: "AXCheckBox", Subrole: "AXSwitch", Identifier: "dark", Title: "Dark", Value: "1", Frame: []float64{78, 319, 40, 24}, Enabled: true}, + {Role: "AXScrollArea", Identifier: "rows", Frame: []float64{78, 353, 868, 226}, Enabled: true, Children: []*AXElement{ + {Role: "AXStaticText", Identifier: "row-1", Value: "Row 1", Frame: []float64{94, 367, 35.5, 16}, Enabled: true}, + {Role: "AXStaticText", Identifier: "row-30", Value: "Row 30", Frame: []float64{0, 768, 0, 0}, Enabled: true}, + {Role: "AXRow", Frame: []float64{88, 400, 831, 24}, Enabled: true, Children: []*AXElement{ + {Role: "AXCell", Frame: []float64{88, 400, 831, 24}, Enabled: true, Children: []*AXElement{ + {Role: "AXStaticText", Identifier: "row-3", Value: "Row 3", Frame: []float64{94, 404, 37, 16}, Enabled: true}, + }}, + }}, + {Role: "AXRow", Frame: []float64{88, 600, 831, 24}, Enabled: true, Children: []*AXElement{ + {Role: "AXCell", Frame: []float64{88, 600, 831, 24}, Enabled: true, Children: []*AXElement{ + {Role: "AXStaticText", Identifier: "row-12", Value: "Row 12", Frame: []float64{94, 604, 37, 16}, Enabled: true}, + }}, + }}, + {Role: "AXScrollBar", Frame: []float64{932, 353, 11, 226}, Enabled: true, Children: []*AXElement{ + {Role: "AXButton", Subrole: "AXIncrementPage", Frame: []float64{932, 407, 11, 169}, Enabled: true}, + }}, + }}, + }}, + {Role: "AXScrollArea", Identifier: "_NS:8", Frame: []float64{62, 600, 100, 50}, Enabled: true}, + {Role: "AXMenuBar", Frame: []float64{0, 0, 1024, 30}, Enabled: true, Children: []*AXElement{ + {Role: "AXMenuBarItem", Title: "Probe", Frame: []float64{300, 0, 50, 30}, Enabled: true, Children: []*AXElement{ + {Role: "AXMenu", Frame: []float64{0, 768, 0, 0}, Enabled: true, Children: []*AXElement{ + {Role: "AXMenuItem", Identifier: "reset:", Title: "Reset Counter", Frame: []float64{310, 40, 200, 22}, Enabled: true}, + }}, + }}, + }}, + }} +} + +func macFind(n *Node, id string) *Node { + if n.TestID == id { + return n + } + for _, c := range n.Children { + if f := macFind(c, id); f != nil { + return f + } + } + return nil +} + +func TestParseMac(t *testing.T) { + tree := ParseMac(macFixture(), "dev.mobium.desk", 2, Rect{X2: 2048, Y2: 1536}) + app := tree.Root.Children[0] + if !app.Displayed || app.Path != "0" { + t.Fatalf("app element: displayed=%v path=%q, want shown at 0", app.Displayed, app.Path) + } + win := app.Children[0] + if !win.Window || win.TestID != "" { + t.Errorf("window: Window=%v TestID=%q, want a window with SwiftUI's type name dropped", win.Window, win.TestID) + } + if c := win.Children[0]; c.Label != "Close" || !HasRole(c, "button") { + t.Errorf("close button: label %q", c.Label) + } + signin := macFind(tree.Root, "signin") + if signin == nil || !Actionable(signin) || signin.Label != "Sign In" || !HasRole(signin, "button") { + t.Fatalf("signin = %+v, want an actionable button labeled Sign In", signin) + } + if signin.Bounds != (Rect{X1: 156, Y1: 518, X2: 287, Y2: 566}) { + t.Errorf("signin bounds = %+v, want points times 2", signin.Bounds) + } + user := macFind(tree.Root, "username") + if !Actionable(user) || !HasRole(user, "input") { + t.Errorf("username: actionable=%v input=%v", Actionable(user), HasRole(user, "input")) + } + if pw := macFind(tree.Root, "password"); !pw.Password || !HasRole(pw, "password") { + t.Errorf("password field not marked: %+v", pw) + } + sw := macFind(tree.Root, "dark") + if !HasRole(sw, "switch") || HasRole(sw, "checkbox") || !sw.Checked { + t.Errorf("switch: switch=%v checkbox=%v checked=%v", HasRole(sw, "switch"), HasRole(sw, "checkbox"), sw.Checked) + } + if st := macFind(tree.Root, "status"); st.Text != "Signed out" || !HasRole(st, "text") { + t.Errorf("status text = %q", st.Text) + } + if r := macFind(tree.Root, "row-1"); !r.Displayed { + t.Error("row-1 is on screen and was hidden") + } + if r := macFind(tree.Root, "row-30"); r.Displayed { + t.Error("row-30 has a zero-size frame and was shown") + } + var rows, inMap []string + tree.Walk(func(n *Node) bool { + if n.Class == "AXRow" && Actionable(n) { + rows = append(rows, describe(n)) + } + if Actionable(n) && (n.Class == "AXCell" || n.Parent.Class == "AXScrollBar") { + inMap = append(inMap, n.Class) + } + return true + }) + if len(rows) != 1 || rows[0] != "Row 3" { + t.Errorf("rows in map = %q, want only Row 3: Row 12 lies below the list's bottom edge", rows) + } + if len(inMap) != 0 { + t.Errorf("a cell or a scroll bar part is in map: %v", inMap) + } + if got := (&Node{Class: "AXScrollArea"}).ShortClass(); got != "ScrollArea" { + t.Errorf("ShortClass = %q", got) + } + if id := app.Children[1].TestID; id != "" { + t.Errorf("AppKit's own view number %q kept as a test id", id) + } + bar := app.Children[2].Children[0] + if !bar.Displayed || !Actionable(bar) { + t.Errorf("menu bar item: displayed=%v actionable=%v", bar.Displayed, Actionable(bar)) + } + item := bar.Children[0].Children[0] + if item.Displayed || item.TestID != "" { + t.Errorf("closed menu's item: displayed=%v testid=%q, want hidden and the selector dropped", item.Displayed, item.TestID) + } +} + +func TestParseMacSheet(t *testing.T) { + app := &AXElement{Role: "AXApplication", Enabled: true, Children: []*AXElement{ + {Role: "AXWindow", Frame: []float64{62, 143, 900, 452}, Enabled: true, Children: []*AXElement{ + {Role: "AXButton", Identifier: "signin", Title: "Sign In", Frame: []float64{78, 259, 65.5, 24}, Enabled: true}, + {Role: "AXSheet", Frame: []float64{512, 369, 1, 0}, Enabled: true, Children: []*AXElement{ + {Role: "AXSheet", Frame: []float64{292, 175, 440, 515}, Enabled: true, Children: []*AXElement{ + {Role: "AXButton", Identifier: "unlock", Title: "Unlock", Frame: []float64{645.5, 646, 66.5, 24}, Enabled: true}, + }}, + }}, + }}, + }} + tree := ParseMac(app, "dev.mobium.desk", 1, Rect{X2: 1024, Y2: 768}) + if n := macFind(tree.Root, "signin"); Actionable(n) { + t.Error("Sign In is behind a sheet and was actionable") + } + if n := macFind(tree.Root, "unlock"); !Actionable(n) { + t.Error("Unlock is on the sheet, inside a zero-size sheet, and was not actionable") + } + d := tree.Dialog() + if d == nil || d.Bounds.Empty() { + t.Fatalf("Dialog() = %+v, want the inner sheet", d) + } + if !macFind(tree.Root, "unlock").Within(d) || macFind(tree.Root, "signin").Within(d) { + t.Error("Unlock must be on the dialog and Sign In under it") + } +} diff --git a/internal/uitree/snapshot.go b/internal/uitree/snapshot.go index e2b4a22f..c7a62257 100644 --- a/internal/uitree/snapshot.go +++ b/internal/uitree/snapshot.go @@ -718,7 +718,9 @@ func (t *Tree) Dialog() *Node { if found != nil { return false } - if n.Displayed && (n.Class == "XCUIElementTypeAlert" || n.Class == "XCUIElementTypeSheet") { + // AppKit nests a sheet in a zero-size one; the dialog is the inner. + macSheet := n.Class == "AXSheet" && !n.Bounds.Empty() + if n.Displayed && (n.Class == "XCUIElementTypeAlert" || n.Class == "XCUIElementTypeSheet" || macSheet) { found = n return false }