feat(desktop): add the macOS native driver crate, built with NAPI-RS (ENG-1533)

Merged
KD
2d ago
+6867-0

What

packages/desktop/native is a new Rust crate that drives macOS apps through the accessibility API. It builds into a NAPI-RS addon that Node loads in process. Nothing calls it yet. #2323 switches @e2e-dev/desktop from agent-desktop to it.

This is the first of four PRs for ENG-1533. They merge together, bottom first:

  1. #2322 (this PR): the driver crate.
  2. #2323: the engine switch, the platform packages, and the docs.
  3. #2324: the desktop testbed.
  4. #2325: CI and the release job.

Why

The desktop engine runs agent-desktop, a CLI it downloads on the first run and starts once per action. Every action pays for a process start and a JSON round trip. A fix to agent-desktop also has to wait for an upstream release. ENG-1533 asks for our own macOS engine in Rust, called directly through NAPI-RS. This PR is that engine. Two rules shape it: no secret of the run's environment reaches the app, and every failure says whether its input reached the app.

How it works

  1. src/lib.rs exports status, screenLocked, processStarted, processesCarrying, forgetProcess, launch, listWindows, snapshot, act, inputId, cancelInput, press, focusWindow, pointer, and screenshot. A call that waits on another process, and processesCarrying, which reads every process in 15 to 40 ms, runs on a blocking thread, in an autorelease pool (src/lib.rs:46), and resolves with { ok, data } or { ok: false, error: { code, message, disposition: { delivery }, details } } (src/failure.rs:78). delivery is not_delivered only when nothing reached the app's content. A window brought forward, or a list's menu that opened and closed with nothing chosen, still counts as not_delivered. The engine reports any other failure of an input as ACTION_MAY_HAVE_COMMITTED.
  2. No input after the caller gives up. act, press, pointer, and launch take an input id from inputId and the call's budget, counted from the call. The addon hands out the ids from one counter for the process (next_input_id, src/input.rs:27, unit tested across threads), since every Node worker thread that loads it shares its cancel marks. guarded (src/actions/mod.rs) registers the run, and go refuses with a not-delivered TIMEOUT once cancelInput(id) was called or the deadline passed. Every send checks it right before it goes out: each AX write, each typed character, the pointer move, each click (again after the hit test before it, which waits on the app), each focus write that brings a window forward (focusWindow takes an input id too), and the open that starts an app. A click already pressed is always released. Cleanup that runs past the deadline, such as closing a menu, stops at a cancel.
  3. src/ax.rs wraps AXUIElement through raw FFI, with a 1 s messaging timeout so a hung app cannot hang the worker. It reads a node's attributes in one batch call. A slot of that batch the app did not answer in time fails the whole read as a stall (slots, :183), since a value the app did not answer is not a value it lacks.
  4. src/windows.rs joins the window server's list with every accessibility window the app counts, by window id. A list that names none of the app's windows while an AXWindow had no id yet, or an entry with no id whose role the app did not answer in time (may_be_window, unit tested), fails as a retryable stall, so an app with a window never reads as having none. A window counts as focused when the app's focused window is it, or a sheet or alert on it (holds_focus); sheet_focused says which, and sheet_id names the sheet: its window id, else a key for its accessibility element. Each window carries is_main, and system for an untitled AXDialog holding an element identified siri (:167), which macOS 27 puts over an app after a press in a SwiftUI sheet.
  5. src/snapshot.rs:622 reads one window into the snapshot shape agent-desktop used, so the engine's nodes.ts reads it with few changes.
    • Hidden nodes. A node outside its clip rect reads as hidden. The clip is the window, cut by every scroll area above the node. An open menu or a popover floats above the window and is not clipped (inner_clip, :229). A node with no size never reads as hidden, since a macOS 27 menu reports a 0x0 frame.
    • Size limits. A read stops at 8,000 nodes, and a node reads up to that many children. A value is read whole, however long: the engine cuts what an observation shows.
    • Incomplete reads. A read reports complete: false when the deadline stopped it (with timed_out, so the engine can answer it as a timeout), or when the app did not answer a read in time, and marks the ancestors subtree_truncated. A read during which the process lost its Accessibility permission fails with PERM_DENIED, never a complete, empty window. A window the app did not answer for itself is marked root_unread, so the engine's launch wait reads it again. Any other read error is the element's own answer, and that element is left out.
    • Names. A row, cell, outline item, option, or list item with no name of its own takes every text inside it, in reading order, joined by spaces (content_name, unit tested), as an accessible name comes from content; text an interactive read prunes counts too.
    • States. An AppKit tab (AXTabButton) reads as a tab, the active one (value 1) selected, and a password field whose value can be set takes keystrokes. A text label's and a heading's actions are read, so one that takes a press gets a ref. A window's own title-bar buttons are left out: the ones the window names (AXCloseButton, AXMinimizeButton, AXZoomButton, AXFullScreenButton), so an app's own button with that subrole stays; the subrole is the rule only for a window that names none. When the app does not answer which element holds focus, no node reads as focused and the read is incomplete, never filled in from each element's own AXFocused. A disclosure triangle is expanded by its value. A menu item is never selected, which on a menu means the pointer is there. A heading carries its level from AXHeadingLevel (macOS 26; level_of, :208, unit tested).
    • Scrolling. A scroll area is offered Scroll only when it has a scroll bar, and reports the axes it scrolls along (scroll_axes), an element listed as an attribute or as a child: SwiftUI gives every scroll area the page actions, also one that fits, and macOS can answer an attribute the area lacks with null.
  6. src/actions/ runs one action on a ref, in modules by kind: mod.rs (the dispatch, the shared checks, and key presses), values.rs (checks, steppers, fills, select-all), select.rs (pop-up menus and list rows), scroll.rs, typing.rs, and pointer.rs (physical input and its hit test). A role read the app did not answer in time fails as a retryable stall (role_of), and an element gone by then as a retryable stale ref, never as a control without that role.
    • Disabled controls. A tap, double-click, right click, check, fill, clear, and select wait for a control whose AXEnabled is false to be enabled, then refuse it (enabled), since AppKit acknowledges a press on a disabled control and ignores it. The wait ends 200 ms before the deadline, so the refusal reaches the engine before it cuts the call off. A box that already shows the state asked for is left alone, disabled or not.
    • Off screen. placement (in snapshot.rs) says whether an element shows, by the test the snapshot reads offscreen with, or is scrolled out, in a minimized window, or a control with no size; a frame or parent read the app did not answer fails it as a stall. reveal scrolls a scrolled-out element into view (AXScrollToVisible) and answers once it shows, and refuses the rest. A tap and a right click run it after the wait for an enabled control, and a check before its press, after its refusals; a failure after a scroll counts as delivered (after_scroll, unit tested), since the list moved. A right click refuses a control with no context menu before it scrolls.
    • Press. A tap on a text field focuses it, before any AX action it offers (AppKit's password field offers AXConfirm). perform sends the AX action. On an error, answered (unit tested) reads the element again. Gone within 300 ms means the press closed what held it, so it landed. A timeout while the app still answers means a menu or modal opened, so it is done. Gone as the action was sent, or any other error, is delivered but unverified. A refusal (no such action or attribute, no permission) sent nothing.
    • Check and stepper. uncheck() on a selected radio button is refused before any press, since only another radio clears it. Both loops judge each press by the state it led to (press_to_state, step_to, unit tested). A SwiftUI toggle or stepper in a fresh sheet answers its first press with an error and still toggles. check reads a box's state as the snapshot does (on, off, and mixed too), and presses no box whose state cannot be read, since it may already show the state asked for. A stepper refuses a value outside its AXMinValue and AXMaxValue, stops when a step wraps around its range, and, when a step goes past the value asked for, is stepped back to the value it started from. Values compare up to the rounding of summed steps (same), never more than half a step once a press showed its size, and whole numbers compare exactly. A stepper that shows the value exactly gets no press. One within rounding of it gets one press to learn the step, and is stepped back when it was there already.
    • Rows. A tap on a table row, or on a cell in one, selects the row through the table's AXSelectedRows, else the row's own AXSelected, and waits for it to show selected (choose_row). A select on a list matches a row by the name the snapshot gives it (row_label: its title, the element that labels it, its description, else all its text, read as deep as a snapshot may), and refuses a label two rows show, or a list with a row label the app did not answer, before anything is chosen. A tab or radio option a select presses must show it became selected; a disabled one is waited for.
    • Pop-up buttons. Select opens the menu, or takes the one a tap already opened (a read of it that stalls fails), presses the item, and checks the button shows it (select). With a menu open, the option already shown is chosen from it too, so the menu closes. The scan of a menu's items, or a list's rows, stops at a cancel (scan, unit tested). Any failure before the item is pressed closes the menu: AXCancel, then Escape, each with a wait of its own (close_menu, unit tested), and neither once the call was cancelled. The scan of the items stops at a cancel too. A menu that stays open makes the failure delivered with menu: "open" (unclosed). A title or row the app did not answer in time is reported as a stall, not a missing option. It refuses a pull-down button, and a combo box that takes no typed value.
    • Select all. select_all sets AXSelectedTextRange to the whole text and reads it back. A field whose length cannot be read is refused, since a range of 0 would read as done. The engine uses it before a replace, since Cmd+A sent to an app in the background selects nothing.
    • Fill. set_value reads whether the value is a number before it sends anything (a read that stalls fails), focuses a field, and writes AXValue. A text field that answers no value counts as empty, so clear() on one succeeds. A secure field is checked by its character count, never its value. A focus write that failed after the app took it (a handler that replaced the field) counts as delivered, so a later failure is not retried as a stale ref.
    • Scroll. It moves the scroll bar (scroll). A scroll bar listed only as a child is found too (scroll_bar). A bar that only steps, and the page actions, take as many steps as the swipe's strength asks for. A position the app did not answer fails as a stall, never as 0, which could turn a swipe around. A node that scrolls itself (its own bar, or the page action for the direction) is scrolled; one with neither, such as a list, scrolls the nearest scroll area above it, so a swipe on a nested list never moves the pane around it.
  7. src/input.rs sends keys to one process with CGEventPostToPid, which reaches the app's key window while the app stays in the background. With physical, it posts HID events instead. Without it, a key goes only to a window that holds the app's focus.
    • Typing (type_text) records the window that holds the keyboard before it checks the field's focus, and requires that window to be the field's or a sheet on it. Before every key it waits, polling every 2 ms for up to 250 ms, until the element the last key went to shows it or loses focus (30 ms once a key showed no change). It then reads the element the key will reach (the field itself for the first key, read once more as the last read before it, and never focused back), and last checks that the window still holds the keyboard and, with physical, that the app is frontmost, so a Return that opened another window, a sheet on this one, or another app does not take the rest of the text. A stop before the first key, with no focus moved, says nothing was sent.
    • Keys. A locator's press names its control's ref, and the key goes only while that element holds the app's focus, read after the window check so a sheet that opened during it is caught; a physical key also needs the window holding the app's focus and, as the last read before it goes, the app frontmost.
    • Each typed character carries the key that types it on the Mac's layout, with Shift when it takes Shift and no other modifier, or code 0 when no key types it (key_code, unit tested). checkCombo reads a combo against the layout as press does and sends nothing. pieces (unit tested) sends one key event per character, as a keyboard does, so a handler that reads each key sees every character; a surrogate pair stays in one event, and \r\n is one Return.
  8. Physical pointer input. physical raises the window and hit-tests the element's center through the system-wide element (aim_at), which finds whatever is on top there, of any app. A click is refused when the point lands outside the element, or on a control inside it: a button, a field, a switch, or any element that offers a press, such as an image or a group a custom control draws itself in (aimed, takes_click, unit tested). A hover only needs the element on top. The first click checks the point again after the move. A double-click's second click follows at once, as part of the same gesture. A hit test the app did not answer is a retryable stall, never a covering element. A hover at a point is refused before the move when another window or app is on top there (window_on_point). A click at a point (pointer_at) checks, before the move and again after it, that the app is frontmost, its window holds the focus, the sheet on it is the one the point was taken on (by its sheet_id; a sheet with no key matches none), or still none, and the window is on top at the point (window_takes_point). A point taken on a node with no ref (content) also refuses a control under the pointer, such as one that coming forward revealed (point_lands, unit tested).
  9. src/launch.rs:140 launches with /usr/bin/open -n. open runs with env_clear, only the variables the caller passes, and --env E2E_DESKTOP_LAUNCH=<token>. NSWorkspace merged the worker's environment, secrets included, so it is not used. The launched copy is the new one whose environment carries the token, read from KERN_PROCARGS2 (parse_procargs, src/process.rs:48, unit tested). macOS hides the environment of its own apps, of Apple's Mac App Store apps (Numbers, Xcode), and of builds signed with restrict (hidden_by, :125, from codesign -dvv, unit tested; every Mac App Store app carries the signature, so each gets the arguments). Those get -E2EDesktopLaunch <token> as their last arguments instead. A copy with neither is never claimed, since the user may have opened it.
  10. Shortcuts on any layout. A key combo with Command, Control, or Option carries only a key code, and macOS reads its character from the layout, so parse_combo (src/input.rs:210) takes the key that types the character on the Mac's ASCII-capable layout, in its Command layer for a Command shortcut (characters, src/layout.rs:44, through UCKeyTranslate, one read at a time), never a keypad key (code_for, :93, unit tested). A layout that cannot be read refuses the shortcut. The Command-Q guard checks the character, so ControlOrMeta+a on AZERTY is Select All, not Quit. Text and Shift combos carry their characters.
  11. native/licenses/ holds the license texts of the crates that publish none (napi-rs, objc2), which the notices generator in #2323 uses; a crate with neither stops it.
  12. src/system.rs reads the screen lock and the two permissions, and takes screenshots with screencapture -x -o -l <window>. rust-toolchain.toml pins Rust 1.100.0 with both macOS targets, and Cargo.lock is committed. The CI job that checks the crate is in #2325.

Issue

Refs ENG-1533

Verified

Ran it locally: yes. With this Mac's screen unlocked, the desktop testbed (#2324) passes live with this driver: pnpm test 23 of 23 and pnpm test:headed 5 of 5 with the real pointer and keyboard. Each live-checked fix was also run without it: typing that follows a window a key opened (2 of 3 leaked without the per-key wait, 0 of 3 with it, directly and after a Tab), keystrokes into a password field (refused without the secure-field rule), the active tab read as selected (fails without its rule), and a tap that focuses the password field (fails without it). Since then, each new testbed test below was run without its driver fix and failed: a select on a pop-up whose menu a tap opened (twice), rows and cells found by their text (LOCATOR_NOT_FOUND), a two-column row selected by all its text (the list has no option). A scratch build of the testbed with a window that can minimize checked that a check and a tap in a minimized window are refused. A probe against the addon checked the visibility test against the snapshot both ways: a visible row needs no scroll, and a row the list holds out of view is refused, since AppKit table rows offer no AXScrollToVisible. The driver's actions now live in modules by kind (src/actions/), a move with no change to the code, as okwasniewski asked. Typing 200 characters takes 1.97 s with the 2 ms poll, against 4.26 s with a 30 ms one. michal-e2e ran the testbed live at 63a08edf6 and fcb32fcd9 too.

  • cargo fmt --check, cargo clippy --locked --all-targets -- -D warnings, and cargo test (56 tests) pass, and release builds pass for both Mac architectures. The tests cover:
    • Launch: the KERN_PROCARGS2 parse and the signatures that hide the environment.
    • Box and stepper loops: error answers, step-back, wrap, the range refusal, rounding bounded by the step, whole numbers, and the deadline.
    • Press answers: the classification of an action's error answer.
    • Cancels: the cancel guard, the scan's limit of matches, a cancel during the hit test, focusWindow cancelled first, the menu cleanup after a cancel, cancel versus deadline, and input ids across threads.
    • Reads: the window list that names no window, a stalled role read counted as a window, a row named from its text, the batch-read stall rule, the offscreen and clip rules, the disclosure and menu-item states, the heading level, and the Siri dialog rule.
    • Menus and pointer: the pop-up's open-menu failure, the hit test's target, control, and stall cases, and the coordinate click's window and sheet rule.
    • Keys: one key event per character, a typed character's key and Shift, a typing stop that sent nothing, the layout key lookup, and parse_combo.
  • okwasniewski's runs on macOS 27 (arm64) of 075ad9d9cb, before rounds 4 and 5 of review: the testbed 9/9, headed 3/3, and his SwiftUI app 10/12. With his prototype, which this head takes in (the sheet focus rule, is_main, the scroll bar rule), his SwiftUI app was 12/12 in both modes with no pinned window. The sign-in suite took a median 5.3 s against 35.6 s with agent-desktop.
  • Against the real addon, with no app driven:
    • Autorelease pool. Three launches of a missing app print 12 missing-pool diagnostics under OBJC_DEBUG_MISSING_POOLS=YES before the pool, and none after.
    • Cancelled launches. A launch given no budget, and one cancelled first, both answer TIMEOUT, not delivered, and no Calculator starts.
    • Blocking thread. A zero-delay timer set before processesCarrying fires at about 1 ms, while the scan answers at about 17 ms.
    • Window lists. The window list no longer refuses itself for Finder, Chrome, Slack, and the other apps running here, whose AXWindows hold elements that are not windows.
    • Launch claims. Calculator is still claimed by its token argument. Reviewers' runs on this head's code claimed Calculator while the user's own copy ran, and kept a secret of the caller's environment out of the testbed app.
  • Not run live on this head (the unit tests cover their logic only):
    • SwiftUI controls: the first press in a fresh SwiftUI sheet, the stepper step-back, and the popover.
    • Reads and selection: select-all, the child scroll bar, the heading level, and the Siri rule on a real dialog.
    • Pointer: a tap refused over a sheet that just opened, and the system-wide hit test against another app's panel.
    • Typing: one character per event, and typing that stops when another window or app takes the keyboard.
    • Keyboard layouts: shortcuts on a non-US layout. Opus read the French, German, and Dvorak-QWERTY tables; this Mac has a US layout.
    • App Store apps: an Apple App Store app's launch. Opus reproduced the old failure on Numbers and saw the token argument fix it.
    • Cancels: every cancel path but the launch's.
  • processesCarrying('E2E_DESKTOP_LAUNCH=tok-a') on a process started with an empty argument and the token as its first variable, and on Calculator launched by the driver:
ProcessBefore this parseThis PR
node -e ... ''not foundfound
node -e ... 'x'foundfound
Calculator (environment hidden)not foundfound
  • A launch race on Calculator, an app whose environment macOS hides: the driver launches it, and a second copy is opened with open -n at the same moment, as a user would. Three runs each:
DriverResult
Lone-copy rule (claim a new copy when it is the only one)TIMEOUT, kind: unclaimed, after 10 s, 3 of 3
Token in the arguments (this PR)Claims its own copy (-E2EDesktopLaunch race-token-1 in ps), 3 of 3. The user's copy started first and was left alone

🤖 Generated with Claude Code