Skip to content

armgit / andee

Public Imported from GitHub
0

Andee lives on your phone or Mac and uses any app like you do—no integrations, no root, any model; memory and passwords never leave your device | Andee 住进你的手机或 Mac,像你一样操作任何 App——无需集成、无需 Root、支持任意模型,记忆和密码绝不离开设备。

feat(desktop): the Mac's screen and device hands

booboosui3626ba90e3b1
diff --git a/desktop/build.gradle b/desktop/build.gradle
index 93c7f1f..9b064a6 100644
--- a/desktop/build.gradle
+++ b/desktop/build.gradle
@@ -15,14 +15,24 @@ kotlin {
// Native helpers, compiled with the Command Line Tools' swiftc (arm64).
def nativeOut = layout.buildDirectory.dir('native')
-tasks.register('buildNative', Exec) {
+tasks.register('buildTrashTool', Exec) {
def src = file('native/trash.swift')
def out = nativeOut.get().file('andee-trash').asFile
inputs.file(src)
outputs.file(out)
doFirst { out.parentFile.mkdirs() }
- commandLine 'swiftc', '-O', '-target', 'arm64-apple-macos13', src.path, '-o', out.path
+ commandLine 'swiftc', '-O', '-target', 'arm64-apple-macos14', src.path, '-o', out.path
}
+// The bridge JNA loads: accessibility tree, input events, ScreenCaptureKit, workspace.
+tasks.register('buildBridge', Exec) {
+ def src = file('native/AndeeMac.swift')
+ def out = nativeOut.get().file('libandeemac.dylib').asFile
+ inputs.file(src)
+ outputs.file(out)
+ doFirst { out.parentFile.mkdirs() }
+ commandLine 'swiftc', '-O', '-target', 'arm64-apple-macos14', '-emit-library', src.path, '-o', out.path
+}
+tasks.register('buildNative') { dependsOn('buildTrashTool', 'buildBridge') }
sourceSets.main.resources.srcDir(nativeOut)
processResources.dependsOn('buildNative')
@@ -31,6 +41,8 @@ dependencies {
implementation compose.desktop.currentOs
// Android has org.json built in; a JVM app has to bring it.
implementation 'org.json:json:20240303'
+ // Calls into native/AndeeMac.swift.
+ implementation 'net.java.dev.jna:jna:5.14.0'
testImplementation libs.junit
}
diff --git a/desktop/native/AndeeMac.swift b/desktop/native/AndeeMac.swift
new file mode 100644
index 0000000..cbfd55d
--- /dev/null
+++ b/desktop/native/AndeeMac.swift
@@ -0,0 +1,312 @@
+// Andee's native bridge on macOS: the things a JVM cannot do cleanly, as C
+// functions the Kotlin side calls through JNA. Every function returns plain
+// values or a malloc'd UTF-8 JSON string the caller frees with andee_free.
+//
+// Built with the Command Line Tools' swiftc (no Xcode):
+// swiftc -O -target arm64-apple-macos14 -emit-library AndeeMac.swift -o libandeemac.dylib
+// macOS 14 is the floor: ScreenCaptureKit's one-shot screenshot arrived there.
+
+import AppKit
+import ApplicationServices
+import CoreGraphics
+import Foundation
+import ScreenCaptureKit
+
+// MARK: - helpers
+
+private func cstr(_ s: String) -> UnsafeMutablePointer<CChar> { strdup(s) }
+
+private func json(_ o: Any) -> UnsafeMutablePointer<CChar> {
+ let data = (try? JSONSerialization.data(withJSONObject: o, options: [])) ?? Data("{}".utf8)
+ return cstr(String(data: data, encoding: .utf8) ?? "{}")
+}
+
+@_cdecl("andee_free")
+public func andee_free(_ p: UnsafeMutablePointer<CChar>?) { free(p) }
+
+// MARK: - permissions
+
+@_cdecl("andee_ax_trusted")
+public func andee_ax_trusted(_ prompt: Int32) -> Int32 {
+ let opts = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: prompt != 0] as CFDictionary
+ return AXIsProcessTrustedWithOptions(opts) ? 1 : 0
+}
+
+@_cdecl("andee_screen_capture_allowed")
+public func andee_screen_capture_allowed(_ request: Int32) -> Int32 {
+ if CGPreflightScreenCaptureAccess() { return 1 }
+ if request != 0 { return CGRequestScreenCaptureAccess() ? 1 : 0 }
+ return 0
+}
+
+// MARK: - display / apps
+
+@_cdecl("andee_main_display")
+public func andee_main_display() -> UnsafeMutablePointer<CChar> {
+ let b = CGDisplayBounds(CGMainDisplayID())
+ let scale = NSScreen.main?.backingScaleFactor ?? 2
+ return json(["x": b.origin.x, "y": b.origin.y, "w": b.width, "h": b.height, "scale": scale])
+}
+
+@_cdecl("andee_frontmost")
+public func andee_frontmost() -> UnsafeMutablePointer<CChar> {
+ guard let app = NSWorkspace.shared.frontmostApplication else { return json([:]) }
+ return json(["name": app.localizedName ?? "", "bundle": app.bundleIdentifier ?? "", "pid": Int(app.processIdentifier)])
+}
+
+@_cdecl("andee_running_apps")
+public func andee_running_apps() -> UnsafeMutablePointer<CChar> {
+ let apps = NSWorkspace.shared.runningApplications.filter { $0.activationPolicy == .regular }
+ return json(apps.map { ["name": $0.localizedName ?? "", "bundle": $0.bundleIdentifier ?? "", "pid": Int($0.processIdentifier), "active": $0.isActive] })
+}
+
+// MARK: - accessibility tree
+
+private func attr(_ e: AXUIElement, _ name: String) -> CFTypeRef? {
+ var v: CFTypeRef?
+ return AXUIElementCopyAttributeValue(e, name as CFString, &v) == .success ? v : nil
+}
+
+private func str(_ e: AXUIElement, _ name: String) -> String? {
+ guard let v = attr(e, name) else { return nil }
+ if let s = v as? String { return s.isEmpty ? nil : s }
+ if let n = v as? NSNumber { return n.stringValue }
+ return nil
+}
+
+private func frame(_ e: AXUIElement) -> CGRect? {
+ guard let p = attr(e, kAXPositionAttribute), let s = attr(e, kAXSizeAttribute) else { return nil }
+ var pt = CGPoint.zero, sz = CGSize.zero
+ AXValueGetValue(p as! AXValue, .cgPoint, &pt)
+ AXValueGetValue(s as! AXValue, .cgSize, &sz)
+ return CGRect(origin: pt, size: sz)
+}
+
+private func actions(_ e: AXUIElement) -> [String] {
+ var names: CFArray?
+ guard AXUIElementCopyActionNames(e, &names) == .success, let a = names as? [String] else { return [] }
+ return a
+}
+
+private var nodeBudget = 0
+
+private func walk(_ e: AXUIElement, depth: Int) -> [String: Any]? {
+ nodeBudget -= 1
+ if nodeBudget < 0 || depth > 40 { return nil }
+ var n: [String: Any] = [:]
+ n["role"] = str(e, kAXRoleAttribute) ?? ""
+ if let sub = str(e, kAXSubroleAttribute) { n["subrole"] = sub }
+ if let t = str(e, kAXTitleAttribute) { n["title"] = t }
+ if let d = str(e, kAXDescriptionAttribute) { n["desc"] = d }
+ if let v = str(e, kAXValueAttribute) { n["value"] = String(v.prefix(200)) }
+ if let h = str(e, kAXHelpAttribute) { n["help"] = String(h.prefix(120)) }
+ if let id = str(e, kAXIdentifierAttribute) { n["id"] = id }
+ if let p = str(e, kAXPlaceholderValueAttribute) { n["placeholder"] = p }
+ if let f = frame(e) { n["frame"] = [f.origin.x, f.origin.y, f.width, f.height] }
+ if let en = attr(e, kAXEnabledAttribute) as? Bool, !en { n["disabled"] = true }
+ if let fo = attr(e, kAXFocusedAttribute) as? Bool, fo { n["focused"] = true }
+ let acts = actions(e)
+ if acts.contains(kAXPressAction as String) { n["press"] = true }
+ if let settable = settableValue(e), settable { n["editable"] = true }
+ if let kids = attr(e, kAXChildrenAttribute) as? [AXUIElement], !kids.isEmpty {
+ let c = kids.compactMap { walk($0, depth: depth + 1) }
+ if !c.isEmpty { n["children"] = c }
+ }
+ return n
+}
+
+private func settableValue(_ e: AXUIElement) -> Bool? {
+ var s: DarwinBoolean = false
+ return AXUIElementIsAttributeSettable(e, kAXValueAttribute as CFString, &s) == .success ? s.boolValue : nil
+}
+
+/** The frontmost app's focused window (or its first window) as a JSON tree. */
+@_cdecl("andee_ax_tree")
+public func andee_ax_tree(_ maxNodes: Int32) -> UnsafeMutablePointer<CChar> {
+ guard let app = NSWorkspace.shared.frontmostApplication else { return json(["error": "no frontmost app"]) }
+ let ax = AXUIElementCreateApplication(app.processIdentifier)
+ // Chromium and Electron build their tree only when asked.
+ AXUIElementSetAttributeValue(ax, "AXManualAccessibility" as CFString, kCFBooleanTrue)
+ AXUIElementSetAttributeValue(ax, "AXEnhancedUserInterface" as CFString, kCFBooleanTrue)
+ var win: AXUIElement? = nil
+ if let w = attr(ax, kAXFocusedWindowAttribute) { win = (w as! AXUIElement) }
+ else if let ws = attr(ax, kAXWindowsAttribute) as? [AXUIElement], let f = ws.first { win = f }
+ nodeBudget = Int(maxNodes)
+ var out: [String: Any] = ["app": app.localizedName ?? "", "bundle": app.bundleIdentifier ?? "", "pid": Int(app.processIdentifier)]
+ if let w = win {
+ out["window_title"] = str(w, kAXTitleAttribute) ?? ""
+ out["tree"] = walk(w, depth: 0) ?? [:]
+ } else {
+ out["tree"] = [:]
+ out["no_window"] = true
+ }
+ // The menu bar is part of the app a person can reach.
+ if let mb = attr(ax, kAXMenuBarAttribute) {
+ nodeBudget = 400
+ out["menubar"] = walk(mb as! AXUIElement, depth: 0) ?? [:]
+ }
+ out["truncated"] = nodeBudget < 0
+ return json(out)
+}
+
+/** Press the element at an index path from the last tree (child indices from the window root). */
+@_cdecl("andee_ax_press_at")
+public func andee_ax_press_at(_ x: Double, _ y: Double) -> Int32 {
+ let sys = AXUIElementCreateSystemWide()
+ var el: AXUIElement?
+ guard AXUIElementCopyElementAtPosition(sys, Float(x), Float(y), &el) == .success, let e = el else { return 0 }
+ return AXUIElementPerformAction(e, kAXPressAction as CFString) == .success ? 1 : 0
+}
+
+/** Set the focused element's value (a text field), as a person pasting it would. */
+@_cdecl("andee_ax_set_focused_value")
+public func andee_ax_set_focused_value(_ text: UnsafePointer<CChar>) -> Int32 {
+ let sys = AXUIElementCreateSystemWide()
+ guard let f = attr(sys, kAXFocusedUIElementAttribute) else { return 0 }
+ let e = f as! AXUIElement
+ return AXUIElementSetAttributeValue(e, kAXValueAttribute as CFString, String(cString: text) as CFString) == .success ? 1 : 0
+}
+
+@_cdecl("andee_ax_focused_value")
+public func andee_ax_focused_value() -> UnsafeMutablePointer<CChar> {
+ let sys = AXUIElementCreateSystemWide()
+ guard let f = attr(sys, kAXFocusedUIElementAttribute) else { return json(["focused": false]) }
+ let e = f as! AXUIElement
+ return json(["focused": true, "role": str(e, kAXRoleAttribute) ?? "", "value": str(e, kAXValueAttribute) ?? ""])
+}
+
+// MARK: - input events (points in global display coordinates, top-left origin)
+
+private func post(_ e: CGEvent?) { e?.post(tap: .cghidEventTap) }
+
+@_cdecl("andee_click")
+public func andee_click(_ x: Double, _ y: Double, _ button: Int32, _ count: Int32, _ holdMs: Int32) {
+ let p = CGPoint(x: x, y: y)
+ let (down, up, b): (CGEventType, CGEventType, CGMouseButton) =
+ button == 1 ? (.rightMouseDown, .rightMouseUp, .right) : (.leftMouseDown, .leftMouseUp, .left)
+ post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: p, mouseButton: b))
+ usleep(30_000)
+ for i in 1...max(1, Int(count)) {
+ let d = CGEvent(mouseEventSource: nil, mouseType: down, mouseCursorPosition: p, mouseButton: b)
+ d?.setIntegerValueField(.mouseEventClickState, value: Int64(i))
+ post(d)
+ usleep(useconds_t(max(30, Int(holdMs)) * 1000))
+ let u = CGEvent(mouseEventSource: nil, mouseType: up, mouseCursorPosition: p, mouseButton: b)
+ u?.setIntegerValueField(.mouseEventClickState, value: Int64(i))
+ post(u)
+ usleep(60_000)
+ }
+}
+
+@_cdecl("andee_drag")
+public func andee_drag(_ x1: Double, _ y1: Double, _ x2: Double, _ y2: Double, _ ms: Int32) {
+ let steps = max(8, Int(ms) / 16)
+ post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: CGPoint(x: x1, y: y1), mouseButton: .left))
+ for i in 1...steps {
+ let t = Double(i) / Double(steps)
+ let p = CGPoint(x: x1 + (x2 - x1) * t, y: y1 + (y2 - y1) * t)
+ post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDragged, mouseCursorPosition: p, mouseButton: .left))
+ usleep(useconds_t(max(1, Int(ms) / steps) * 1000))
+ }
+ usleep(120_000)
+ post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: CGPoint(x: x2, y: y2), mouseButton: .left))
+}
+
+/** Scroll by [dy]/[dx] pixels at a point, in small steps so lists move as far as asked and no further. */
+@_cdecl("andee_scroll")
+public func andee_scroll(_ x: Double, _ y: Double, _ dx: Int32, _ dy: Int32) {
+ post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: CGPoint(x: x, y: y), mouseButton: .left))
+ usleep(30_000)
+ let steps = 10
+ for _ in 0..<steps {
+ let e = CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 2,
+ wheel1: dy / Int32(steps), wheel2: dx / Int32(steps), wheel3: 0)
+ post(e)
+ usleep(16_000)
+ }
+}
+
+/** Type text as keystrokes carrying Unicode, which works in any field regardless of keyboard layout. */
+@_cdecl("andee_type_text")
+public func andee_type_text(_ text: UnsafePointer<CChar>) {
+ let s = Array(String(cString: text).utf16)
+ var i = 0
+ while i < s.count {
+ let chunk = Array(s[i..<min(i + 16, s.count)])
+ let d = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true)
+ chunk.withUnsafeBufferPointer { d?.keyboardSetUnicodeString(stringLength: chunk.count, unicodeString: $0.baseAddress) }
+ post(d)
+ let u = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)
+ post(u)
+ usleep(8_000)
+ i += 16
+ }
+}
+
+/** A key with modifiers: flags bit 0 cmd, 1 shift, 2 option, 3 control. */
+@_cdecl("andee_key")
+public func andee_key(_ keyCode: Int32, _ flags: Int32) {
+ var f: CGEventFlags = []
+ if flags & 1 != 0 { f.insert(.maskCommand) }
+ if flags & 2 != 0 { f.insert(.maskShift) }
+ if flags & 4 != 0 { f.insert(.maskAlternate) }
+ if flags & 8 != 0 { f.insert(.maskControl) }
+ let d = CGEvent(keyboardEventSource: nil, virtualKey: CGKeyCode(keyCode), keyDown: true)
+ d?.flags = f
+ post(d)
+ let u = CGEvent(keyboardEventSource: nil, virtualKey: CGKeyCode(keyCode), keyDown: false)
+ u?.flags = f
+ post(u)
+}
+
+// MARK: - screenshots (ScreenCaptureKit, our own windows excluded)
+
+/**
+ * Capture the main display to a PNG at [path], leaving out every window of
+ * this process — the ball and the cards are never in the picture.
+ * Returns 1 on success.
+ */
+@_cdecl("andee_screenshot")
+public func andee_screenshot(_ path: UnsafePointer<CChar>, _ maxSide: Int32) -> Int32 {
+ let out = URL(fileURLWithPath: String(cString: path))
+ let sem = DispatchSemaphore(value: 0)
+ final class Box: @unchecked Sendable { var ok: Int32 = 0 }
+ let box = Box()
+ Task {
+ defer { sem.signal() }
+ do {
+ let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true)
+ guard let display = content.displays.first(where: { $0.displayID == CGMainDisplayID() }) ?? content.displays.first else { return }
+ let mine = content.applications.filter { $0.processID == getpid() }
+ let filter = SCContentFilter(display: display, excludingApplications: mine, exceptingWindows: [])
+ let cfg = SCStreamConfiguration()
+ let scale = NSScreen.main?.backingScaleFactor ?? 2
+ var w = Double(display.width) * scale, h = Double(display.height) * scale
+ let longSide = max(w, h)
+ if maxSide > 0 && longSide > Double(maxSide) { let k = Double(maxSide) / longSide; w *= k; h *= k }
+ cfg.width = Int(w); cfg.height = Int(h)
+ cfg.showsCursor = false
+ let img = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: cfg)
+ let rep = NSBitmapImageRep(cgImage: img)
+ if let png = rep.representation(using: .png, properties: [:]) { try png.write(to: out); box.ok = 1 }
+ } catch {
+ FileHandle.standardError.write("screenshot: \(error)\n".data(using: .utf8)!)
+ }
+ }
+ _ = sem.wait(timeout: .now() + 10)
+ return box.ok
+}
+
+// MARK: - workspace
+
+@_cdecl("andee_open")
+public func andee_open(_ target: UnsafePointer<CChar>) -> Int32 {
+ let t = String(cString: target)
+ if let u = URL(string: t), u.scheme != nil { return NSWorkspace.shared.open(u) ? 1 : 0 }
+ if let u = NSWorkspace.shared.urlForApplication(withBundleIdentifier: t) {
+ let sem = DispatchSemaphore(value: 0); var ok: Int32 = 0
+ NSWorkspace.shared.openApplication(at: u, configuration: NSWorkspace.OpenConfiguration()) { app, _ in ok = app != nil ? 1 : 0; sem.signal() }
+ _ = sem.wait(timeout: .now() + 10); return ok
+ }
+ return NSWorkspace.shared.open(URL(fileURLWithPath: t)) ? 1 : 0
+}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
index 9f7c384..a90850c 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Assistant.kt
@@ -37,6 +37,20 @@ object Assistant {
)
}
+ /** Hides Andee's own windows for the instant of a click; set by the window. */
+ @Volatile var hideWindows: (Boolean) -> Unit = {}
+
+ /** The screen hand: accessibility tree, clicks, keys and screenshots. */
+ val screen: net.kuafuai.andee.desktop.mac.MacScreen by lazy {
+ net.kuafuai.andee.desktop.mac.MacScreen { hide -> hideWindows(hide) }
+ }
+
+ /** Apps, calendar, reminders, contacts, volume, battery and the vault. */
+ val device: net.kuafuai.andee.desktop.mac.MacDevice by lazy {
+ net.kuafuai.andee.desktop.mac.MacVault.entries()
+ net.kuafuai.andee.desktop.mac.MacDevice()
+ }
+
/** Values that must never reach the model or a log: Andee's own keys, then the vault. */
private fun secrets(): List<Pair<String, String>> = buildList {
Settings.get("llm_api_key").takeIf { it.length >= 8 }?.let { add("Andee's model key" to it) }
@@ -71,6 +85,8 @@ object Assistant {
notes.dispatch(method, p, silent, untrusted)
},
shell,
+ screen,
+ device,
)
}
@@ -89,7 +105,7 @@ object Assistant {
Log.i(TAG, "building the brain (${cfg.mode}, ${cfg.model})")
val b = LocalBrain(
cfg = cfg,
- host = DesktopBrainHost(providers(), MacPrompt.Capabilities(shell = true)),
+ host = DesktopBrainHost(providers(), MacPrompt.Capabilities(shell = true, screen = true)),
onProgress = { onProgress(it) },
onFinal = { text ->
Scrollback.add(Scrollback.Role.ASSISTANT, text)
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacPrompt.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacPrompt.kt
index 3eb407b..ad672ed 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacPrompt.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/MacPrompt.kt
@@ -25,7 +25,15 @@ What you can do here, right now, is exactly what your tool list contains — not
)
append("\n\n")
if (caps.screen) {
- append("- You can see and operate the Mac's screen: the tools whose names mention the screen work on this Mac, with the same grid and 0-1000 coordinates.\n")
+ append(
+ "- You can see and operate the Mac's screen with the same tools and the same grid and 0-1000 coordinates. " +
+ "On a Mac: a tap is a mouse click; long_press is a right-click (the context menu); swipe scrolls what is " +
+ "under its start point by that distance; system_action back is ⌘[ (Back in browsers and Finder — many " +
+ "apps have none, prefer a visible button or Esc), home shows the desktop. launch_app takes a bundle id " +
+ "(com.apple.Safari) or an app name. Prefer keyboard shortcuts and the menu bar (it is in the element list) " +
+ "over hunting for small icons. Anything a command can do (open -a, open URL, mdfind) is usually faster " +
+ "than clicking.\n",
+ )
} else {
append("- **You cannot see or operate this Mac's screen yet.** There are no screen tools on this device. Do not offer to open, tap, click, type into or look at anything on the screen, and do not say you did.\n")
}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
index 792445a..9327805 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Main.kt
@@ -27,6 +27,11 @@ fun main() {
title = "Andee",
state = rememberWindowState(width = 520.dp, height = 760.dp),
) {
+ // A click aimed at another app must not land on Andee: step aside for the instant of it.
+ val w = this.window
+ Assistant.hideWindows = { hide ->
+ javax.swing.SwingUtilities.invokeAndWait { w.opacity = if (hide) 0f else 1f }
+ }
androidx.compose.foundation.layout.Box {
if (settings) SettingsScreen { settings = false } else ChatScreen { settings = true }
pending?.let { ApprovalCard(it) }
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt
new file mode 100644
index 0000000..79b1edf
--- /dev/null
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt
@@ -0,0 +1,101 @@
+package net.kuafuai.andee.desktop.mac
+
+import com.sun.jna.Library
+import com.sun.jna.Native
+import com.sun.jna.Pointer
+import net.kuafuai.andee.util.Log
+import org.json.JSONArray
+import org.json.JSONObject
+import java.io.File
+
+/**
+ * The native bridge (desktop/native/AndeeMac.swift), loaded through JNA.
+ * Strings that come back are malloc'd JSON; [Bridge] frees them.
+ */
+object Bridge {
+
+ private interface Lib : Library {
+ fun andee_free(p: Pointer?)
+ fun andee_ax_trusted(prompt: Int): Int
+ fun andee_screen_capture_allowed(request: Int): Int
+ fun andee_main_display(): Pointer
+ fun andee_frontmost(): Pointer
+ fun andee_running_apps(): Pointer
+ fun andee_ax_tree(maxNodes: Int): Pointer
+ fun andee_ax_press_at(x: Double, y: Double): Int
+ fun andee_ax_set_focused_value(text: String): Int
+ fun andee_ax_focused_value(): Pointer
+ fun andee_click(x: Double, y: Double, button: Int, count: Int, holdMs: Int)
+ fun andee_drag(x1: Double, y1: Double, x2: Double, y2: Double, ms: Int)
+ fun andee_scroll(x: Double, y: Double, dx: Int, dy: Int)
+ fun andee_type_text(text: String)
+ fun andee_key(keyCode: Int, flags: Int)
+ fun andee_screenshot(path: String, maxSide: Int): Int
+ fun andee_open(target: String): Int
+ }
+
+ private val lib: Lib? by lazy {
+ val f = locate()
+ if (f == null) {
+ Log.e("Bridge", "libandeemac.dylib not found; screen tools are unavailable")
+ null
+ } else {
+ runCatching { Native.load(f.path, Lib::class.java) }
+ .onFailure { Log.e("Bridge", "could not load ${f.path}", it) }.getOrNull()
+ }
+ }
+
+ val available: Boolean get() = lib != null
+
+ private fun locate(): File? {
+ System.getProperty("compose.application.resources.dir")?.let { File(it, "libandeemac.dylib") }
+ ?.takeIf { it.exists() }?.let { return it }
+ val cached = File(System.getProperty("user.home"), "Library/Andee-shell/libandeemac.dylib")
+ val res = Bridge::class.java.getResourceAsStream("/libandeemac.dylib") ?: return cached.takeIf { it.exists() }
+ res.use { input -> cached.parentFile.mkdirs(); cached.outputStream().use { input.copyTo(it) } }
+ return cached
+ }
+
+ private fun need(): Lib = lib ?: throw IllegalStateException(
+ "The Mac screen bridge is not loaded on this install, so screen tools cannot run. Say so to the user.",
+ )
+
+ private fun str(p: Pointer): String = try { p.getString(0, "UTF-8") } finally { need().andee_free(p) }
+
+ fun axTrusted(prompt: Boolean = false) = lib?.andee_ax_trusted(if (prompt) 1 else 0) == 1
+ fun screenCaptureAllowed(request: Boolean = false) = lib?.andee_screen_capture_allowed(if (request) 1 else 0) == 1
+ fun display(): JSONObject = JSONObject(str(need().andee_main_display()))
+ fun frontmost(): JSONObject = JSONObject(str(need().andee_frontmost()))
+ fun runningApps(): JSONArray = JSONArray(str(need().andee_running_apps()))
+ fun axTree(maxNodes: Int): JSONObject = JSONObject(str(need().andee_ax_tree(maxNodes)))
+ fun axPressAt(x: Double, y: Double) = need().andee_ax_press_at(x, y) == 1
+ fun setFocusedValue(text: String) = need().andee_ax_set_focused_value(text) == 1
+ fun focusedValue(): JSONObject = JSONObject(str(need().andee_ax_focused_value()))
+ fun click(x: Double, y: Double, right: Boolean = false, count: Int = 1, holdMs: Int = 40) =
+ need().andee_click(x, y, if (right) 1 else 0, count, holdMs)
+ fun drag(x1: Double, y1: Double, x2: Double, y2: Double, ms: Int) = need().andee_drag(x1, y1, x2, y2, ms)
+ fun scroll(x: Double, y: Double, dx: Int, dy: Int) = need().andee_scroll(x, y, dx, dy)
+ fun typeText(text: String) = need().andee_type_text(text)
+ fun key(code: Int, flags: Int = 0) = need().andee_key(code, flags)
+ fun screenshot(path: String, maxSide: Int) = need().andee_screenshot(path, maxSide) == 1
+ fun open(target: String) = need().andee_open(target) == 1
+
+ /** macOS virtual key codes the tools use. */
+ object Keys {
+ const val RETURN = 36
+ const val TAB = 48
+ const val ESCAPE = 53
+ const val DELETE = 51
+ const val LEFT_BRACKET = 33
+ const val A = 0
+ const val V = 9
+ const val SPACE = 49
+ const val F3 = 160
+ const val UP = 126
+ const val DOWN = 125
+ const val CMD = 1
+ const val SHIFT = 2
+ const val OPTION = 4
+ const val CONTROL = 8
+ }
+}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacDevice.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacDevice.kt
new file mode 100644
index 0000000..cee0edd
--- /dev/null
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacDevice.kt
@@ -0,0 +1,305 @@
+package net.kuafuai.andee.desktop.mac
+
+import net.kuafuai.andee.desktop.DesktopBrainHost
+import net.kuafuai.andee.desktop.EncryptedFileStore
+import net.kuafuai.andee.desktop.AppDirs
+import net.kuafuai.andee.desktop.Scrollback
+import net.kuafuai.andee.desktop.VaultSecrets
+import net.kuafuai.andee.util.Log
+import org.json.JSONArray
+import org.json.JSONObject
+import java.io.File
+import java.net.InetSocketAddress
+import java.net.Socket
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+import java.util.concurrent.TimeUnit
+
+/**
+ * The `device.*` tools that mean something on a Mac. The ones that do not —
+ * SMS, calls, call log, step counter, motion sensors, the camera scanner — are
+ * simply not registered, so the model never sees them (a listed tool that
+ * cannot work is a promise the model makes and breaks).
+ *
+ * Calendar, reminders and contacts go through the Mac's own apps with
+ * AppleScript; the first use asks the user for Automation permission, which
+ * is the honest place for that question.
+ */
+class MacDevice : DesktopBrainHost.ToolProvider {
+
+ override fun handles(method: String) = method in METHODS
+
+ override fun dispatch(method: String, p: JSONObject, silent: Boolean, untrusted: Boolean): Any? = when (method) {
+ "device.launch" -> launch(p)
+ "device.open_url" -> openUrl(p.optString("url"))
+ "device.apps" -> apps()
+ "device.battery" -> battery()
+ "device.connectivity" -> connectivity()
+ "device.volume" -> volume(p)
+ "device.facts" -> facts()
+ "device.calendar" -> calendar(p.optInt("days_ahead", 7))
+ "device.calendar.add" -> addEvent(p)
+ "device.alarm" -> reminder(p)
+ "device.contacts" -> contacts(p.optString("query"))
+ "device.permissions" -> permissions()
+ "device.vault.list" -> MacVault.list()
+ "device.vault.get" -> MacVault.get(p.optString("entry"), p.optString("field"))
+ "device.vault.fill" -> MacVault.fill(p.optString("entry"))
+ else -> throw IllegalArgumentException("unknown method $method")
+ }
+
+ private fun launch(p: JSONObject): JSONObject {
+ val target = p.optString("pkg").ifBlank { p.optString("label") }.trim()
+ require(target.isNotEmpty()) { "launch_app needs pkg (a bundle id like com.apple.Safari) or label (an app name)" }
+ val ok = if (target.contains('.') && !target.contains(' ')) Bridge.open(target) || openA(target) else openA(target)
+ if (!ok) throw IllegalArgumentException("No app called \"$target\" here. list_installed_apps shows what is installed.")
+ Thread.sleep(800)
+ return JSONObject().put("launched", target).put("front_app", Bridge.frontmost().optString("name"))
+ }
+
+ private fun openA(name: String): Boolean = run("/usr/bin/open", "-a", name).first == 0
+
+ private fun openUrl(url: String): JSONObject {
+ require(Regex("^[a-zA-Z][a-zA-Z0-9+.-]*:").containsMatchIn(url)) { "url must be absolute, e.g. https://…" }
+ require(Bridge.open(url)) { "could not open $url" }
+ return JSONObject().put("opened", url)
+ }
+
+ private fun apps(): JSONObject {
+ val arr = JSONArray()
+ val dirs = listOf(File("/Applications"), File("/System/Applications"), File(System.getProperty("user.home"), "Applications"))
+ for (d in dirs) d.listFiles { f -> f.name.endsWith(".app") }?.sortedBy { it.name }?.forEach { app ->
+ val id = run("/usr/bin/mdls", "-raw", "-name", "kMDItemCFBundleIdentifier", app.path).second.trim()
+ arr.put(JSONObject().put("label", app.name.removeSuffix(".app")).put("pkg", if (id == "(null)") "" else id))
+ }
+ return JSONObject().put("apps", arr).put("count", arr.length())
+ }
+
+ private fun battery(): JSONObject {
+ val out = run("/usr/bin/pmset", "-g", "batt").second
+ val pct = Regex("(\\d+)%").find(out)?.groupValues?.get(1)?.toIntOrNull()
+ return JSONObject().put("percent", pct ?: JSONObject.NULL)
+ .put("charging", out.contains("charging") && !out.contains("discharging") || out.contains("charged"))
+ .put("plugged", out.contains("AC Power"))
+ .apply { if (pct == null) put("note", "This Mac has no battery.") }
+ }
+
+ private fun connectivity(): JSONObject {
+ val online = runCatching { Socket().use { it.connect(InetSocketAddress("223.5.5.5", 53), 2000); true } }.getOrDefault(false) ||
+ runCatching { Socket().use { it.connect(InetSocketAddress("1.1.1.1", 53), 2000); true } }.getOrDefault(false)
+ val wifi = run("/usr/sbin/networksetup", "-getairportnetwork", "en0").second
+ val type = when {
+ wifi.contains("Current Wi-Fi Network") -> "wifi"
+ online -> "ethernet"
+ else -> "none"
+ }
+ return JSONObject().put("online", online).put("type", type)
+ }
+
+ private fun volume(p: JSONObject): JSONObject {
+ if (p.has("mute")) osa("set volume output muted ${p.optBoolean("mute")}")
+ if (p.has("level")) osa("set volume output volume ${p.optInt("level").coerceIn(0, 100)}")
+ val now = osa("output volume of (get volume settings)").trim()
+ return JSONObject().put("level", now.toIntOrNull() ?: JSONObject.NULL)
+ .put("muted", osa("output muted of (get volume settings)").trim() == "true")
+ }
+
+ private fun facts(): JSONObject = JSONObject()
+ .put("device", "Mac").put("model", run("/usr/sbin/sysctl", "-n", "hw.model").second.trim())
+ .put("os", "macOS " + run("/usr/bin/sw_vers", "-productVersion").second.trim())
+ .put("name", run("/usr/sbin/scutil", "--get", "ComputerName").second.trim())
+ .put("now", SimpleDateFormat("yyyy-MM-dd EEE HH:mm", Locale.US).format(Date()))
+ .put("display", Bridge.display())
+
+ // ---- calendar / reminders / contacts via the Mac's apps -------------------
+
+ private fun calendar(days: Int): JSONObject {
+ val d = days.coerceIn(0, 60)
+ val script = """
+ set out to ""
+ set t0 to current date
+ set t1 to t0 + ($d * days)
+ tell application "Calendar"
+ repeat with c in calendars
+ repeat with e in (every event of c whose start date ≥ t0 and start date ≤ t1)
+ set out to out & (summary of e) & tab & ((start date of e) as «class isot» as string) & tab & ((end date of e) as «class isot» as string) & tab & (name of c) & linefeed
+ end repeat
+ end repeat
+ end tell
+ return out
+ """.trimIndent()
+ val arr = JSONArray()
+ for (line in osa(script, timeoutS = 30).lines().filter { it.isNotBlank() }) {
+ val f = line.split('\t')
+ arr.put(JSONObject().put("title", f.getOrElse(0) { "" }).put("begin", f.getOrElse(1) { "" })
+ .put("end", f.getOrElse(2) { "" }).put("calendar", f.getOrElse(3) { "" }))
+ }
+ return JSONObject().put("events", arr).put("count", arr.length()).put("days_ahead", d)
+ }
+
+ private fun addEvent(p: JSONObject): JSONObject {
+ val title = p.optString("title").trim().ifEmpty { throw IllegalArgumentException("title is required") }
+ val begin = p.optLong("begin_ms", 0L).takeIf { it > 0 } ?: throw IllegalArgumentException("begin_ms is required")
+ val end = p.optLong("end_ms", begin + 3_600_000L)
+ fun asDate(ms: Long) = "(date \"" + SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date(ms)) + "\")"
+ val loc = p.optString("location").replace("\"", "'")
+ val desc = p.optString("description").replace("\"", "'")
+ osa(
+ """
+ tell application "Calendar"
+ tell (first calendar whose writable is true)
+ make new event with properties {summary:"${title.replace("\"", "'")}", start date:${asDate(begin)}, end date:${asDate(end)}, location:"$loc", description:"$desc"}
+ end tell
+ end tell
+ """.trimIndent(),
+ timeoutS = 20,
+ )
+ return JSONObject().put("added", true).put("title", title).put("begin", Date(begin).toString())
+ }
+
+ /** "Set an alarm" on a Mac is a Reminders reminder with an alert. */
+ private fun reminder(p: JSONObject): JSONObject {
+ val h = p.optInt("hour", -1); val m = p.optInt("minutes", p.optInt("minute", 0))
+ require(h in 0..23) { "hour 0-23 is required" }
+ val label = p.optString("label").ifBlank { p.optString("message") }.ifBlank { "Andee" }.replace("\"", "'")
+ osa(
+ """
+ set d to current date
+ set hours of d to $h
+ set minutes of d to $m
+ set seconds of d to 0
+ if d < (current date) then set d to d + (1 * days)
+ tell application "Reminders" to make new reminder with properties {name:"$label", remind me date:d}
+ """.trimIndent(),
+ timeoutS = 20,
+ )
+ return JSONObject().put("set", true).put("time", String.format("%02d:%02d", h, m)).put("label", label)
+ .put("note", "On a Mac this is a Reminders reminder with an alert, not an alarm clock.")
+ }
+
+ private fun contacts(query: String): JSONObject {
+ val q = query.replace("\"", "'").trim()
+ val script = """
+ set out to ""
+ tell application "Contacts"
+ repeat with p in (every person whose name contains "$q")
+ set ph to ""
+ repeat with x in phones of p
+ set ph to ph & (value of x) & ","
+ end repeat
+ set em to ""
+ repeat with x in emails of p
+ set em to em & (value of x) & ","
+ end repeat
+ set out to out & (name of p) & tab & ph & tab & em & linefeed
+ end repeat
+ end tell
+ return out
+ """.trimIndent()
+ val arr = JSONArray()
+ for (line in osa(script, timeoutS = 30).lines().filter { it.isNotBlank() }.take(20)) {
+ val f = line.split('\t')
+ arr.put(JSONObject().put("name", f.getOrElse(0) { "" })
+ .put("phones", JSONArray(f.getOrElse(1) { "" }.split(',').filter { it.isNotBlank() }))
+ .put("emails", JSONArray(f.getOrElse(2) { "" }.split(',').filter { it.isNotBlank() })))
+ }
+ return JSONObject().put("contacts", arr).put("count", arr.length())
+ }
+
+ private fun permissions(): JSONObject {
+ val granted = JSONArray(); val missing = JSONArray()
+ (if (Bridge.axTrusted()) granted else missing).put(JSONObject().put("id", "accessibility").put("feature", "operate other apps"))
+ (if (Bridge.screenCaptureAllowed()) granted else missing).put(JSONObject().put("id", "screen_recording").put("feature", "see the screen"))
+ return JSONObject().put("granted", granted).put("missing", missing)
+ .put("note", "Calendar, Reminders and Contacts ask for permission the first time they are used. " +
+ "Missing ones are granted in System Settings → Privacy & Security; Andee's ✓ check card has buttons.")
+ }
+
+ // ---- helpers --------------------------------------------------------------
+
+ private fun run(vararg cmd: String): Pair<Int, String> = runCatching {
+ val p = ProcessBuilder(*cmd).redirectErrorStream(true).start()
+ val out = p.inputStream.bufferedReader().readText()
+ if (!p.waitFor(20, TimeUnit.SECONDS)) { p.destroyForcibly(); -1 to out } else p.exitValue() to out
+ }.getOrDefault(-1 to "")
+
+ private fun osa(script: String, timeoutS: Long = 10): String {
+ val p = ProcessBuilder("/usr/bin/osascript", "-e", script).redirectErrorStream(true).start()
+ val out = p.inputStream.bufferedReader().readText()
+ if (!p.waitFor(timeoutS, TimeUnit.SECONDS)) { p.destroyForcibly(); throw IllegalStateException("timed out waiting for the app") }
+ if (p.exitValue() != 0) {
+ if (out.contains("-1743") || out.contains("not allowed")) throw IllegalStateException(
+ "macOS has not given Andee permission to control that app. The user can allow it in System Settings → " +
+ "Privacy & Security → Automation (Andee → that app).",
+ )
+ throw IllegalStateException(out.trim().take(300))
+ }
+ return out
+ }
+
+ companion object {
+ val METHODS = setOf(
+ "device.launch", "device.open_url", "device.apps", "device.battery", "device.connectivity", "device.volume",
+ "device.facts", "device.calendar", "device.calendar.add", "device.alarm", "device.contacts",
+ "device.permissions", "device.vault.list", "device.vault.get", "device.vault.fill",
+ )
+ }
+}
+
+/**
+ * The user's own accounts on the Mac: one encrypted file under a Keychain key,
+ * the same rules as the phone's vault. `get` refuses the password outright;
+ * `fill` types it into the focused field and never returns it.
+ */
+object MacVault {
+
+ private val store = EncryptedFileStore(AppDirs.file("vault.enc"), "vault-key")
+
+ init {
+ VaultSecrets.source = { entries().flatMap { e -> listOfNotNull(e.optString("password").takeIf { it.isNotEmpty() }?.let { "vault «${e.optString("label")}»" to it }) } }
+ }
+
+ fun entries(): List<JSONObject> {
+ val raw = store.read() ?: return emptyList()
+ val a = runCatching { JSONArray(raw) }.getOrDefault(JSONArray())
+ return (0 until a.length()).map { a.getJSONObject(it) }
+ }
+
+ fun save(all: List<JSONObject>) {
+ check(store.write(JSONArray(all).toString())) { "the vault could not be saved (is the login Keychain locked?)" }
+ }
+
+ private fun mask(s: String) = if (s.length <= 4) "••••" else s.take(2) + "•".repeat((s.length - 4).coerceAtMost(6)) + s.takeLast(2)
+
+ fun list(): JSONObject {
+ val arr = JSONArray()
+ for (e in entries()) arr.put(
+ JSONObject().put("entry", e.optString("label"))
+ .put("username", mask(e.optString("username"))).put("phone", mask(e.optString("phone")))
+ .put("email", mask(e.optString("email"))).put("has_password", e.optString("password").isNotEmpty()),
+ )
+ return JSONObject().put("entries", arr).put("count", arr.length())
+ }
+
+ private fun find(label: String) = entries().firstOrNull { it.optString("label") == label }
+ ?: throw IllegalArgumentException("No vault entry called \"$label\" — list_vault shows the names.")
+
+ fun get(label: String, field: String): JSONObject {
+ val f = field.ifBlank { "username" }
+ require(f != "password") { "Passwords are never read out. Use fill_secret with the field focused." }
+ val e = find(label)
+ return JSONObject().put("entry", label).put("field", f).put("value", e.optString(f))
+ }
+
+ fun fill(label: String): JSONObject {
+ val pw = find(label).optString("password")
+ require(pw.isNotEmpty()) { "That entry has no password saved." }
+ require(Bridge.focusedValue().optBoolean("focused")) { "Click into the password field first." }
+ Scrollback.add(Scrollback.Role.ASSISTANT, "🔐 正在填入「$label」的密码… / filling the password for “$label”…")
+ val ok = Bridge.setFocusedValue(pw) || run { Bridge.typeText(pw); true }
+ val len = Bridge.focusedValue().optString("value").length
+ Log.i("Vault", "filled $label (${pw.length} chars)")
+ return JSONObject().put("performed", ok).put("len", pw.length).put("field_len", len)
+ }
+}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacScreen.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacScreen.kt
new file mode 100644
index 0000000..0341da2
--- /dev/null
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacScreen.kt
@@ -0,0 +1,414 @@
+package net.kuafuai.andee.desktop.mac
+
+import net.kuafuai.andee.desktop.DesktopBrainHost
+import net.kuafuai.andee.screen.AimParts
+import net.kuafuai.andee.util.Log
+import org.json.JSONArray
+import org.json.JSONObject
+import java.awt.BasicStroke
+import java.awt.Color
+import java.awt.Font
+import java.awt.RenderingHints
+import java.awt.image.BufferedImage
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.util.Base64
+import javax.imageio.ImageIO
+
+/**
+ * The `screen.*` tools on a Mac, speaking the phone's protocol exactly: an
+ * element outline with e-numbers, 0-1000 coordinates of the main display, an
+ * 8x12 aim grid on every screenshot, zoom with a crosshair, and the same
+ * guards (values outside 0-1000 are refused, the fourth tap on one spot within
+ * five minutes is refused).
+ *
+ * What a tap does here: an e-number press uses the element's own Press action
+ * when it has one (nothing can land on the wrong thing), and otherwise clicks
+ * its centre. A coordinate tap is a real mouse click.
+ */
+class MacScreen(
+ /** Hide our own windows for a gesture or a capture, and show them again after. */
+ private val hideOwnWindows: (Boolean) -> Unit,
+) : DesktopBrainHost.ToolProvider {
+
+ private data class El(val eid: String, val cx: Double, val cy: Double, val press: Boolean, val editable: Boolean, val label: String)
+
+ @Volatile private var index: Map<String, El> = emptyMap()
+ @Volatile private var zoomRegion: IntArray? = null
+ @Volatile private var zoomAt = 0L
+ private val spots = HashMap<String, MutableList<Long>>()
+
+ override fun handles(method: String) = method in METHODS
+
+ override fun dispatch(method: String, p: JSONObject, silent: Boolean, untrusted: Boolean): Any? {
+ if (!Bridge.available) throw IllegalStateException("The Mac screen bridge did not load; screen tools cannot run here.")
+ if (!Bridge.axTrusted()) throw IllegalStateException(
+ "Andee does not have Accessibility permission on this Mac, so it cannot read or operate the screen. " +
+ "Tell the user to allow it in System Settings → Privacy & Security → Accessibility (Andee's ✓ check card has a button).",
+ )
+ return when (method) {
+ "screen.ui_tree" -> uiTree(p.optBoolean("with_shot", false))
+ "screen.tap_id" -> tapId(req(p, "eid"), long = false)
+ "screen.long_press_id" -> tapId(req(p, "eid"), long = true)
+ "screen.tap" -> tapAim(p, long = false)
+ "screen.long_press" -> tapAim(p, long = true)
+ "screen.swipe" -> swipe(p)
+ "screen.type" -> type(p.optString("text"))
+ "screen.submit_input" -> submit()
+ "screen.wait" -> waitFor(p.optDouble("seconds", 2.0))
+ "screen.screenshot" -> screenshot(grid = true)
+ "screen.look_region" -> lookRegion(p)
+ "screen.global" -> global(req(p, "action"))
+ else -> throw IllegalArgumentException("unknown method $method")
+ }
+ }
+
+ // ---- geometry ----------------------------------------------------------
+
+ private val display: JSONObject get() = Bridge.display()
+ private fun dw() = display.getDouble("w")
+ private fun dh() = display.getDouble("h")
+ private fun toPx(nx: Int, ny: Int) = (nx / 1000.0 * dw()) to (ny / 1000.0 * dh())
+ private fun toNorm(x: Double, y: Double) = (x / dw() * 1000).toInt().coerceIn(0, 1000) to (y / dh() * 1000).toInt().coerceIn(0, 1000)
+
+ private fun requireNorm(v: Int, name: String) {
+ require(v in 0..1000) { "$name=$v is outside 0-1000. Coordinates are relative to the screen, 0 to 1000; read them off the grid." }
+ }
+
+ // ---- the outline ---------------------------------------------------------
+
+ private fun uiTree(withShot: Boolean): JSONObject {
+ val raw = Bridge.axTree(1500)
+ val lines = mutableListOf<String>()
+ val idx = LinkedHashMap<String, El>()
+ var total = 0
+ var n = 0
+ fun visit(o: JSONObject, depth: Int) {
+ total++
+ val f = o.optJSONArray("frame")
+ val role = o.optString("role").removePrefix("AX")
+ val label = listOf("title", "desc", "value", "placeholder", "help").map { o.optString(it) }.firstOrNull { it.isNotBlank() }
+ ?: o.optString("id").takeIf { it.isNotBlank() }?.let { "#$it" } ?: ""
+ val visible = f != null && f.getDouble(2) > 1 && f.getDouble(3) > 1 &&
+ f.getDouble(0) < dw() && f.getDouble(1) < dh() && f.getDouble(0) + f.getDouble(2) > 0 && f.getDouble(1) + f.getDouble(3) > 0
+ val press = o.optBoolean("press")
+ val editable = o.optBoolean("editable") || role in setOf("TextField", "TextArea", "SearchField", "ComboBox")
+ val useful = visible && !o.optBoolean("disabled") &&
+ (press || editable || label.isNotBlank() || role in setOf("Button", "Link", "CheckBox", "RadioButton", "PopUpButton", "MenuButton", "Tab", "Cell", "Row"))
+ val kids = o.optJSONArray("children")
+ val decorative = role in setOf("Group", "ScrollArea", "SplitGroup", "Unknown", "LayoutArea", "") && label.isBlank() && !press
+ var d = depth
+ if (useful && !(decorative && kids != null)) {
+ val eid = "e${n++}"
+ val cx = f!!.getDouble(0) + f.getDouble(2) / 2
+ val cy = f.getDouble(1) + f.getDouble(3) / 2
+ val (nx, ny) = toNorm(cx, cy)
+ idx[eid] = El(eid, cx, cy, press, editable, label)
+ if (lines.size < MAX_LINES) {
+ lines += " ".repeat(depth) + "$eid${if (press) "*" else ""}${if (editable) "✎" else ""}|$role|${label.take(80).replace('\n', ' ')}|[$nx,$ny]"
+ }
+ d = depth + 1
+ }
+ if (kids != null) for (i in 0 until kids.length()) visit(kids.getJSONObject(i), d)
+ }
+ raw.optJSONObject("tree")?.let { visit(it, 0) }
+ index = idx
+ val out = JSONObject().put("app", raw.optString("app")).put("bundle", raw.optString("bundle"))
+ .put("window", raw.optString("window_title")).put("nodes_total", total).put("elements_listed", idx.size)
+ .put("elements", lines.joinToString("\n"))
+ if (idx.size > MAX_LINES) out.put("elements_dropped", idx.size - MAX_LINES)
+ if (idx.isEmpty()) {
+ out.put("empty", true).put(
+ "hint",
+ "This app gives the accessibility layer almost nothing (common for apps that draw their own UI, like " +
+ "WeChat for Mac). Work from the screenshot attached here: aim with the grid and tap_by_coordinates, " +
+ "checking each result. A keyboard shortcut or the app's menu bar is often more reliable than a click.",
+ )
+ if (Bridge.screenCaptureAllowed()) out.put("shot_auto", true).put("png_base64", shot(grid = true)) else out.put("screenshot_blocked", SCREEN_RECORDING_NOTE)
+ } else if (withShot) {
+ if (Bridge.screenCaptureAllowed()) out.put("png_base64", shot(grid = true)) else out.put("screenshot_blocked", SCREEN_RECORDING_NOTE)
+ }
+ out.put("aim_note", "Coordinates are [x,y] in 0-1000 of the main display. * = has a Press action; ✎ = editable.")
+ return out
+ }
+
+ // ---- taps ---------------------------------------------------------------
+
+ private fun tapId(eid: String, long: Boolean): JSONObject {
+ val e = index[eid] ?: throw IllegalArgumentException(
+ "unknown element $eid — the screen has changed or the number is from an older list. Re-dump with get_screen_element; do not guess.",
+ )
+ val (nx, ny) = toNorm(e.cx, e.cy)
+ val pressed = !long && e.press && gesture { Bridge.axPressAt(e.cx, e.cy) }
+ if (!pressed) gesture { Bridge.click(e.cx, e.cy, right = long, holdMs = 40) }
+ return afterTap(JSONObject().put("completed", true).put("eid", eid).put("label", e.label)
+ .put("via", if (pressed) "press_action" else if (long) "right_click" else "click").put("x", nx).put("y", ny))
+ }
+
+ private fun tapAim(p: JSONObject, long: Boolean): JSONObject {
+ val (nx, ny, label) = resolveAim(p)
+ guardSpot(nx, ny)
+ val (x, y) = toPx(nx, ny)
+ gesture { Bridge.click(x, y, right = long, holdMs = if (long) 40 else 40) }
+ return afterTap(JSONObject().put("completed", true).put("x", nx).put("y", ny).put("aimed_at", label)
+ .put("via", if (long) "right_click" else "click"))
+ }
+
+ /** Taps are followed by a fresh picture, as on the phone, so the next step reads the result. */
+ private fun afterTap(o: JSONObject): JSONObject {
+ Thread.sleep(400)
+ if (Bridge.screenCaptureAllowed()) o.put("after_shot", JSONObject().put("png_base64", shot(grid = true)))
+ o.put("front_app", Bridge.frontmost().optString("name"))
+ return o
+ }
+
+ private fun resolveAim(p: JSONObject): Triple<Int, Int, String> {
+ val on = p.optString("on").lowercase()
+ val cell = p.optString("cell").trim()
+ if (cell.isNotEmpty()) {
+ val zoom = on == "zoom" || (on.isEmpty() && cell.first().isLowerCase())
+ val (col, row) = parseCell(cell)
+ val part = p.optString("part").trim().lowercase().replace('_', '-').replace(' ', '-')
+ val (fx, fy) = if (part.isEmpty()) intArrayOf(1, AimParts.MID_ROW).let { it[0] to it[1] }
+ else (AimParts.cellOf(part) ?: throw IllegalArgumentException("unknown part \"$part\" — one of ${AimParts.PARTS.joinToString()}")).let { it[0] to it[1] }
+ val lx = ((col * AimParts.COLS + fx) * 2 + 1) * 1000 / (2 * GRID_COLS * AimParts.COLS)
+ val ly = ((row * AimParts.ROWS + fy) * 2 + 1) * 1000 / (2 * GRID_ROWS * AimParts.ROWS)
+ return if (zoom) zoomToScreen(lx, ly).let { Triple(it.first, it.second, "zoom cell $cell $part") }
+ else Triple(lx, ly, "cell $cell $part")
+ }
+ val x = p.optInt("x", Int.MIN_VALUE)
+ val y = p.optInt("y", Int.MIN_VALUE)
+ require(x != Int.MIN_VALUE && y != Int.MIN_VALUE) { "give either cell (+ part) or x and y" }
+ requireNorm(x, "x"); requireNorm(y, "y")
+ return if (on == "zoom") zoomToScreen(x, y).let { Triple(it.first, it.second, "zoom $x,$y") } else Triple(x, y, "$x,$y")
+ }
+
+ private fun parseCell(cell: String): Pair<Int, Int> {
+ val s = cell.uppercase()
+ val col = s[0] - 'A'
+ val row = s.substring(1).toIntOrNull()?.minus(1) ?: -1
+ require(col in 0 until GRID_COLS && row in 0 until GRID_ROWS) {
+ "bad grid cell '$cell' — a column letter A..H and a row number 1..12, exactly as labelled on the image"
+ }
+ return col to row
+ }
+
+ private fun zoomToScreen(lx: Int, ly: Int): Pair<Int, Int> {
+ val r = zoomRegion ?: throw IllegalStateException("on=\"zoom\" needs a zoom first — call zoom_screen_region")
+ if (System.currentTimeMillis() - zoomAt > 180_000) throw IllegalStateException("that zoom is over three minutes old; take a fresh one")
+ return (r[0] + lx * (r[2] - r[0]) / 1000) to (r[1] + ly * (r[3] - r[1]) / 1000)
+ }
+
+ /** The phone's stuck-loop guard: a fourth tap within 120 px of a spot inside five minutes is refused. */
+ private fun guardSpot(nx: Int, ny: Int) {
+ val (x, y) = toPx(nx, ny)
+ val now = System.currentTimeMillis()
+ synchronized(spots) {
+ spots.values.forEach { it.removeAll { t -> now - t > 300_000 } }
+ val key = spots.keys.firstOrNull { k -> k.split(',').let { Math.hypot(it[0].toDouble() - x, it[1].toDouble() - y) < 120 } }
+ ?: "${x.toInt()},${y.toInt()}"
+ val list = spots.getOrPut(key) { mutableListOf() }
+ if (list.size >= 3) throw IllegalStateException(
+ "refused: this is the fourth tap on the same spot in five minutes. Stop, look at the screen again, and " +
+ "if it is not working, tell the user where you are stuck instead of tapping again.",
+ )
+ list += now
+ }
+ }
+
+ // ---- swipes, typing, keys ---------------------------------------------
+
+ private fun swipe(p: JSONObject): JSONObject {
+ val x1 = p.getInt("x1"); val y1 = p.getInt("y1"); val x2 = p.getInt("x2"); val y2 = p.getInt("y2")
+ listOf(x1 to "x1", y1 to "y1", x2 to "x2", y2 to "y2").forEach { requireNorm(it.first, it.second) }
+ val (ax, ay) = toPx(x1, y1); val (bx, by) = toPx(x2, y2)
+ // On a Mac a swipe that scrolls is a scroll: the content moves the way the finger did, by that distance.
+ gesture { Bridge.scroll(ax, ay, (bx - ax).toInt(), (by - ay).toInt()) }
+ return JSONObject().put("completed", true).put("from", "$x1,$y1").put("to", "$x2,$y2").put("via", "scroll")
+ .put("note", "A swipe scrolls whatever is under the start point by that distance. To drag something, use the app's own controls.")
+ }
+
+ private fun type(text: String): JSONObject {
+ val before = Bridge.focusedValue()
+ if (!before.optBoolean("focused")) throw IllegalStateException("no field has focus — click into the field first")
+ val viaAx = Bridge.setFocusedValue(text)
+ if (!viaAx) gesture { Bridge.key(Bridge.Keys.A, Bridge.Keys.CMD); Bridge.key(Bridge.Keys.DELETE); Bridge.typeText(text) }
+ Thread.sleep(150)
+ val now = Bridge.focusedValue().optString("value")
+ val ok = now == text || now.contains(text)
+ return JSONObject().put("performed", ok).put("via", if (viaAx) "ax_value" else "keystrokes").put("len", text.length)
+ .apply { if (ok) put("text", now.take(200)) else put("error", "the field reads '${now.take(30)}' — check with a screenshot") }
+ }
+
+ private fun submit(): JSONObject {
+ gesture { Bridge.key(Bridge.Keys.RETURN) }
+ return JSONObject().put("performed", true).put("via", "return_key")
+ }
+
+ private fun global(action: String): JSONObject {
+ when (action.lowercase()) {
+ "back" -> Bridge.key(Bridge.Keys.LEFT_BRACKET, Bridge.Keys.CMD)
+ "home" -> Bridge.key(Bridge.Keys.F3, Bridge.Keys.CMD)
+ "recents" -> Bridge.key(Bridge.Keys.UP, Bridge.Keys.CONTROL)
+ "notifications", "quick_settings" -> Bridge.open("x-apple.systempreferences:com.apple.ControlCenter-Settings.extension")
+ else -> throw IllegalArgumentException("unknown action $action — back, home, recents, notifications")
+ }
+ return JSONObject().put("performed", true).put("action", action)
+ .put("note", when (action.lowercase()) {
+ "back" -> "Sent ⌘[ — Back in browsers and Finder. Many apps have no Back; prefer a visible button or Esc."
+ "home" -> "Sent ⌘F3 (show desktop)."
+ "recents" -> "Sent ⌃↑ (Mission Control)."
+ else -> "Opened Control Center settings."
+ })
+ }
+
+ private fun waitFor(seconds: Double): JSONObject {
+ val ms = (seconds.coerceIn(0.0, 20.0) * 1000).toLong()
+ Thread.sleep(ms)
+ return uiTree(withShot = true).put("waited_ms", ms)
+ }
+
+ // ---- pictures -----------------------------------------------------------
+
+ private fun screenshot(grid: Boolean): JSONObject {
+ if (!Bridge.screenCaptureAllowed()) throw IllegalStateException(SCREEN_RECORDING_NOTE)
+ return JSONObject().put("png_base64", shot(grid)).put("aim_grid", AIM_GRID_NOTE)
+ }
+
+ private fun capture(): BufferedImage {
+ val f = File.createTempFile("andee-shot", ".png")
+ try {
+ val ok = gestureless { Bridge.screenshot(f.path, 2560) }
+ if (!ok) throw IllegalStateException(SCREEN_RECORDING_NOTE)
+ return ImageIO.read(f)
+ } finally { f.delete() }
+ }
+
+ private fun shot(grid: Boolean): String {
+ var img = capture()
+ img = scale(img, SHOT_MAX_SIDE)
+ if (grid) drawGrid(img, zoom = false)
+ return png(img)
+ }
+
+ private fun lookRegion(p: JSONObject): JSONObject {
+ if (!Bridge.screenCaptureAllowed()) throw IllegalStateException(SCREEN_RECORDING_NOTE)
+ val (cx, cy, w, h, mark) = if (p.optString("cell").isNotBlank()) {
+ val (nx, ny, _) = resolveAim(p)
+ listOf(nx, ny, 2 * 1000 / GRID_COLS, 2 * 1000 / GRID_ROWS, 1)
+ } else {
+ listOf(p.getInt("x"), p.getInt("y"), p.optInt("w", 200), p.optInt("h", 300), 0)
+ }
+ requireNorm(cx, "x"); requireNorm(cy, "y")
+ val left = (cx - w / 2).coerceIn(0, 999); val top = (cy - h / 2).coerceIn(0, 999)
+ val right = (left + w).coerceAtMost(1000); val bottom = (top + h).coerceAtMost(1000)
+ val full = capture()
+ val sx = full.width / 1000.0; val sy = full.height / 1000.0
+ val sub = full.getSubimage((left * sx).toInt(), (top * sy).toInt(), ((right - left) * sx).toInt().coerceAtLeast(4), ((bottom - top) * sy).toInt().coerceAtLeast(4))
+ val k = SHOT_MAX_SIDE.toDouble() / maxOf(sub.width, sub.height)
+ val out = BufferedImage((sub.width * k).toInt(), (sub.height * k).toInt(), BufferedImage.TYPE_INT_RGB)
+ out.createGraphics().apply {
+ setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC)
+ drawImage(sub, 0, 0, out.width, out.height, null); dispose()
+ }
+ drawGrid(out, zoom = true)
+ if (mark == 1) {
+ val mx = (cx - left) * out.width / (right - left).toDouble(); val my = (cy - top) * out.height / (bottom - top).toDouble()
+ out.createGraphics().apply {
+ setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
+ val r = minOf(out.width, out.height) * 0.045
+ color = Color(224, 0, 255); stroke = BasicStroke((r * 0.14).toFloat())
+ drawOval((mx - r).toInt(), (my - r).toInt(), (2 * r).toInt(), (2 * r).toInt())
+ drawLine((mx - r * 1.8).toInt(), my.toInt(), (mx - r * 0.4).toInt(), my.toInt())
+ drawLine((mx + r * 0.4).toInt(), my.toInt(), (mx + r * 1.8).toInt(), my.toInt())
+ drawLine(mx.toInt(), (my - r * 1.8).toInt(), mx.toInt(), (my - r * 0.4).toInt())
+ drawLine(mx.toInt(), (my + r * 0.4).toInt(), mx.toInt(), (my + r * 1.8).toInt())
+ dispose()
+ }
+ }
+ zoomRegion = intArrayOf(left, top, right, bottom); zoomAt = System.currentTimeMillis()
+ return JSONObject().put("png_base64", png(out)).put("region", JSONObject().put("left", left).put("top", top).put("right", right).put("bottom", bottom))
+ .put("zoom_hint", "This is a magnified region; its grid is lowercase (a1..h12). Aim off it with {\"cell\": \"d7\", \"part\": \"…\", \"on\": \"zoom\"}.")
+ }
+
+ private fun scale(img: BufferedImage, maxSide: Int): BufferedImage {
+ val k = maxSide.toDouble() / maxOf(img.width, img.height)
+ if (k >= 1) return img
+ val out = BufferedImage((img.width * k).toInt(), (img.height * k).toInt(), BufferedImage.TYPE_INT_RGB)
+ out.createGraphics().apply {
+ setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
+ drawImage(img, 0, 0, out.width, out.height, null); dispose()
+ }
+ return out
+ }
+
+ private fun drawGrid(img: BufferedImage, zoom: Boolean) {
+ val g = img.createGraphics()
+ g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
+ val cw = img.width / GRID_COLS.toDouble(); val ch = img.height / GRID_ROWS.toDouble()
+ for (i in 0..GRID_COLS) {
+ val x = (i * cw).toInt().coerceIn(0, img.width - 1)
+ g.color = Color(255, 255, 255, 38); g.stroke = BasicStroke(3f); g.drawLine(x, 0, x, img.height)
+ g.color = Color(0, 0, 0, 96); g.stroke = BasicStroke(1f); g.drawLine(x, 0, x, img.height)
+ }
+ for (i in 0..GRID_ROWS) {
+ val y = (i * ch).toInt().coerceIn(0, img.height - 1)
+ g.color = Color(255, 255, 255, 38); g.stroke = BasicStroke(3f); g.drawLine(0, y, img.width, y)
+ g.color = Color(0, 0, 0, 96); g.stroke = BasicStroke(1f); g.drawLine(0, y, img.width, y)
+ }
+ val size = (minOf(cw, ch) * 0.2).coerceIn(9.0, 24.0).toFloat()
+ g.font = Font(Font.SANS_SERIF, Font.BOLD, size.toInt())
+ for (r in 0 until GRID_ROWS) for (c in 0 until GRID_COLS) {
+ val label = "${'A' + c}${r + 1}".let { if (zoom) it.lowercase() else it }
+ val w = g.fontMetrics.stringWidth(label)
+ val tx = ((c + 0.5) * cw - w / 2).toInt(); val ty = ((r + 0.5) * ch + size * 0.35).toInt()
+ g.color = Color(0, 0, 0, 165); for (dx in -1..1) for (dy in -1..1) g.drawString(label, tx + dx, ty + dy)
+ g.color = Color(255, 255, 255, 175); g.drawString(label, tx, ty)
+ }
+ g.dispose()
+ }
+
+ private fun png(img: BufferedImage): String {
+ val bos = ByteArrayOutputStream()
+ ImageIO.write(img, "png", bos)
+ return Base64.getEncoder().encodeToString(bos.toByteArray())
+ }
+
+ // ---- our own windows -----------------------------------------------------
+
+ /** Gestures hide our windows so a click cannot land on Andee. */
+ private fun <T> gesture(block: () -> T): T {
+ hideOwnWindows(true)
+ try { Thread.sleep(120); return block() } finally { hideOwnWindows(false) }
+ }
+
+ /** Captures exclude our process in ScreenCaptureKit itself; nothing to hide. */
+ private fun <T> gestureless(block: () -> T): T = block()
+
+ private fun req(p: JSONObject, k: String) = p.optString(k).trim().ifEmpty { throw IllegalArgumentException("$k is required") }
+
+ companion object {
+ private const val GRID_COLS = 8
+ private const val GRID_ROWS = 12
+ private const val SHOT_MAX_SIDE = 1280
+ private const val MAX_LINES = 300
+
+ val METHODS = setOf(
+ "screen.ui_tree", "screen.tap_id", "screen.tap", "screen.long_press_id", "screen.long_press",
+ "screen.swipe", "screen.type", "screen.submit_input", "screen.wait", "screen.look_region",
+ "screen.screenshot", "screen.global",
+ )
+
+ const val SCREEN_RECORDING_NOTE =
+ "Andee does not have Screen Recording permission on this Mac, so it cannot see the screen. Tell the user to " +
+ "allow it in System Settings → Privacy & Security → Screen & System Audio Recording (the ✓ check card has a button), " +
+ "then quit and reopen Andee."
+
+ private const val AIM_GRID_NOTE =
+ "This image carries an 8x12 aim grid, A1 (top-left) to H12 (bottom-right), each label at the centre of its cell. " +
+ "To click something, name its cell and which part of the cell — {\"cell\": \"D7\", \"part\": \"bottom-right\"} on " +
+ "tap_by_coordinates. Andee's own windows are never in this picture."
+
+ init { Log.i("MacScreen", "screen tools registered") }
+ }
+}