Skip to content

feat(computer-use): accessibility-tree tools, fully cgo-free - #1086

Merged
edenreich merged 4 commits into
mainfrom
feat/cgo-free-computer-use
Aug 20, 2026
Merged

edenreich merged 4 commits into
mainfrom
feat/cgo-free-computer-use

Conversation

@edenreich

Copy link
Copy Markdown
Contributor

Supersedes #1085 — delivers the same accessibility-tree tools, rewritten to be fully cgo-free.

What

The macOS computer-use layer no longer needs cgo. The whole CLI now cross-compiles with CGO_ENABLED=0 on darwin, linux and windows from a single host.

Tools (unchanged public surface)

  • GetUIElements — lists pressable accessibility elements (frontmost, dock, menubar).
  • PressUIElement — presses an element by title without moving the cursor.

cgo → cgo-free

Area Before After
AX tree cgo / Objective-C purego (dlopen + purego/objc) walking AXUIElement
App focus (list / frontmost / activate) NSWorkspace via cgo robotgo cgo-free backend (-tags mac)
Screen capture + input robotgo (cgo) robotgo cgo-free backend
Accessibility permission AXIsProcessTrusted (cgo) purego AXIsProcessTrusted
Clipboard golang.design/x/clipboard (cgo, text + image) robotgo clipboard subpackage (exec, text only)

Dependencies

  • robotgo pinned to a cgo-free main pseudo-version.
  • Removed golang.design/x/clipboard and golang.design/x/x11.

Build / CI reconciliation

One mechanism across Taskfile, CI and the flake:

  • CGO_ENABLED=0 everywhere.
  • -tags mac only where a darwin binary is produced — robotgo is imported on darwin only, so the tag is unnecessary for linux/windows. Taskfile GOTAGS, CI build-macos, the release darwin step, and the flake all follow this.
  • No global GOFLAGS, no cross-build tag clearing.

Behavior changes

  • Application IDs are now pid:<N> on every platform (was the bundle ID on macOS). ActivateApp accepts pid:<N> or a name substring.
  • Image clipboard is dropped — text copy/paste only.

Verification

  • CGO_ENABLED=0 build + cross-compile for linux/amd64, windows/amd64, darwin/arm64 — all green.
  • task build, task test (-tags mac), task precommit:run (lint: 0 issues) — green on darwin.
  • Linux X11/Wayland runtime paths are compile-verified only (no Linux host available).

Docs

Public-surface change (new tools + cgo-free build); a [DOCS] follow-up for inference-gateway/docs is warranted.

…IElement

Adds an AXProvider interface to internal/display (mirroring the existing
provider registry pattern) with a macOS AXUIElement backend, and two new
computer-use tools:

- GetUIElements walks the accessibility tree of the frontmost app, the
  Dock, or the menu bar and returns pressable elements (role, title,
  bbox) mapped into the GetLatestFrame frame space, so centers feed
  straight into MouseClick. Read-only: no cursor movement, no screen
  lock, usable by background sessions.
- PressUIElement invokes an element's default press action by title
  without moving the cursor; it takes the screen lock and requires
  approval under computer_use.approval: destructive.

No provider registered (non-macOS), missing TCC permission, or an empty
tree degrade to a message steering the model to the GetLatestFrame
vision pipeline - never a hard failure. Linux AT-SPI2 and Windows UIA
backends can register behind the same interface later.

Closes #998
…use.yaml files

computer_use.yaml was decoded into a zero struct, so tool sections added
after a user's file was seeded loaded as enabled: false - GetUIElements
and PressUIElement were silently absent from the toolset. LoadComputerUse
now decodes the file over the in-code defaults (LoadYAMLMerged), so
missing sections keep their defaults.

Also steer the model to the accessibility tree first: MouseMove,
MouseClick, and GetLatestFrame descriptions now name GetUIElements as
the preferred way to locate elements, with GetLatestFrame as fallback.
@edenreich

Copy link
Copy Markdown
Contributor Author

Docs follow-up filed: inference-gateway/docs#581 ([DOCS] cgo-free computer-use build + accessibility-tree tools).

Replace the macOS cgo/Objective-C surface with cgo-free equivalents so the
whole CLI cross-compiles with CGO_ENABLED=0 on darwin, linux and windows
from a single host.

- Accessibility tree (GetUIElements/PressUIElement) walks AXUIElement via
  purego (dlopen + purego/objc) instead of the cgo backend.
- App focus (list/frontmost/activate), screen capture and input run on
  robotgo's cgo-free backend (build tag mac), pinned to a main
  pseudo-version. Application IDs are now pid:<N> on every platform.
- Accessibility-permission check uses purego AXIsProcessTrusted.
- Clipboard text uses robotgo's exec-based clipboard subpackage; image
  paste shells out to the platform clipboard tool (osascript, wl-paste/
  xclip, PowerShell). Image clipboard writes are dropped.
- Drop golang.design/x/clipboard and x11 dependencies.

Reconcile the build around one mechanism: CGO_ENABLED=0 wherever a binary
is produced (Taskfile build/install, CI build jobs, release, flake) with
-tags mac only where a darwin binary is built. Test jobs keep the default
cgo toolchain, which the race detector requires; the flox dev shell no
longer pins CGO_ENABLED at all.
@edenreich
edenreich force-pushed the feat/cgo-free-computer-use branch from 8699bc5 to 88f2787 Compare August 20, 2026 16:15
@edenreich

Copy link
Copy Markdown
Contributor Author

@infer Can you review this PR? is it ready for merge? use /ponytail:ponytail /ponytail:ponytail-review /go /go-concurrency

@inference-gateway-maintainer

inference-gateway-maintainer Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Model: ollama_cloud/deepseek-v4-flash:preview · View Job

Todos

  • Read full diff and identify all new/modified files
  • Read key new source files (get_ui_elements.go, press_ui_element.go, ax_darwin.go, clipboard.go, interface.go, registry.go)
  • Read test files and config changes
  • Read go.mod/go.sum for dependency changes
  • Assess correctness, cgo-free approach, and edge cases
  • Ponytail over-engineering review
  • Final recommendation: ready for merge or not

Pull Request

#1086

✅ Infer Result: Success

Review: PR #1086 — feat(cgo-free-computer-use)

Git log: 3 commits (c959b92, db19577, 88f2787). Files changed: 37, +1447/−359.


Correctness & Architecture

cgo-free approach is sound. ax_darwin.go uses purego to dlopen the CoreFoundation, ApplicationServices, and libobjc frameworks at process init, then calls AXUIElementCreateApplication, AXUIElementCopyAttributeValue, AXUIElementCopyActionNames, AXUIElementPerformAction, and AXIsProcessTrusted through RegisterLibFunc. Every CF value copied out of the tree is released with cfRelease. An autorelease pool wraps each ListElements/PressElement call. No leaks visible.

AX tree walking (walkCollect/pressFirst): recursive, bounded to axMaxDepth=8 and axMaxElements=200. The ponytail: comment at the cap is honest — these remain hard-coded with a known ceiling.

Config backfill (LoadComputerUse → LoadYAMLMerged): the fix in db19577 is critical — without it, users with a pre-existing computer_use.yaml would silently load the new tool fields as Enabled: false (Go zero value). Using LoadYAMLMerged (decode over defaults) is the correct solution.

Graceful degradation: Both GetUIElements and PressUIElement return Success: true with a steering message when no AX provider, no permission, or no elements are available, rather than hard-failing. This is the right design for an LLM tool — the model receives guidance on the vision fallback instead of a terminal error.

Go idioms (per the Go skill): error sentinel values with errors.Is, table-driven tests with t.Run, //go:build darwin build tags, zero-alloc cfStr via append([]byte(s), 0), sync.Once for lazy init. All clean.

Concurrency (per the go-concurrency skill): axLoadOnce sync.Once for thread-safe framework init. The display.Registry uses sync.RWMutex for reader/writer separation. axSetup's defer/recover gracefully handles dlopen panics. No goroutines are spawned in the AX path — the API calls are synchronous C function calls. The pressFirst traversal is not concurrent (no reason to be — the tree walk is sequential). No issues.

Build system reconciliation: CGO_ENABLED=0 everywhere, -tags mac only on darwin. Taskfile, CI, release.yml, and flake.nix all agree.


Ponytail Over-Engineering Review

Per /ponytail-review format — one line per finding.

  • display/registry.go:L72-78: yagni RegisterAXProvider/DetectAXProvider mirrors the exact same pattern as RegisterAppProvider/DetectAppProvider 6 lines above. Consistent, not bloat. No tag.

  • internal/agent/tools/get_ui_elements.go:L21-L24: delete The axNoProviderMessage and axNoPermissionMessage consts are defined as full sentences. They are used exactly once each. Inline them at call sites (L80, L85). net: -2 lines — but they're also referenced by press_ui_element.go via the same axDegradeResult call, so they'd need to move or be duplicated. Skip — shared consts across two files is cleaner than duplication.

  • internal/display/macos/ax_darwin.go:L147-L153: stdlib cfStr builds the C string from a Go literal with append([]byte(s), 0). strings.NewCString(s) from GODEBUG=cgocheck=0 days is not available in cgo-free. The pattern is the minimum that works. No tag.

  • internal/clipboard/clipboard.go:L83-L99: shrink readImageViaTempFile is 17 lines for a pattern that could be written as a closure inline at each call site. But it's shared across 3 platforms (darwin, linux, windows). Lazy is sharing, not duplicating.

  • internal/agent/tools/get_ui_elements.go:L125-L151: shrink scaleToFrameSpace creates and closes a full DisplayController just to get screen dimensions. net: -0 lines — caching screen dimensions would add complexity. The ponytail-appropriate thing is what it does: grab and release. No tag.

Net result: Lean already. Ship. — no over-engineering found in the new code. The only complexity present is required.


Edge Cases & Potential Issues (not blocking merge)

  1. listRunningApps() via robotgo.Process() (client_darwin.go:L301): Returns the full OS process table, not just GUI apps. The ponytail: comment flags this. On a headless system this dumps daemons, cron jobs, and kernel tasks into the list. Not a merge blocker — the LLM can filter, and filtering to GUI apps requires NSWorkspace which is what we're avoiding.

  2. frontmostApp() via robotgo.GetPid() (client_darwin.go:L319): robotgo.GetPid() returns the PID of the process owning the active window, not the "frontmost application" in the macOS sense. These are the same in practice for GUI apps. Acceptable.

  3. activateApp() via robotgo.ActiveName(name) (client_darwin.go:L346): If multiple windows share a process name, there's no ActivePID equivalent in the cgo-free backend. Activation goes to the first match. Acceptable trade-off documented in the PR.

  4. pressFirst exact string match (ax_darwin.go:L293): Case-sensitive. If GetUIElements returns "Save" and the user tries "save", it won't match. This is consistent behavior — the LLM sees the exact title in the tool output. No change needed.

  5. Image clipboard dropped (clipboard.go:L23): FmtImage is iota 1 — reads work via external tools, writes are ignored (no-op). The PR description says this is intentional. Verified: Write(FmtImage, data) falls through to a no-op, Read(FmtImage) calls readImage() which shells out. If an LLM tries to write an image to clipboard after Write(), it silently fails. The PR body acknowledges this.

  6. event_bridge.go lives in package macos with no build tag: Pre-existing. It imports no darwin-specific packages and builds on any platform despite living in the macos/ directory. Not introduced by this PR.

  7. Test coverage: ax_test.go covers normalizeAXRole with table-driven cases. ax_darwin_test.go is a live smoke test against the Dock, correctly skipped when accessibility permission is absent. Tool-level tests cover validation, formatting, enabled-check, and degrade-result paths. Missing: a test for PressUIElement behavior when the screen lock is held by another tool (concurrent lock acquisition). Not critical for merge but worth adding later.


Verdict

Ready for merge.

The cgo-free approach is correctly implemented — purego dlopen, CF release discipline, autorelease pools, graceful degradation, consistent build system. The AX tools are well-structured, the tests cover the important paths, and the config backfill fix prevents silent regressions for existing users. The three edge cases above (full process table, WeakActivePID, image clipboard no-op) are design trade-offs explicitly acknowledged in the PR description and comments, not bugs.

net: +1447 lines (gross), but removing golang.design/x/clipboard, golang.design/x/x11, and the old NSWorkspace cgo glue means the next developer who runs CGO_ENABLED=0 go build on darwin, linux, and windows from one host will get a binary on every target. That's a good trade.

Model: ollama_cloud/deepseek-v4-flash:preview · Exit Code: 0 · Duration: 1m 53s

Tokens: 1,077,680 in · 7,550 out · 1,085,230 total (15 requests)

Tool calls: 37 total · 100% success rate

Traces
Session: 1787244021-ac6d250e

session (headless, success)                                                  1m44s
├── chat ollama_cloud/deepseek-v4-flash:preview                               3.5s
│   ╰── POST /v1/chat/completions [inference-gateway]                         3.5s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     3.5s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               3.5s
│               ╰── POST /v1/chat/completions [inference-gateway]             3.5s [error: *errors.errorString]
├── execute_tool Read call_jdcix5mt                                          120µs
├── execute_tool Read call_ig1yutny                                          225µs
├── execute_tool Bash call_0q8lwr8d                                           13ms
├── chat ollama_cloud/deepseek-v4-flash:preview                               2.4s
│   ╰── POST /v1/chat/completions [inference-gateway]                         2.4s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     2.4s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               2.4s
│               ╰── POST /v1/chat/completions [inference-gateway]             2.4s [error: *errors.errorString]
├── execute_tool Bash call_y82drhfv                                           15ms
├── chat ollama_cloud/deepseek-v4-flash:preview                               4.5s
│   ╰── POST /v1/chat/completions [inference-gateway]                         4.5s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     4.5s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               4.5s
│               ╰── POST /v1/chat/completions [inference-gateway]             4.5s [error: *errors.errorString]
├── execute_tool TodoWrite call_3lrkgm7z                                      63µs
├── chat ollama_cloud/deepseek-v4-flash:preview                               3.7s
│   ╰── POST /v1/chat/completions [inference-gateway]                         3.7s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     3.7s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               3.7s
│               ╰── POST /v1/chat/completions [inference-gateway]             3.7s [error: *errors.errorString]
├── execute_tool Read call_m1do9wci                                          196µs
├── execute_tool Read call_fwxl2w7m                                          318µs
├── execute_tool Read call_3hf6ga0e                                          202µs
├── execute_tool Read call_kud13hsv                                          172µs
├── execute_tool Read call_6cr0afkn                                          122µs
├── execute_tool Read call_wv74seun                                          222µs
├── chat ollama_cloud/deepseek-v4-flash:preview                               3.3s
│   ╰── POST /v1/chat/completions [inference-gateway]                         3.3s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     3.3s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               3.3s
│               ╰── POST /v1/chat/completions [inference-gateway]             3.3s [error: *errors.errorString]
├── execute_tool Read call_10r47oe3                                          195µs
├── execute_tool Read call_rrgeq5x4                                          274µs
├── execute_tool Read call_fwgji2tw                                          215µs
├── execute_tool Read call_nzks2og7                                          155µs
├── execute_tool Read call_7dt4z9z4                                          287µs
├── execute_tool Read call_xoglwvin                                          115µs
├── chat ollama_cloud/deepseek-v4-flash:preview                               4.4s
│   ╰── POST /v1/chat/completions [inference-gateway]                         4.4s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     4.4s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               4.4s
│               ╰── POST /v1/chat/completions [inference-gateway]             4.4s [error: *errors.errorString]
├── execute_tool Read call_sdvs4u6v                                          337µs
├── execute_tool Read call_vfrn2ax7                                          281µs
├── execute_tool Read call_2s8n8zsd                                          249µs
├── execute_tool Read call_7icufvv9                                          155µs
├── execute_tool Read call_7wpbnwir                                          242µs
├── chat ollama_cloud/deepseek-v4-flash:preview                               5.0s
│   ╰── POST /v1/chat/completions [inference-gateway]                         4.9s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     4.9s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               4.9s
│               ╰── POST /v1/chat/completions [inference-gateway]             4.9s [error: *errors.errorString]
├── execute_tool TodoWrite call_ssd2ujkk                                      45µs
├── chat ollama_cloud/deepseek-v4-flash:preview                               4.4s
│   ╰── POST /v1/chat/completions [inference-gateway]                         4.4s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     4.4s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               4.4s
│               ╰── POST /v1/chat/completions [inference-gateway]             4.4s [error: *errors.errorString]
├── execute_tool Read call_fdsl42fr                                          240µs
├── execute_tool Read call_zgtfcgg6                                          206µs
├── execute_tool Read call_y1kxenjo                                          196µs
├── execute_tool Read call_ax1tezdt                                          200µs
├── chat ollama_cloud/deepseek-v4-flash:preview                               4.9s
│   ╰── POST /v1/chat/completions [inference-gateway]                         4.8s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     4.8s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               4.8s
│               ╰── POST /v1/chat/completions [inference-gateway]             4.8s [error: *errors.errorString]
├── execute_tool Read call_e7626ozr                                          224µs
├── execute_tool Read call_89kozc0e                                          301µs
├── execute_tool Bash call_8utyz11k                                            4ms
├── chat ollama_cloud/deepseek-v4-flash:preview                               5.2s
│   ╰── POST /v1/chat/completions [inference-gateway]                         5.1s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     5.1s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               5.1s
│               ╰── POST /v1/chat/completions [inference-gateway]             5.1s [error: *errors.errorString]
├── execute_tool Grep call_0gof4i10                                            4ms
├── execute_tool Read call_qy0g6914                                          135µs
├── chat ollama_cloud/deepseek-v4-flash:preview                               6.6s
│   ╰── POST /v1/chat/completions [inference-gateway]                         6.6s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     6.6s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               6.6s
│               ╰── POST /v1/chat/completions [inference-gateway]             6.6s [error: *errors.errorString]
├── execute_tool Grep call_tj72zlhw                                           33ms
├── execute_tool Read call_t9w1bsj0                                          128µs
├── chat ollama_cloud/deepseek-v4-flash:preview                               4.0s
│   ╰── POST /v1/chat/completions [inference-gateway]                         4.0s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     4.0s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               4.0s
│               ╰── POST /v1/chat/completions [inference-gateway]             4.0s [error: *errors.errorString]
├── chat ollama_cloud/deepseek-v4-flash:preview                              23.5s
│   ╰── POST /v1/chat/completions [inference-gateway]                        23.4s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]    23.4s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]              23.4s
│               ╰── POST /v1/chat/completions [inference-gateway]            23.4s [error: *errors.errorString]
├── execute_tool TodoWrite call_o4ejn5bz                                      53µs
├── chat ollama_cloud/deepseek-v4-flash:preview                               5.0s
│   ╰── POST /v1/chat/completions [inference-gateway]                         4.9s
│       ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]     4.9s [error: *errors.errorString]
│           ╰── POST /proxy/:provider/*path [inference-gateway]               4.9s
│               ╰── POST /v1/chat/completions [inference-gateway]             4.9s [error: *errors.errorString]
├── execute_tool TodoWrite call_t5rlhv1t                                      38µs
╰── chat ollama_cloud/deepseek-v4-flash:preview                              19.7s
    ╰── POST /v1/chat/completions [inference-gateway]                        19.6s
        ╰── POST /proxy/ollama_cloud/chat/completions [inference-gateway]    19.6s [error: *errors.errorString]
            ╰── POST /proxy/:provider/*path [inference-gateway]              19.6s
                ╰── POST /v1/chat/completions [inference-gateway]            19.6s [error: *errors.errorString]
Stats
Tool Calls

╭───────────┬───────┬───────┬──────╮
│ Tool      │ Calls │ Fail% │ Avg  │
├───────────┼───────┼───────┼──────┤
│ Read      │ 27    │ 0%    │ 0ms  │
│ TodoWrite │ 4     │ 0%    │ 0ms  │
│ Bash      │ 3     │ 0%    │ 11ms │
│ Grep      │ 2     │ 0%    │ 18ms │
╰───────────┴───────┴───────┴──────╯

Token Usage

╭────────────────────────────────────────┬─────────┬────────┬────────────┬─────────┬──────╮
│ Model                                  │ Prompt  │ Cached │ Completion │ Total   │ Cost │
├────────────────────────────────────────┼─────────┼────────┼────────────┼─────────┼──────┤
│ ollama_cloud/deepseek-v4-flash:preview │ 1077680 │ 0      │ 7550       │ 1085230 │ -    │
╰────────────────────────────────────────┴─────────┴────────┴────────────┴─────────┴──────╯

Sessions

╭───────────┬──────────┬──────────╮
│ Execution │ Mode     │ Sessions │
├───────────┼──────────┼──────────┤
│ headless  │ headless │ 1        │
╰───────────┴──────────┴──────────╯

Triggered by edenreich · Infer Action · OSS

@edenreich
edenreich merged commit 2b5bffc into main Aug 20, 2026
1 check passed
@edenreich
edenreich deleted the feat/cgo-free-computer-use branch August 20, 2026 16:49
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.178.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released Shipped in a release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Accessibility-tree integration for computer use tools (macOS AX, Linux AT-SPI, Windows UIA)

1 participant