diff --git a/README.md b/README.md
index e903c8c..510fb73 100644
--- a/README.md
+++ b/README.md
@@ -228,11 +228,14 @@ real headset, and not immersive apps, which publish no accessibility tree
**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.
+read back, a sheet treated as a dialog, scrolling with the wheel, the menu
+bar's menus, a context menu by `tap --button right`, keys and shortcuts by
+`press` (`press escape`, `press cmd+shift+r`), 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
+Screen Recording. Not yet: hover, drag and double click, 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
diff --git a/clients/dotnet/Mobium/Device.cs b/clients/dotnet/Mobium/Device.cs
index de7ae79..ec62f41 100644
--- a/clients/dotnet/Mobium/Device.cs
+++ b/clients/dotnet/Mobium/Device.cs
@@ -270,6 +270,13 @@ public void Drag(string from, string to, int holdMillis) =>
public void TapFingers(string target, int fingers) =>
Act("app_tap", Args("target", target, "fingers", fingers));
+ ///
+ /// Right-clicks an element, which opens a context menu on a Mac. A
+ /// phone throws; LongPress opens a context menu there.
+ ///
+ public void RightClick(string target) =>
+ Act("app_tap", Args("target", target, "button", "right"));
+
///
/// Holds one element with a finger while a second finger taps another;
/// the first lifts only after the second. Both are resolved before
@@ -1055,6 +1062,14 @@ public IList AppLocale(string app, string tags) =>
///
public void Press(string button) => Act("app_press", Args("button", button));
+ ///
+ /// Presses a key or a shortcut on a Mac: escape,
+ /// cmd+shift+r. A named key or one character, after modifiers
+ /// joined by + (cmd, shift, option, ctrl). Sent, not confirmed. A
+ /// phone throws; type text with Type or Fill.
+ ///
+ public void PressKeys(string keys) => Act("app_press", Args("keys", keys));
+
///
/// Goes back and says where it went: foreground, the app in
/// front afterwards; left, the app back closed, absent when it
diff --git a/clients/go/mobium.go b/clients/go/mobium.go
index a346120..d2abf8f 100644
--- a/clients/go/mobium.go
+++ b/clients/go/mobium.go
@@ -603,6 +603,12 @@ func (d *Device) TapFingers(ctx context.Context, target string, fingers int) err
return d.act(ctx, "app_tap", map[string]any{"target": target, "fingers": fingers})
}
+// RightClick right-clicks an element, which opens a context menu on a Mac. A
+// phone returns an error; LongPress opens a context menu there.
+func (d *Device) RightClick(ctx context.Context, target string) error {
+ return d.act(ctx, "app_tap", map[string]any{"target": target, "button": "right"})
+}
+
// PressTap holds one element with a finger while a second finger taps
// another, and lifts the first only after the second. Both are resolved
// before anything is touched. It reports that the gesture was delivered; what
@@ -1818,6 +1824,15 @@ func (d *Device) Press(ctx context.Context, button string) error {
return d.data(ctx, "app_press", map[string]any{"button": button}, &out)
}
+// PressKeys presses a key or a shortcut on a Mac: "escape", "cmd+shift+r". A
+// named key or one character, after modifiers joined by + (cmd, shift,
+// option, ctrl). Sent, not confirmed. A phone returns an error; type text
+// with Type or Fill.
+func (d *Device) PressKeys(ctx context.Context, keys string) error {
+ var out struct{}
+ return d.data(ctx, "app_press", map[string]any{"keys": keys}, &out)
+}
+
// BackResult is what a back did.
type BackResult struct {
// Foreground is the app in front afterwards.
diff --git a/clients/java/src/main/java/dev/mobium/Mobium.java b/clients/java/src/main/java/dev/mobium/Mobium.java
index f0f3598..723fca6 100644
--- a/clients/java/src/main/java/dev/mobium/Mobium.java
+++ b/clients/java/src/main/java/dev/mobium/Mobium.java
@@ -532,6 +532,16 @@ public void tapFingers(String target, int fingers) {
act("app_tap", args("target", target, "fingers", fingers));
}
+ /**
+ * Right-clicks an element, which opens a context menu on a Mac. A phone
+ * throws; {@code longPress} opens a context menu there.
+ *
+ * @param target a ref from {@link #map()} such as {@code "@e5"}, or a locator such as {@code "text=Sign in"}
+ */
+ public void rightClick(String target) {
+ act("app_tap", args("target", target, "button", "right"));
+ }
+
/**
* Holds one element with a finger while a second finger taps another; the
* first lifts only after the second. Both are resolved before anything is
@@ -1670,6 +1680,16 @@ public List appLocale(String app, String tags) {
*/
public void press(String button) { data("app_press", args("button", button)); }
+ /**
+ * Presses a key or a shortcut on a Mac: {@code "escape"},
+ * {@code "cmd+shift+r"}. A named key or one character, after modifiers
+ * joined by + (cmd, shift, option, ctrl). Sent, not confirmed. A phone
+ * throws; type text with {@code type} or {@code fill}.
+ *
+ * @param keys the key, with its modifiers
+ */
+ public void pressKeys(String keys) { data("app_press", args("keys", keys)); }
+
/**
* Goes back with the key and says where it went.
*
diff --git a/clients/javascript/index.d.ts b/clients/javascript/index.d.ts
index 17bb286..2e72e15 100644
--- a/clients/javascript/index.d.ts
+++ b/clients/javascript/index.d.ts
@@ -258,8 +258,9 @@ export class Device {
scrollTo(target: string, options?: { direction?: 'down' | 'up' | 'left' | 'right' }): Promise
// acting
- tap(target: string, options?: { fingers?: number }): Promise
- tap(point: Point, options?: { fingers?: number }): Promise
+ /** `button: 'right'` right-clicks, on a Mac; left is the default. */
+ tap(target: string, options?: { fingers?: number; button?: 'right' }): Promise
+ tap(point: Point, options?: { fingers?: number; button?: 'right' }): Promise
doubleTap(target: string | Point): Promise
drag(from: string, to: string, options?: { holdMs?: number }): Promise
pressTap(hold: string, tap: string, options?: { leadMs?: number }): Promise
@@ -364,6 +365,8 @@ export class Device {
| 'back' | 'home' | 'recents' | 'volume-up' | 'volume-down'
| 'dpad-up' | 'dpad-down' | 'dpad-left' | 'dpad-right' | 'select'
| 'play-pause' | 'stop' | 'next' | 'previous' | 'rewind' | 'fast-forward'): Promise
+ /** Press a key or a shortcut on a Mac: "escape", "cmd+shift+r". A phone throws. */
+ pressKeys(keys: string): Promise
/** Go back and say where it went; `gesture` swipes in from the left edge instead of the key. */
back(options?: { gesture?: boolean }): Promise<{ foreground?: string; left?: string; title?: string; confirmed: boolean }>
screenLocked(): Promise
diff --git a/clients/javascript/index.js b/clients/javascript/index.js
index 20b822d..57543ab 100644
--- a/clients/javascript/index.js
+++ b/clients/javascript/index.js
@@ -663,10 +663,12 @@ export class Device {
* `{ fingers }` taps with several at once, side by side: 2 for a two-finger
* tap, 3 for three (up to 5). On iOS three fingers can reach the system
* instead of the app — three-finger gestures are undo, redo, copy and paste
- * there.
+ * there. `{ button: 'right' }` is a right-click, which opens a context menu
+ * on a Mac; a phone throws.
*/
- async tap(target, { fingers } = {}) {
+ async tap(target, { fingers, button } = {}) {
const extra = fingers === undefined ? {} : { fingers }
+ if (button !== undefined) extra.button = button
if (typeof target === 'string') {
return void (await this.#text('app_tap', { target, ...extra }))
}
@@ -1476,6 +1478,16 @@ export class Device {
await this.#data('app_press', { button })
}
+ /**
+ * Press a key or a shortcut on a Mac: "escape", "cmd+shift+r". A named key
+ * or one character, after modifiers joined by + (cmd, shift, option,
+ * ctrl). Sent, not confirmed. A phone throws; type text with `type` or
+ * `fill`.
+ */
+ async pressKeys(keys) {
+ await this.#data('app_press', { keys })
+ }
+
/**
* Go back, and say where it went: `foreground` (the app in front
* afterwards), `left` (the app back closed, absent when it stayed in
diff --git a/clients/python/mobium/_device.py b/clients/python/mobium/_device.py
index 7c3042d..c1ea5cd 100644
--- a/clients/python/mobium/_device.py
+++ b/clients/python/mobium/_device.py
@@ -417,15 +417,19 @@ def tap(
x: int | None = None,
y: int | None = None,
fingers: int | None = None,
+ button: str | None = None,
) -> None:
"""Tap a ref, a locator, or a point in device pixels.
fingers taps with several at once, side by side: 2 for a two-finger
tap, 3 for three (up to 5). On iOS three fingers can reach the system
instead of the app — three-finger gestures are undo, redo, copy and
- paste there.
+ paste there. button="right" is a right-click, which opens a context
+ menu on a Mac; a phone raises.
"""
extra = {} if fingers is None else {"fingers": fingers}
+ if button is not None:
+ extra["button"] = button
if target is not None:
self._call("app_tap", {"target": target, **extra})
elif x is not None and y is not None:
@@ -1202,6 +1206,15 @@ def press(self, button: str) -> None:
"""
self._data("app_press", {"button": button})
+ def press_keys(self, keys: str) -> None:
+ """Press a key or a shortcut on a Mac: "escape", "cmd+shift+r".
+
+ A named key or one character, after modifiers joined by + (cmd,
+ shift, option, ctrl). Sent, not confirmed: what a shortcut does is
+ the app's. A phone raises; type text with type or fill.
+ """
+ self._data("app_press", {"keys": keys})
+
def back(self, gesture: bool = False) -> dict:
"""Go back, and say where it went.
diff --git a/cmd/mobium/buttons.go b/cmd/mobium/buttons.go
index e45e265..f2904ea 100644
--- a/cmd/mobium/buttons.go
+++ b/cmd/mobium/buttons.go
@@ -1,12 +1,15 @@
package main
-import "github.com/spf13/cobra"
+import (
+ "github.com/mobiumdev/mobium/internal/agent"
+ "github.com/spf13/cobra"
+)
func newPressCmd() *cobra.Command {
var gesture bool
cmd := &cobra.Command{
- Use: "press ",
- Short: "Press a hardware button",
+ Use: "press ",
+ Short: "Press a hardware button, or a key on a Mac",
Long: "On Android, back is primary navigation — an app that opened a detail\n" +
"screen expects it, and no amount of tapping substitutes for it.\n\n" +
"iOS has no back button by design: navigation back is a per-app\n" +
@@ -21,16 +24,25 @@ func newPressCmd() *cobra.Command {
"focus went, or that it did not move, and select activates what has\n" +
"focus. The media keys go to whichever app holds the media session, and\n" +
"are reported as sent. iOS has none of them.\n\n" +
+ "On a Mac it presses keys: a named key (escape, return, tab, up, f5) or\n" +
+ "one character, after modifiers joined by + (cmd+shift+r), sent as the\n" +
+ "tool's keys. They are sent, not confirmed. A phone refuses keys;\n" +
+ "type text with app_type.\n\n" +
"Any press can move the screen, so refs from the last map are discarded.",
Example: ` mobium press back
mobium press back --gesture
mobium press home
mobium press recents
mobium press dpad-down
- mobium press select`,
+ mobium press select
+ mobium press cmd+shift+r # a shortcut, on a Mac
+ mobium press escape # closes a Mac menu`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
call := map[string]interface{}{"button": args[0]}
+ if agent.PressIsKeys(args[0]) {
+ call = map[string]interface{}{"keys": args[0]}
+ }
if gesture {
call["gesture"] = true
}
diff --git a/cmd/mobium/tap.go b/cmd/mobium/tap.go
index 0102351..fb17f59 100644
--- a/cmd/mobium/tap.go
+++ b/cmd/mobium/tap.go
@@ -14,6 +14,7 @@ import (
// duplicated all of that to change which driver method gets the coordinates.
func newTapCmd() *cobra.Command {
var fingers int
+ var button string
cmd := &cobra.Command{
Use: "tap <@ref | locator | x y>",
Short: "Tap an element or a point",
@@ -21,13 +22,17 @@ func newTapCmd() *cobra.Command {
mobium tap text="Sign In" # tap by visible text
mobium tap testid=submit_btn # tap by resource-id
mobium tap 540 1200 # tap raw device coordinates
- mobium tap @e2 --fingers 2 # a two-finger tap`,
+ mobium tap @e2 --fingers 2 # a two-finger tap
+ mobium tap @e2 --button right # a right-click, on a Mac`,
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
call := map[string]interface{}{}
if cmd.Flags().Changed("fingers") {
call["fingers"] = fingers
}
+ if cmd.Flags().Changed("button") {
+ call["button"] = button
+ }
if len(args) == 2 {
x, err := strconv.Atoi(args[0])
if err != nil {
@@ -46,6 +51,8 @@ func newTapCmd() *cobra.Command {
}
cmd.Flags().IntVar(&fingers, "fingers", 1,
"how many fingers tap at once, side by side (1 to 5)")
+ cmd.Flags().StringVar(&button, "button", "left",
+ "right for a secondary click, which opens a context menu (a Mac only)")
return cmd
}
diff --git a/docs/CHALLENGES.md b/docs/CHALLENGES.md
index 355961a..4903bb4 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
-417 defects, 335 were found only by running against a real device. Eighteen
+419 defects, 337 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,
@@ -9013,6 +9013,37 @@ 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.
+### 418. A click outside an open Mac menu closed it and was reported done
+
+**Found by:** opening MobiumDesk's Probe menu and tapping Increment. The tap
+reported success, the count did not move, and the menu was gone. While a
+menu is open, AppKit takes a click outside it as closing the menu and
+nothing else. The rest of the app stays in the tree with real frames, and
+the hit test names the app's own window, so nothing refused the tap.
+
+**Fixed:** a menu whose frame has a size is open. While one is, `map` lists
+the menu bar and the open menu only, and a target elsewhere is refused,
+naming the menu, with two remedies that work: one of its items, or its title,
+which closes it. Not a point outside it, as on iOS: on a desktop that point
+may lie over another app's window, where a click is refused. A closed menu
+stays in the tree about 0.4 seconds while it animates shut. `desktop.sh`
+asserts the refused tap is not counted.
+
+### 419. An autorelease pool drained on another thread crashed the daemon
+
+**Found by:** `desktop.sh` failing about one run in five, at a different step
+each time, often with "daemon closed the connection without responding".
+The daemon's standard error is thrown away when the CLI starts it, so a
+debugging build sent it to a file. The next failure left a SIGSEGV
+(address 0x10) in the driver's autorelease pool, draining it inside
+`bundleOf`. An autorelease pool belongs to the thread that made it, and Go
+may move a goroutine to another thread between two calls. The two daemon
+drops in 411's work, put down as unexplained, are explained by this.
+
+**Fixed:** the goroutine is held to its thread for the pool's life.
+`desktop.sh` then passed 15 runs in 15 with the daemon's standard error
+logged, and nothing was logged. Before the fix it failed 4 runs in 10.
+
## Findings that were not defects
Worth recording because each one closed off an approach that looked obvious.
diff --git a/docs/FLAGS.md b/docs/FLAGS.md
index 2ef9472..7802c78 100644
--- a/docs/FLAGS.md
+++ b/docs/FLAGS.md
@@ -213,6 +213,7 @@ command mentions them.
| `app_press` | `device` | string | _global_ --device |
| `app_press` | `driver` | string | _global_ --driver |
| `app_press` | `gesture` | boolean | press |
+| `app_press` | `keys` | string | press |
| `app_press_drag` | `device` | string | _global_ --device |
| `app_press_drag` | `driver` | string | _global_ --driver |
| `app_press_drag` | `duration_ms` | integer | press-drag |
@@ -309,6 +310,7 @@ command mentions them.
| `app_swipe` | `x2` | integer | swipe |
| `app_swipe` | `y1` | integer | swipe |
| `app_swipe` | `y2` | integer | swipe |
+| `app_tap` | `button` | string | tap |
| `app_tap` | `device` | string | _global_ --device |
| `app_tap` | `double` | boolean | double-tap |
| `app_tap` | `driver` | string | _global_ --driver |
@@ -428,7 +430,7 @@ arguments and the two global flags.
| `open` | app_open_url | — | url |
| `orientation` | app_orientation | — | orientation |
| `pipe` | — | — | — |
-| `press` | app_press | --gesture | button, gesture |
+| `press` | app_press | --gesture | button, gesture, keys |
| `press-drag` | app_press_drag | --duration-ms --lead-ms | duration_ms, from, hold, lead_ms, to, x1, x2, x3, y1, y2, y3 |
| `press-tap` | app_press_tap | --lead-ms | hold, lead_ms, tap, x1, x2, y1, y2 |
| `record` | app_record | --output | action, path |
@@ -454,7 +456,7 @@ arguments and the two global flags.
| `stop` | — | — | status |
| `storage` | app_storage, app_storage, app_storage | --output | action, state |
| `swipe` | app_swipe | --duration | direction, duration_ms, target, x1, x2, y1, y2 |
-| `tap` | app_tap, app_tap | --fingers | fingers, target, x, y |
+| `tap` | app_tap, app_tap | --button --fingers | button, fingers, target, x, y |
| `terminate` | app_terminate | — | app |
| `test` | — | --config --debug --grep --last-failed --list --no-screenshots --open --output --project --reporter --retries --timeout --trace --ui --ui-port --workers | list |
| `text` | app_text | — | target |
diff --git a/docs/RELEASE-CHECKLIST.md b/docs/RELEASE-CHECKLIST.md
index c42a517..90519f2 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: 335 of 417 were found only by
+serious defects in this project have come from: 337 of 419 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 a368a01..fc51475 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -9,10 +9,13 @@ this is what is not.
- **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.
+ 1. ~~Scrolling and `scroll-to`.~~ Done 2026-11-27: a swipe is the scroll
+ wheel at its start point, and `scroll-to` reaches a row out of view
+ both ways.
+ 2. ~~Menus~~ done 2026-11-27: the menu bar's menus (CHALLENGES 418), a
+ context menu by `tap --button right`, and keys and shortcuts by
+ `press` (`escape`, `cmd+shift+r`). Left: hover. Recording as code
+ writes neither a right-click nor several fingers yet: it emits a tap.
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.
@@ -21,9 +24,8 @@ this is what is not.
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.
+ did); and a launch of MobiumDesk answered no accessibility (417, twice).
+ The daemon closing a connection without answering was a crash, 419.
- **Found reviewing the docs evaluation's golden set** (written down
2026-10-12, read from the code, not yet run on a device):
diff --git a/docs/api/flags.json b/docs/api/flags.json
index 236629a..ae83d70 100644
--- a/docs/api/flags.json
+++ b/docs/api/flags.json
@@ -1586,6 +1586,14 @@
"press"
]
},
+ {
+ "tool": "app_press",
+ "arg": "keys",
+ "type": "string",
+ "setBy": [
+ "press"
+ ]
+ },
{
"tool": "app_press_drag",
"arg": "device",
@@ -2389,6 +2397,14 @@
"swipe"
]
},
+ {
+ "tool": "app_tap",
+ "arg": "button",
+ "type": "string",
+ "setBy": [
+ "tap"
+ ]
+ },
{
"tool": "app_tap",
"arg": "device",
@@ -3501,7 +3517,8 @@
],
"sends": [
"button",
- "gesture"
+ "gesture",
+ "keys"
]
},
{
@@ -3803,9 +3820,11 @@
"app_tap"
],
"flags": [
+ "--button",
"--fingers"
],
"sends": [
+ "button",
"fingers",
"target",
"x",
diff --git a/docs/checks/README.md b/docs/checks/README.md
index aff6d57..1e3e6f0 100644
--- a/docs/checks/README.md
+++ b/docs/checks/README.md
@@ -66,7 +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) |
+| [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; Row 35 scrolled to with the wheel and back up to Row 2; the Probe menu's item resetting the counter, a tap outside the open menu refused and not counted, and its title closing it; a right-click opening Increment's context menu, a tap behind it refused, Add Ten counted and escape closing it; `cmd+shift+r` resetting the counter; the front window's screenshot. Takes `macos`. Passed 2026-11-27 on a macOS 26.6.2 guest, about 30 seconds: 23 runs in 23, 15 with the daemon's standard error logged and 8 as committed. Before CHALLENGES 419 was fixed it failed 4 runs in 10; before that, 2 runs in 22 failed on a launch of the app that answered no accessibility (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
index 48d5ac3..a0ca5fd 100644
--- a/docs/checks/desktop-app.swift
+++ b/docs/checks/desktop-app.swift
@@ -1,5 +1,5 @@
// 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
+// a counter with a context menu, a sheet, a 40-row list and a menu command. desktop.sh builds it
// with swiftc; it needs no Xcode project.
import SwiftUI
@@ -36,6 +36,9 @@ struct Root: View {
Button("Show Sheet") { showSheet = true }.accessibilityIdentifier("show-sheet")
HStack {
Button("Increment") { count += 1 }.accessibilityIdentifier("increment")
+ .contextMenu {
+ Button("Add Ten") { count += 10 }.accessibilityIdentifier("add-ten")
+ }
Text("Count: \(count)").accessibilityIdentifier("count")
}
List(1...40, id: \.self) { i in
diff --git a/docs/checks/desktop.sh b/docs/checks/desktop.sh
index aef6da7..56549df 100755
--- a/docs/checks/desktop.sh
+++ b/docs/checks/desktop.sh
@@ -11,6 +11,13 @@
# - 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 row out of view is scrolled to with the wheel, down and back up,
+# and a tap lands on it;
+# - an open menu's item resets the counter, a tap outside the menu is
+# refused and not counted, and its title closes it (CHALLENGES 418);
+# - a right-click opens Increment's context menu, a tap behind it is
+# refused and not counted, its item adds ten, and escape closes it;
+# - cmd+shift+r, the Probe menu's shortcut, resets the counter;
# - a screenshot is the window's PNG.
#
# The Mac MUST be a virtual machine, or MOBIUM_DESKTOP_HOST=1 must be set:
@@ -30,6 +37,12 @@ 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'; }
+# want_count N MESSAGE waits for the app to show Count: N. An action returns
+# when it is sent, before SwiftUI redraws.
+want_count() {
+ $M wait "text=Count: $1" --timeout 5s >/dev/null || fail "$2 (Count is $(count), want $1):
+$($M map 2>&1)"
+}
WORK="$CHECK_TMP"
BUNDLE="$WORK/MobiumDesk.app"
@@ -68,7 +81,7 @@ 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)"
+want_count $((before + 2)) "two taps on Increment did not count"
row "tap" "two taps, counted by the app"
$M fill testid=username mobium >/dev/null || fail "fill username was not confirmed"
@@ -91,7 +104,7 @@ echo "$out" | grep -qF '"A sheet"' || fail "the refusal does not name the sheet:
$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)"
+want_count "$before" "a refused tap moved Count"
row "sheet" "a tap under it refused and not counted; app_alert read and answered it"
before=$(count)
@@ -101,9 +114,53 @@ $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)"
+want_count $((before + 1)) "the tap after the rule did not count"
row "rule" "a dialog rule answered the sheet on the way, and the tap counted"
+$M map | grep -qF "Row 35" && fail "Row 35 is in map before any scroll"
+out=$($M scroll-to "text=Row 35" 2>&1) || fail "scroll-to did not bring Row 35 into view: $out
+$($M map 2>&1)"
+$M map | grep -qF "Row 35 (button)" || fail "Row 35 is not in map after scroll-to"
+$M tap "text=Row 35" >/dev/null || fail "a tap on Row 35 was refused"
+out=$($M scroll-to "text=Row 2" --direction up 2>&1) || fail "scroll-to up did not bring Row 2 back: $out"
+$M map | grep -qF "Row 35" && fail "Row 35 is still in map after scrolling back up"
+row "scroll" "the wheel brought Row 35 in and Row 2 back, and a tap landed"
+
+[ "$(count)" != 0 ] || $M tap testid=increment >/dev/null
+before=$(count)
+[ "$before" != 0 ] || fail "no count to reset"
+$M tap label=Probe >/dev/null
+$M wait "label=Reset Counter" --timeout 5s >/dev/null || fail "the Probe menu did not open"
+if out=$($M tap testid=increment 2>&1); then fail "a tap outside the open menu was not refused: $out"; fi
+echo "$out" | grep -qF '"Probe" menu is open' || fail "the refusal does not name the menu: $out"
+$M tap "label=Reset Counter" >/dev/null || fail "Reset Counter was refused"
+want_count 0 "Reset Counter did not reset Count from $before"
+$M tap label=Probe >/dev/null
+$M wait "label=Reset Counter" --timeout 5s >/dev/null || fail "the Probe menu did not open again"
+$M tap label=Probe >/dev/null
+$M wait "label=Reset Counter" --for hidden --timeout 5s >/dev/null || fail "the menu's title did not close it"
+$M tap testid=increment >/dev/null
+want_count 1 "a tap after the menu closed did not count"
+row "menu" "its item acted, a tap outside it refused, and its title closed it"
+
+before=$(count)
+$M tap testid=increment --button right >/dev/null || fail "the right-click was refused"
+$M wait "label=Add Ten" --timeout 5s >/dev/null || fail "the context menu did not open"
+if out=$($M tap testid=show-sheet 2>&1); then fail "a tap behind the context menu was not refused: $out"; fi
+echo "$out" | grep -qF "context menu is open" || fail "the refusal does not say a context menu is open: $out"
+$M tap "label=Add Ten" >/dev/null || fail "Add Ten was refused"
+want_count $((before + 10)) "Add Ten did not add ten to $before"
+$M tap testid=increment --button right >/dev/null
+$M wait "label=Add Ten" --timeout 5s >/dev/null || fail "the context menu did not open again"
+$M press escape >/dev/null || fail "escape was refused"
+$M wait "label=Add Ten" --for hidden --timeout 5s >/dev/null || fail "escape did not close the context menu"
+row "context" "a right-click opened it, a tap behind it refused, Add Ten counted, escape closed it"
+
+[ "$(count)" != 0 ] || fail "no count for the shortcut to reset"
+$M press cmd+shift+r >/dev/null || fail "cmd+shift+r was refused"
+want_count 0 "cmd+shift+r did not reset the counter"
+row "shortcut" "cmd+shift+r, the menu's shortcut, reset the counter"
+
$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"
diff --git a/internal/agent/buttons.go b/internal/agent/buttons.go
index e03cbed..67f618b 100644
--- a/internal/agent/buttons.go
+++ b/internal/agent/buttons.go
@@ -24,12 +24,30 @@ func (h *Handlers) press(ctx context.Context, args map[string]interface{}) (*Too
}
func (h *Handlers) pressOn(ctx context.Context, s *session, args map[string]interface{}) (*ToolsCallResult, error) {
+ if keys := strings.TrimSpace(stringArg(args, "keys")); keys != "" {
+ if stringArg(args, "button") != "" {
+ return nil, mobiumerr.New(mobiumerr.InvalidArgument, "give button or keys, not both")
+ }
+ k, ok := mobiumdriver.ParseKeys(keys)
+ if !ok {
+ return nil, mobiumerr.New(mobiumerr.InvalidArgument, "%q is not a key: a named key (%s) or one "+
+ "character, after modifiers joined by + (cmd, shift, option, ctrl), such as cmd+shift+r",
+ keys, mobiumdriver.KeyNames())
+ }
+ return h.pressKeys(ctx, s, k, args)
+ }
+ button := strings.ToLower(strings.TrimSpace(stringArg(args, "button")))
+ if _, isKeys := s.driver.(mobiumdriver.Keys); isKeys && button != "" && !isButtonName(button) {
+ return nil, mobiumerr.New(mobiumerr.InvalidArgument, "%q is neither a button nor a key: a key is a "+
+ "named key (%s) or one character, after modifiers joined by + (cmd, shift, option, ctrl)",
+ button, mobiumdriver.KeyNames()).
+ WithRemedy("app_press with keys, such as escape or cmd+shift+r")
+ }
ctrl, ok := mobiumdriver.AsButtons(s.driver)
if !ok {
return nil, cannot(s, mobiumdriver.CapButtons, "press hardware buttons")
}
- button := strings.ToLower(strings.TrimSpace(stringArg(args, "button")))
if button == "" {
return nil, mobiumerr.New(mobiumerr.InvalidArgument, "app_press needs a button — this device has %s",
mobiumdriver.ButtonNames(ctrl.SupportedButtons()))
@@ -47,8 +65,12 @@ func (h *Handlers) pressOn(ctx context.Context, s *session, args map[string]inte
}
}
if !known {
- return nil, mobiumerr.New(mobiumerr.InvalidArgument, "there is no %q button — mobium knows %s",
+ err := mobiumerr.New(mobiumerr.InvalidArgument, "there is no %q button — mobium knows %s",
button, mobiumdriver.ButtonNames(mobiumdriver.AllButtons()))
+ if _, isKey := mobiumdriver.ParseKeys(button); isKey {
+ err = err.WithRemedy("it is a key: give it as keys, which a Mac presses")
+ }
+ return nil, err
}
// Home and back have outcomes worth checking. Home brings the launcher
@@ -292,3 +314,43 @@ type LockView struct {
Previous *bool `json:"previous,omitempty"`
Device string `json:"device"`
}
+
+// pressKeys is app_press for a key or a chord, on a device with a keyboard.
+// It is sent, not confirmed: a shortcut's effect is the app's own.
+func (h *Handlers) pressKeys(ctx context.Context, s *session, k mobiumdriver.KeyCombo, args map[string]interface{}) (*ToolsCallResult, error) {
+ if boolArg(args, "gesture") {
+ return nil, mobiumerr.New(mobiumerr.InvalidArgument, "only back has a gesture; press %s without one", k)
+ }
+ kd, ok := s.driver.(mobiumdriver.Keys)
+ if !ok {
+ return nil, mobiumerr.New(mobiumerr.Unsupported, "%q is a key, and only a Mac has a keyboard Mobium "+
+ "presses keys on", k.String()).
+ WithRemedy("app_type to type text, or app_press with a button this device has")
+ }
+ if err := kd.PressKeys(ctx, k); err != nil {
+ return nil, err
+ }
+ delete(h.refs, s.dev.Serial)
+ return Result("pressed "+k.String(), PressView{Button: k.String(), Device: s.dev.Serial}), nil
+}
+
+func isButtonName(s string) bool {
+ for _, b := range mobiumdriver.AllButtons() {
+ if b == s {
+ return true
+ }
+ }
+ return false
+}
+
+// PressIsKeys reports whether what a person typed after `press` is keys
+// rather than a button. A name that is both, home, is the button.
+func PressIsKeys(arg string) bool {
+ for _, b := range mobiumdriver.AllButtons() {
+ if strings.EqualFold(b, strings.TrimSpace(arg)) {
+ return false
+ }
+ }
+ _, ok := mobiumdriver.ParseKeys(arg)
+ return ok
+}
diff --git a/internal/agent/handlers.go b/internal/agent/handlers.go
index 0af81d6..caabb57 100644
--- a/internal/agent/handlers.go
+++ b/internal/agent/handlers.go
@@ -888,6 +888,17 @@ func (h *Handlers) tapOn(ctx context.Context, s *session, args map[string]interf
return nil, mobiumerr.New(mobiumerr.InvalidArgument, "a double tap with several fingers is not supported — "+
"give double or fingers, not both")
}
+ button := strings.ToLower(strings.TrimSpace(stringArg(args, "button")))
+ switch button {
+ case "", "left":
+ case "right":
+ if fingers != 1 || boolArg(args, "double") {
+ return nil, mobiumerr.New(mobiumerr.InvalidArgument, "a right-click is one click: give button right "+
+ "without double or fingers")
+ }
+ default:
+ return nil, mobiumerr.New(mobiumerr.InvalidArgument, "button is \"left\" or \"right\", got %q", button)
+ }
// touch is the one line that differs, resolved once so every path below
// reads the same.
@@ -912,6 +923,17 @@ func (h *Handlers) tapOn(ctx context.Context, s *session, args map[string]interf
verb, action = "double-tapped", "double_tap"
}
+ if button == "right" {
+ rt, ok := driver.(mobiumdriver.RightTapper)
+ if !ok {
+ return nil, mobiumerr.New(mobiumerr.Unsupported, "a right-click is a Mac's: a touch screen has one "+
+ "kind of touch, and holds it for a context menu").
+ WithRemedy("app_long_press opens a context menu on a phone")
+ }
+ touch = rt.RightTap
+ verb, action = "right-clicked", "right_click"
+ }
+
// Several fingers at once is this tool too, for the reason a double tap
// is: everything but the touch itself is the same. The fingers land side
// by side about the point a one-finger tap would have used.
@@ -1380,6 +1402,27 @@ func dialogOver(dialog string, loc uitree.Locator, covered bool) error {
WithDetail("dialog", dialog)
}
+// menuOver refuses a target outside an open Mac menu: a click there only
+// closes the menu, and was reported done (CHALLENGES 418). The menu's title
+// closes it when clicked again, which a point outside it may not: it can
+// lie over another app's window, which a click is refused on.
+func menuOver(loc uitree.Locator, menu *uitree.Node) error {
+ title, what := "", "a context menu is open"
+ if menu.Parent != nil && menu.Parent.Class == "AXMenuBarItem" {
+ title = menu.Parent.Label
+ what = fmt.Sprintf("the %q menu is open", title)
+ }
+ remedy := "app_tap one of the menu's items from app_map, or app_press keys escape to close it"
+ if title != "" {
+ remedy += fmt.Sprintf(", or app_tap label=%q", title)
+ }
+ return failedCheck(mobiumerr.ElementNotReachable, loc, checkReceivesEvents,
+ what+", and a click outside it only closes it", "choose one of its items, or close it first").
+ WithRemedy(remedy).
+ WithDetail("locator", loc.String()).
+ WithDetail("menu", title)
+}
+
// 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 {
@@ -1624,6 +1667,9 @@ func pickOne(loc uitree.Locator, tree *uitree.Tree) (*uitree.Node, error) {
if d := tree.Dialog(); d != nil && !matches[0].Within(d) {
return nil, dialogOver(dialogName(d), loc, true)
}
+ if m := tree.OpenMenu(); m != nil && !uitree.InMenuBar(matches[0]) && !matches[0].Within(m) {
+ return nil, menuOver(loc, m)
+ }
// 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 —
// so a tap landed on a key and reported success. Refused only where
diff --git a/internal/agent/keys_test.go b/internal/agent/keys_test.go
new file mode 100644
index 0000000..3d7e36a
--- /dev/null
+++ b/internal/agent/keys_test.go
@@ -0,0 +1,55 @@
+package agent
+
+import (
+ "context"
+ "testing"
+
+ "github.com/mobiumdev/mobium/internal/mobiumerr"
+)
+
+// A phone has no keyboard Mobium presses and no secondary click: both are
+// refused, with a remedy that works there, and nothing is touched.
+func TestKeysAndRightClickAreRefusedOnAPhone(t *testing.T) {
+ h, s, f := withFake(t, screen(t, "Sign In"))
+ ctx := context.Background()
+
+ _, err := h.pressOn(ctx, s, map[string]interface{}{"keys": "cmd+shift+r"})
+ if mobiumerr.CodeOf(err) != mobiumerr.Unsupported {
+ t.Fatalf("keys on a phone: err = %v, want unsupported", err)
+ }
+ if e, _ := mobiumerr.As(err); e.Remedy == "" {
+ t.Error("the refusal of keys names no remedy")
+ }
+
+ _, err = tap(h, s, map[string]interface{}{"target": "text=Sign In", "button": "right"})
+ if mobiumerr.CodeOf(err) != mobiumerr.Unsupported {
+ t.Fatalf("a right-click on a phone: err = %v, want unsupported", err)
+ }
+ if len(f.tapped) != 0 {
+ t.Errorf("a refused right-click touched %v", f.tapped)
+ }
+
+ _, err = tap(h, s, map[string]interface{}{"target": "text=Sign In", "button": "middle"})
+ if mobiumerr.CodeOf(err) != mobiumerr.InvalidArgument {
+ t.Errorf("button middle: err = %v, want invalid_argument", err)
+ }
+ _, err = h.pressOn(ctx, s, map[string]interface{}{"keys": "hyper+q"})
+ if mobiumerr.CodeOf(err) != mobiumerr.InvalidArgument {
+ t.Errorf("keys hyper+q: err = %v, want invalid_argument", err)
+ }
+ _, err = h.pressOn(ctx, s, map[string]interface{}{"keys": "escape", "button": "back"})
+ if mobiumerr.CodeOf(err) != mobiumerr.InvalidArgument {
+ t.Errorf("keys and button together: err = %v, want invalid_argument", err)
+ }
+}
+
+func TestPressIsKeys(t *testing.T) {
+ for in, want := range map[string]bool{
+ "back": false, "home": false, "dpad-up": false, "escape": true, "cmd+shift+r": true,
+ "cmd+home": true, "nonsense": false,
+ } {
+ if got := PressIsKeys(in); got != want {
+ t.Errorf("PressIsKeys(%q) = %v, want %v", in, got, want)
+ }
+ }
+}
diff --git a/internal/agent/schema.go b/internal/agent/schema.go
index aa9c154..c0d2496 100644
--- a/internal/agent/schema.go
+++ b/internal/agent/schema.go
@@ -150,6 +150,13 @@ func GetToolSchemas() []Tool {
"reach the system instead of the app: three-finger gestures " +
"are undo, redo, copy and paste there. Not with double.",
},
+ "button": map[string]interface{}{
+ "type": "string",
+ "description": "\"left\" or \"right\". \"right\" sends a secondary click, which opens a " +
+ "context menu: a Mac only. A phone refuses it; app_long_press " +
+ "opens a context menu there. Defaults to \"left\". Not with " +
+ "double or fingers.",
+ },
}),
"additionalProperties": false,
},
@@ -1425,18 +1432,29 @@ func GetToolSchemas() []Tool {
"did**: whether it left the app and what is in front now, and on iOS " +
"what the navigation bar says — the difference between going back a " +
"screen and closing the app. Home reports the launcher coming forward. " +
- "Any press can move the screen, so the refs from the last app_map are " +
- "discarded; map again before acting.",
+ "**On a Mac, keys presses a key or a shortcut** instead of a button: " +
+ "\"escape\", \"cmd+shift+r\". Keys are sent, not confirmed: what a " +
+ "shortcut does is the app's. A phone refuses keys; type text with " +
+ "app_type. Any press can move the screen, so the refs from the last " +
+ "app_map are discarded; map again before acting.",
InputSchema: map[string]interface{}{
"type": "object",
"properties": withDevice(map[string]interface{}{
"button": map[string]interface{}{
"type": "string",
- "description": "Which button. Refused with the list of what this platform has.",
+ "description": "Which button. Refused with the list of what this platform has. Not with keys.",
"enum": []string{"back", "home", "recents", "volume-up", "volume-down",
"dpad-up", "dpad-down", "dpad-left", "dpad-right", "select",
"play-pause", "stop", "next", "previous", "rewind", "fast-forward"},
},
+ "keys": map[string]interface{}{
+ "type": "string",
+ "description": "On a Mac, a key to press instead of a button: a named key " +
+ "(escape, return, tab, space, delete, up, down, left, right, page-up, " +
+ "page-down, home, end, f1 to f12) or one character, after modifiers " +
+ "joined by + (cmd, shift, option, ctrl) — \"cmd+shift+r\", \"cmd+,\". " +
+ "Not with button.",
+ },
"gesture": map[string]interface{}{
"type": "boolean",
"description": "Back only: a swipe in from the left edge instead of the key. " +
@@ -1444,7 +1462,6 @@ func GetToolSchemas() []Tool {
"refused on an Android device using button navigation.",
},
}),
- "required": []string{"button"},
"additionalProperties": false,
},
},
diff --git a/internal/mobiumdriver/keys.go b/internal/mobiumdriver/keys.go
new file mode 100644
index 0000000..e1175ff
--- /dev/null
+++ b/internal/mobiumdriver/keys.go
@@ -0,0 +1,154 @@
+package mobiumdriver
+
+import (
+ "context"
+ "sort"
+ "strings"
+
+ "github.com/mobiumdev/mobium/internal/mobiumerr"
+)
+
+// Keys is implemented by backends with a keyboard to press keys on: a Mac.
+// A key is a named key or one character, after modifiers joined by "+":
+// "escape", "cmd+shift+r". Text is typed with app_type, not pressed.
+type Keys interface {
+ PressKeys(ctx context.Context, keys KeyCombo) error
+}
+
+// RightTapper is implemented by backends with a secondary click: a Mac. A
+// touch screen holds a touch for a context menu instead.
+type RightTapper interface {
+ RightTap(ctx context.Context, x, y int) error
+}
+
+// KeyCombo is a parsed chord: its modifiers and the one key they modify.
+type KeyCombo struct {
+ Mods []string // "cmd", "shift", "option", "ctrl", in that order
+ Key string // a named key, or one character
+}
+
+// String is the chord as it is written.
+func (k KeyCombo) String() string {
+ return strings.Join(append(append([]string(nil), k.Mods...), k.Key), "+")
+}
+
+var keyModifiers = map[string]string{
+ "cmd": "cmd", "command": "cmd",
+ "shift": "shift",
+ "option": "option", "opt": "option", "alt": "option",
+ "ctrl": "ctrl", "control": "ctrl",
+}
+
+var modifierOrder = []string{"cmd", "shift", "option", "ctrl"}
+
+// NamedKeys are the keys pressed by name rather than by their character.
+var NamedKeys = []string{
+ "escape", "return", "tab", "space", "delete", "forward-delete",
+ "up", "down", "left", "right", "page-up", "page-down", "home", "end",
+ "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12",
+}
+
+var keyAliases = map[string]string{"esc": "escape", "enter": "return", "backspace": "delete", "del": "delete"}
+
+// ParseKeys reads a chord. ok is false for anything that is not one: a
+// hardware button's name stays a button, and is not read as a key unless
+// a modifier comes with it.
+func ParseKeys(s string) (KeyCombo, bool) {
+ parts := strings.Split(strings.ToLower(strings.TrimSpace(s)), "+")
+ if len(parts) == 0 {
+ return KeyCombo{}, false
+ }
+ key := parts[len(parts)-1]
+ if key == "" && len(parts) >= 2 && parts[len(parts)-2] == "" {
+ key = "+" // "cmd++" presses the plus key
+ parts = parts[:len(parts)-1]
+ }
+ held := map[string]bool{}
+ for _, p := range parts[:len(parts)-1] {
+ m, ok := keyModifiers[p]
+ if !ok || held[m] {
+ return KeyCombo{}, false
+ }
+ held[m] = true
+ }
+ if a, ok := keyAliases[key]; ok {
+ key = a
+ }
+ named := false
+ for _, n := range NamedKeys {
+ named = named || n == key
+ }
+ if !named && len([]rune(key)) != 1 {
+ return KeyCombo{}, false
+ }
+ // "home" alone is the hardware button on a phone.
+ if len(held) == 0 && isButton(key) {
+ return KeyCombo{}, false
+ }
+ var mods []string
+ for _, m := range modifierOrder {
+ if held[m] {
+ mods = append(mods, m)
+ }
+ }
+ return KeyCombo{Mods: mods, Key: key}, true
+}
+
+func isButton(s string) bool {
+ for _, b := range AllButtons() {
+ if b == s {
+ return true
+ }
+ }
+ return false
+}
+
+// KeyNames lists the named keys for an error message.
+func KeyNames() string {
+ out := append([]string(nil), NamedKeys...)
+ sort.Strings(out)
+ return strings.Join(out, ", ")
+}
+
+// macKeyCodes are the virtual key codes of a US keyboard's keys. A shortcut
+// is matched by the character its key makes, so another layout may need a
+// different key for the same character.
+var macKeyCodes = map[string]uint16{
+ "a": 0x00, "s": 0x01, "d": 0x02, "f": 0x03, "h": 0x04, "g": 0x05, "z": 0x06, "x": 0x07,
+ "c": 0x08, "v": 0x09, "b": 0x0B, "q": 0x0C, "w": 0x0D, "e": 0x0E, "r": 0x0F, "y": 0x10,
+ "t": 0x11, "1": 0x12, "2": 0x13, "3": 0x14, "4": 0x15, "6": 0x16, "5": 0x17, "=": 0x18,
+ "9": 0x19, "7": 0x1A, "-": 0x1B, "8": 0x1C, "0": 0x1D, "]": 0x1E, "o": 0x1F, "u": 0x20,
+ "[": 0x21, "i": 0x22, "p": 0x23, "l": 0x25, "j": 0x26, "'": 0x27, "k": 0x28, ";": 0x29,
+ "\\": 0x2A, ",": 0x2B, "/": 0x2C, "n": 0x2D, "m": 0x2E, ".": 0x2F, "`": 0x32,
+ "return": 0x24, "tab": 0x30, "space": 0x31, "delete": 0x33, "escape": 0x35,
+ "forward-delete": 0x75, "home": 0x73, "end": 0x77, "page-up": 0x74, "page-down": 0x79,
+ "left": 0x7B, "right": 0x7C, "down": 0x7D, "up": 0x7E,
+ "f1": 0x7A, "f2": 0x78, "f3": 0x63, "f4": 0x76, "f5": 0x60, "f6": 0x61, "f7": 0x62,
+ "f8": 0x64, "f9": 0x65, "f10": 0x6D, "f11": 0x67, "f12": 0x6F,
+}
+
+// macShifted are characters a US keyboard makes with shift held.
+var macShifted = map[string]string{
+ "!": "1", "@": "2", "#": "3", "$": "4", "%": "5", "^": "6", "&": "7", "*": "8", "(": "9", ")": "0",
+ "_": "-", "+": "=", "{": "[", "}": "]", "|": "\\", ":": ";", "\"": "'", "<": ",", ">": ".", "?": "/", "~": "`",
+}
+
+var macModFlags = map[string]uint64{"cmd": 0x100000, "shift": 0x20000, "option": 0x80000, "ctrl": 0x40000}
+
+// macKey is the key code and modifier flags for a chord on a US keyboard.
+func macKey(k KeyCombo) (uint16, uint64, error) {
+ var flags uint64
+ for _, m := range k.Mods {
+ flags |= macModFlags[m]
+ }
+ key := k.Key
+ if base, ok := macShifted[key]; ok {
+ key, flags = base, flags|macModFlags["shift"]
+ }
+ code, ok := macKeyCodes[key]
+ if !ok {
+ return 0, 0, mobiumerr.New(mobiumerr.InvalidArgument, "%q has no key on a US keyboard; type it with "+
+ "app_type, or press a named key: %s", k.Key, KeyNames())
+ }
+ return code, flags, nil
+}
diff --git a/internal/mobiumdriver/keys_test.go b/internal/mobiumdriver/keys_test.go
new file mode 100644
index 0000000..4247886
--- /dev/null
+++ b/internal/mobiumdriver/keys_test.go
@@ -0,0 +1,48 @@
+package mobiumdriver
+
+import "testing"
+
+func TestParseKeys(t *testing.T) {
+ for _, c := range []struct {
+ in string
+ want string
+ ok bool
+ }{
+ {"escape", "escape", true},
+ {"Esc", "escape", true},
+ {"cmd+shift+r", "cmd+shift+r", true},
+ {"Shift+Command+R", "cmd+shift+r", true},
+ {"ctrl+alt+delete", "option+ctrl+delete", true},
+ {"cmd++", "cmd++", true},
+ {"cmd+,", "cmd+,", true},
+ {"a", "a", true},
+ {"home", "", false}, // the hardware button, not the key
+ {"cmd+home", "cmd+home", true},
+ {"back", "", false},
+ {"cmd+shift", "", false}, // no key
+ {"cmd+cmd+r", "", false},
+ {"hyper+r", "", false},
+ {"enterr", "", false},
+ } {
+ k, ok := ParseKeys(c.in)
+ if ok != c.ok || (ok && k.String() != c.want) {
+ t.Errorf("ParseKeys(%q) = %q, %v; want %q, %v", c.in, k.String(), ok, c.want, c.ok)
+ }
+ }
+}
+
+func TestMacKey(t *testing.T) {
+ k, _ := ParseKeys("cmd+shift+r")
+ code, flags, err := macKey(k)
+ if err != nil || code != 0x0F || flags != 0x100000|0x20000 {
+ t.Errorf("cmd+shift+r = %#x, %#x, %v", code, flags, err)
+ }
+ k, _ = ParseKeys("cmd+?")
+ if code, flags, err := macKey(k); err != nil || code != 0x2C || flags != 0x100000|0x20000 {
+ t.Errorf("cmd+? = %#x, %#x, %v; want the / key with shift", code, flags, err)
+ }
+ k, _ = ParseKeys("é")
+ if _, _, err := macKey(k); err == nil {
+ t.Error("é has no key on a US keyboard and was pressed")
+ }
+}
diff --git a/internal/mobiumdriver/macos.go b/internal/mobiumdriver/macos.go
index 1a0079f..d09b4c3 100644
--- a/internal/mobiumdriver/macos.go
+++ b/internal/mobiumdriver/macos.go
@@ -25,6 +25,11 @@ type macSystem interface {
// 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
+ RightClick(x, y float64) error
+ // Wheel scrolls at a point by dx, dy points, in steps over d.
+ Wheel(x, y, dx, dy float64, d time.Duration) error
+ // Press holds the left button at a point for d.
+ Press(x, y float64, d time.Duration) error
// Key sends one key with modifiers; text sends characters to the focus.
Key(code uint16, flags uint64) error
Text(s string) error
@@ -124,23 +129,42 @@ func (m *Mac) Screenshot(context.Context) ([]byte, error) {
// 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 {
+ px, py, err := m.reach(x, y)
+ if err != nil {
+ return err
+ }
+ return m.sys.Click(px, py)
+}
+
+// RightTap is a secondary click, which opens a context menu.
+func (m *Mac) RightTap(_ context.Context, x, y int) error {
+ px, py, err := m.reach(x, y)
+ if err != nil {
+ return err
+ }
+ return m.sys.RightClick(px, py)
+}
+
+// reach converts a point to points and refuses it when a click there would
+// reach another app's window.
+func (m *Mac) reach(x, y int) (float64, float64, error) {
s := m.sys.Scale()
px, py := float64(x)/s, float64(y)/s
front, bundle, err := m.sys.Front()
if err != nil {
- return err
+ return 0, 0, err
}
pid, role, err := m.sys.ElementAt(px, py)
if err != nil {
- return err
+ return 0, 0, err
}
if pid != front {
- return mobiumerr.New(mobiumerr.ElementNotReachable, "a click at (%d, %d) would reach another app's %s, "+
+ return 0, 0, 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)
+ return px, py, nil
}
const (
@@ -333,3 +357,30 @@ 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")
}
+
+// wheelSign turns a finger's travel into a wheel delta that moves the content
+// the same way, as a swipe on a phone does.
+const wheelSign = 1
+
+// Swipe scrolls with the wheel at the start point: a drag on a Mac selects,
+// it does not scroll. Coordinates are pixels.
+func (m *Mac) Swipe(_ context.Context, x1, y1, x2, y2 int, d time.Duration) error {
+ s := m.sys.Scale()
+ dx, dy := float64(x2-x1)/s, float64(y2-y1)/s
+ return m.sys.Wheel(float64(x1)/s, float64(y1)/s, wheelSign*dx, wheelSign*dy, d)
+}
+
+// LongPress holds the left button.
+func (m *Mac) LongPress(_ context.Context, x, y int, d time.Duration) error {
+ s := m.sys.Scale()
+ return m.sys.Press(float64(x)/s, float64(y)/s, d)
+}
+
+// PressKeys presses a key, with its modifiers held as keys of their own.
+func (m *Mac) PressKeys(_ context.Context, k KeyCombo) error {
+ code, flags, err := macKey(k)
+ if err != nil {
+ return err
+ }
+ return m.sys.Key(code, flags)
+}
diff --git a/internal/mobiumdriver/macos_darwin.go b/internal/mobiumdriver/macos_darwin.go
index 854fefb..c526960 100644
--- a/internal/mobiumdriver/macos_darwin.go
+++ b/internal/mobiumdriver/macos_darwin.go
@@ -4,6 +4,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "runtime"
"strconv"
"sync"
"time"
@@ -65,6 +66,7 @@ type darwinMac struct {
cgEventSetIntegerValueField func(ev uintptr, field uint32, v int64)
cgEventSetFlags func(ev uintptr, flags uint64)
cgEventPost func(tap uint32, ev uintptr)
+ cgEventCreateScrollWheelEvent2 func(src uintptr, units uint32, count uint32, w1, w2, w3 int32) uintptr
cgPreflightScreenCaptureAccess func() bool
}
@@ -136,6 +138,7 @@ func (d *darwinMac) load() error {
{as, &d.cgEventSetIntegerValueField, "CGEventSetIntegerValueField"},
{as, &d.cgEventSetFlags, "CGEventSetFlags"},
{as, &d.cgEventPost, "CGEventPost"},
+ {as, &d.cgEventCreateScrollWheelEvent2, "CGEventCreateScrollWheelEvent2"},
{as, &d.cgPreflightScreenCaptureAccess, "CGPreflightScreenCaptureAccess"},
} {
purego.RegisterLibFunc(f.fn, f.lib, f.name)
@@ -280,8 +283,12 @@ func (d *darwinMac) lock() error {
}
// pool runs f inside an autorelease pool: the daemon has no run loop to
-// drain one, and every Objective-C call below autoreleases.
+// drain one, and every Objective-C call below autoreleases. A pool belongs
+// to the thread that made it, and Go may move a goroutine between threads:
+// a pool drained on another thread crashed the daemon (CHALLENGES 419).
func pool(f func()) {
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
p := objc.ID(objc.GetClass("NSAutoreleasePool")).Send(objc.RegisterName("new"))
defer p.Send(objc.RegisterName("drain"))
f()
@@ -424,6 +431,62 @@ var macModifiers = []struct {
// 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.
+// RightClick sends a secondary click at a point.
+func (d *darwinMac) RightClick(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{3, 4} { // rightMouseDown, rightMouseUp
+ ev := d.cgEventCreateMouseEvent(0, t, p, 1) // kCGMouseButtonRight
+ d.cgEventSetIntegerValueField(ev, 1, 1)
+ d.post(ev)
+ time.Sleep(50 * time.Millisecond)
+ }
+ return nil
+}
+
+// Wheel moves the pointer to the point, then scrolls by pixels in steps.
+func (d *darwinMac) Wheel(x, y, dx, dy float64, dur time.Duration) error {
+ if err := d.lock(); err != nil {
+ return err
+ }
+ defer d.mu.Unlock()
+ d.post(d.cgEventCreateMouseEvent(0, 5, cgPoint{x, y}, 0)) // mouseMoved
+ time.Sleep(30 * time.Millisecond)
+ const steps = 10
+ var sentX, sentY int32
+ for i := 1; i <= steps; i++ {
+ wantX, wantY := int32(dx*float64(i)/steps), int32(dy*float64(i)/steps)
+ d.post(d.cgEventCreateScrollWheelEvent2(0, 0, 2, wantY-sentY, wantX-sentX, 0)) // kCGScrollEventUnitPixel
+ sentX, sentY = wantX, wantY
+ time.Sleep(dur / steps)
+ }
+ return nil
+}
+
+// Press holds the left button at a point.
+func (d *darwinMac) Press(x, y float64, dur time.Duration) 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))
+ time.Sleep(30 * time.Millisecond)
+ down := d.cgEventCreateMouseEvent(0, 1, p, 0)
+ d.cgEventSetIntegerValueField(down, 1, 1)
+ d.post(down)
+ time.Sleep(dur)
+ up := d.cgEventCreateMouseEvent(0, 2, p, 0)
+ d.cgEventSetIntegerValueField(up, 1, 1)
+ d.post(up)
+ return nil
+}
+
func (d *darwinMac) Key(code uint16, flags uint64) error {
if err := d.lock(); err != nil {
return err
diff --git a/internal/mobiumdriver/macos_other.go b/internal/mobiumdriver/macos_other.go
index 04c48cf..26bf599 100644
--- a/internal/mobiumdriver/macos_other.go
+++ b/internal/mobiumdriver/macos_other.go
@@ -3,6 +3,8 @@
package mobiumdriver
import (
+ "time"
+
"github.com/mobiumdev/mobium/internal/mobiumerr"
"github.com/mobiumdev/mobium/internal/uitree"
)
@@ -17,19 +19,22 @@ func errNotMac() error {
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() }
+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) RightClick(float64, float64) error { return errNotMac() }
+func (otherMac) Click(float64, float64) error { return errNotMac() }
+func (otherMac) Wheel(float64, float64, float64, float64, time.Duration) error { return errNotMac() }
+func (otherMac) Press(float64, float64, time.Duration) 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/mobiumdriver/macos_test.go b/internal/mobiumdriver/macos_test.go
new file mode 100644
index 0000000..206ddb3
--- /dev/null
+++ b/internal/mobiumdriver/macos_test.go
@@ -0,0 +1,49 @@
+package mobiumdriver
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/mobiumdev/mobium/internal/uitree"
+)
+
+// fakeMac records the wheel and press calls the driver makes.
+type fakeMac struct {
+ macSystem
+ scale float64
+ wheels [][4]float64
+ press []float64
+}
+
+func (f *fakeMac) Scale() float64 { return f.scale }
+func (f *fakeMac) Wheel(x, y, dx, dy float64, _ time.Duration) error {
+ f.wheels = append(f.wheels, [4]float64{x, y, dx, dy})
+ return nil
+}
+func (f *fakeMac) Press(x, y float64, _ time.Duration) error {
+ f.press = append(f.press, x, y)
+ return nil
+}
+func (f *fakeMac) Tree(int32) (*uitree.AXElement, error) { return nil, nil }
+
+func TestMacSwipeIsTheWheel(t *testing.T) {
+ f := &fakeMac{scale: 2}
+ m := &Mac{sys: f}
+ // A finger moving up from y 1075 to 460: on a phone that brings in
+ // what is below. Measured on MobiumDesk's list in a macOS 26.6.2 guest,
+ // a wheel delta of the same sign did: Rows 1-8 became 13-20.
+ if err := m.Swipe(context.Background(), 1024, 1075, 1024, 460, time.Millisecond); err != nil {
+ t.Fatal(err)
+ }
+ want := [4]float64{512, 537.5, 0, -307.5}
+ if len(f.wheels) != 1 || f.wheels[0] != want {
+ t.Errorf("wheel = %v, want %v: at the start point in points, by the finger's travel", f.wheels, want)
+ }
+ if err := m.LongPress(context.Background(), 100, 200, time.Millisecond); err != nil {
+ t.Fatal(err)
+ }
+ if len(f.press) != 2 || f.press[0] != 50 || f.press[1] != 100 {
+ t.Errorf("press = %v, want at 50, 100 points", f.press)
+ }
+}
diff --git a/internal/testrun/file.go b/internal/testrun/file.go
index 5ff9dff..5876e64 100644
--- a/internal/testrun/file.go
+++ b/internal/testrun/file.go
@@ -184,6 +184,10 @@ func toolSchema(name string) (map[string]interface{}, bool) {
// called "up". They have no shorthand, as before they took a target.
var targetNeedsMore = map[string]bool{"app_swipe": true}
+// shorthandArg names the main argument where the schema cannot: press takes a
+// button or a Mac's keys, neither required, and {"press": "back"} is a button.
+var shorthandArg = map[string]string{"app_press": "button"}
+
// mainArgument is what a string in the shorthand fills: target when the tool
// has one, else its one required string, else its only argument — read from
// the schema, so a tool added later needs nothing here. A tool with no single
@@ -200,6 +204,9 @@ func mainArgument(tool string, schema map[string]interface{}) (string, error) {
if _, ok := props["target"]; ok && !targetNeedsMore[tool] {
return "target", nil
}
+ if name, ok := shorthandArg[tool]; ok {
+ return name, nil
+ }
var strs []string
if req, ok := schema["required"].([]interface{}); ok {
for _, r := range req {
diff --git a/internal/uitree/parse_ax.go b/internal/uitree/parse_ax.go
index a80e7eb..fe17db3 100644
--- a/internal/uitree/parse_ax.go
+++ b/internal/uitree/parse_ax.go
@@ -57,9 +57,50 @@ func ParseMac(app *AXElement, bundle string, scale float64, screen Rect) *Tree {
n := macNodeFrom(app, root, 0, bundle, scale, screen, screen)
root.Children = []*Node{n}
}
+ if m := tree.OpenMenu(); m != nil {
+ hideOutsideMenuBar(root, m)
+ }
return tree
}
+// OpenMenu is a Mac menu that is open, or nil. A closed menu's frame has no
+// size; an open one's does.
+func (t *Tree) OpenMenu() *Node {
+ var open *Node
+ t.Walk(func(n *Node) bool {
+ if open == nil && n.Class == "AXMenu" && n.Displayed && !n.Bounds.Empty() {
+ open = n
+ }
+ return open == nil
+ })
+ return open
+}
+
+// InMenuBar reports whether n is the menu bar or inside it.
+func InMenuBar(n *Node) bool {
+ for p := n; p != nil; p = p.Parent {
+ if p.Class == "AXMenuBar" {
+ return true
+ }
+ }
+ return false
+}
+
+// hideOutsideMenuBar hides what an open menu makes unreachable: a click
+// outside it and the menu bar only closes it (CHALLENGES 418). A context
+// menu is open outside the menu bar.
+func hideOutsideMenuBar(n, open *Node) {
+ if n.Class == "AXMenuBar" || n == open {
+ return
+ }
+ if n.Class != "hierarchy" && n.Class != "AXApplication" && !open.Within(n) {
+ n.Displayed = false
+ }
+ for _, c := range n.Children {
+ hideOutsideMenuBar(c, open)
+ }
+}
+
// 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)
@@ -120,6 +161,10 @@ func macNodeFrom(e *AXElement, parent *Node, sibling int, bundle string, scale f
if n.Text != "" && n.Text == e.Placeholder {
n.ShowingHint = true
}
+ // A disabled menu item with no title is a separator, shown as nothing.
+ // SwiftUI's context menu put one at its item's frame, and map called the
+ // item covered by it.
+ separator := e.Role == "AXMenuItem" && e.Title == "" && !e.Enabled
// 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
@@ -128,7 +173,7 @@ func macNodeFrom(e *AXElement, parent *Node, sibling int, bundle string, scale f
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)
+ n.Displayed = n.Displayed && on && contains(clip, x, y) && !separator
}
switch {
case e.Role == "AXSheet" && !n.Bounds.Empty():
@@ -141,6 +186,9 @@ func macNodeFrom(e *AXElement, parent *Node, sibling int, bundle string, scale f
if e.Role == "AXScrollBar" || parent.Class == "AXScrollBar" {
n.Clickable = false
}
+ if separator {
+ n.Clickable = false
+ }
for i, c := range e.Children {
n.Children = append(n.Children, macNodeFrom(c, n, i, bundle, scale, screen, clip))
}
diff --git a/internal/uitree/parse_ax_test.go b/internal/uitree/parse_ax_test.go
index 0720963..2422a1c 100644
--- a/internal/uitree/parse_ax_test.go
+++ b/internal/uitree/parse_ax_test.go
@@ -151,3 +151,92 @@ func TestParseMacSheet(t *testing.T) {
t.Error("Unlock must be on the dialog and Sign In under it")
}
}
+
+func TestParseMacOpenMenu(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: "increment", Title: "Increment", Frame: []float64{78, 319, 85, 24}, Enabled: true},
+ }},
+ {Role: "AXMenuBar", Frame: []float64{0, 0, 1024, 30}, Enabled: true, Children: []*AXElement{
+ {Role: "AXMenuBarItem", Title: "File", Frame: []float64{200, 0, 40, 30}, Enabled: true},
+ {Role: "AXMenuBarItem", Title: "Probe", Frame: []float64{276, 0, 54, 30}, Selected: true, Enabled: true, Children: []*AXElement{
+ {Role: "AXMenu", Frame: []float64{272, 31, 178, 34}, Enabled: true, Children: []*AXElement{
+ {Role: "AXMenuItem", Identifier: "menuAction:", Title: "Reset Counter", Frame: []float64{272, 36, 178, 24}, Enabled: true},
+ }},
+ }},
+ }},
+ }}
+ tree := ParseMac(app, "dev.mobium.desk", 1, Rect{X2: 1024, Y2: 768})
+ menu := tree.OpenMenu()
+ if menu == nil {
+ t.Fatal("OpenMenu() = nil with the Probe menu open")
+ }
+ var item, inc, file *Node
+ tree.Walk(func(n *Node) bool {
+ switch n.Label {
+ case "Reset Counter":
+ item = n
+ case "Increment":
+ inc = n
+ case "File":
+ file = n
+ }
+ return true
+ })
+ if !Actionable(item) || !item.Within(menu) {
+ t.Error("Reset Counter is on the open menu and was not actionable")
+ }
+ if Actionable(inc) {
+ t.Error("Increment is behind an open menu, where a click only closes it, and was actionable")
+ }
+ if !Actionable(file) || !InMenuBar(file) {
+ t.Error("another menu's title stays reachable with a menu open")
+ }
+
+ app.Children[1].Children[1].Children[0].Frame = []float64{0, 768, 0, 0}
+ if tree := ParseMac(app, "dev.mobium.desk", 1, Rect{X2: 1024, Y2: 768}); tree.OpenMenu() != nil {
+ t.Error("a closed menu, with no size, was taken as open")
+ }
+}
+
+func TestParseMacContextMenu(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: "increment", Title: "Increment", Frame: []float64{78, 319, 85, 24}, Enabled: true},
+ }},
+ {Role: "AXMenuBar", Frame: []float64{0, 0, 1024, 30}, Enabled: true},
+ }}
+ // As measured: the menu inside the window's hosting group, with a
+ // disabled, untitled item at its one item's frame.
+ app.Children[0].Children = append(app.Children[0].Children, &AXElement{Role: "AXGroup",
+ Frame: []float64{62, 143, 900, 452}, Enabled: true, Children: []*AXElement{
+ {Role: "AXMenu", Frame: []float64{121, 359, 84, 34}, Enabled: true, Children: []*AXElement{
+ {Role: "AXMenuItem", Identifier: "add-ten", Title: "Add Ten", Frame: []float64{121, 364, 84, 24}, Enabled: true},
+ {Role: "AXMenuItem", Frame: []float64{121, 364, 84, 24}},
+ }},
+ }})
+ tree := ParseMac(app, "dev.mobium.desk", 1, Rect{X2: 1024, Y2: 768})
+ m := tree.OpenMenu()
+ if m == nil || m.Parent.Class == "AXMenuBarItem" {
+ t.Fatalf("OpenMenu() = %+v, want the context menu", m)
+ }
+ var add, inc *Node
+ tree.Walk(func(n *Node) bool {
+ switch n.Label {
+ case "Add Ten":
+ add = n
+ case "Increment":
+ inc = n
+ }
+ return true
+ })
+ if !Actionable(add) {
+ t.Error("the context menu's item was not actionable")
+ }
+ if a := tree.AimAt(add); a.Blocker != nil || a.Over != nil {
+ t.Errorf("Add Ten is aimed at with %+v: a separator takes no click", a)
+ }
+ if Actionable(inc) {
+ t.Error("Increment is behind an open context menu and was actionable")
+ }
+}