import AppKit import ApplicationServices import OSLog /// One control on screen the agent can act on. `frame` is in global screen coordinates /// with a top-left origin (the Accessibility and CGEvent convention). struct ScreenElement: @unchecked Sendable { let id: String let axRole: String let role: String let label: String let value: String? let frame: CGRect let element: AXUIElement let canPress: Bool let isFocused: Bool var isEditable: Bool { ScreenObserver.textRoles.contains(axRole) } var center: CGPoint { CGPoint(x: frame.midX, y: frame.midY) } /// e.g. `button "Send"` or `text field "To" containing "bob@…"`. var summary: String { var s = label.isEmpty ? role : "\(role) \"\(label)\"" if let value, !value.isEmpty { s += " containing \"\(value)\"" } return s } } /// What's on screen: the frontmost app's window, its controls and its text. struct Observation: Sendable { let appName: String let bundleID: String? let pid: pid_t let windowTitle: String let windowFrame: CGRect let elements: [ScreenElement] let texts: [String] var focused: ScreenElement? { elements.first(where: \.isFocused) } /// Changes whenever the screen meaningfully changes; used to spot the agent going in circles. var signature: String { ([appName, windowTitle, focused?.summary ?? ""] + elements.map(\.summary)).joined(separator: "|") } /// Coarse position within the window, e.g. "upper left". func position(of element: ScreenElement) -> String { guard windowFrame.width > 0, windowFrame.height > 0 else { return "" } let x = (element.frame.midX - windowFrame.minX) / windowFrame.width let y = (element.frame.midY - windowFrame.minY) / windowFrame.height let row = y < 0.33 ? "upper" : y < 0.67 ? "middle" : "lower" let col = x < 0.33 ? "left" : x < 0.67 ? "center" : "right" return row == "middle" && col == "center" ? "center" : "\(row) \(col)" } } enum ScreenObserver { static let textRoles: Set = ["AXTextField", "AXTextArea", "AXComboBox", "AXSearchField"] static let roleNames: [String: String] = [ "AXButton": "button", "AXLink": "link", "AXTextField": "text field", "AXTextArea": "text area", "AXSearchField": "search field", "AXComboBox": "combo box", "AXCheckBox": "checkbox", "AXRadioButton": "radio button", "AXPopUpButton": "pop-up menu", "AXMenuButton": "menu button", "AXMenuItem": "menu item", "AXMenuBarItem": "menu", "AXDisclosureTriangle": "disclosure triangle", "AXSlider": "slider", "AXRow": "row", "AXCell": "cell", "AXTab": "tab", "AXSwitch": "switch", "AXDockItem": "dock item", ] private static let maxVisited = 4000 private static let maxElements = 150 private static let maxTextChars = 3000 /// Observes the frontmost app other than Seer. static func observe() -> Observation? { guard let app = frontmostApp() else { return nil } let appElement = AXUIElementCreateApplication(app.processIdentifier) AXUIElementSetMessagingTimeout(appElement, 1.0) // Chromium and Electron apps only build their accessibility tree when asked. AXUIElementSetAttributeValue(appElement, "AXManualAccessibility" as CFString, kCFBooleanTrue) let window = copy(appElement, kAXFocusedWindowAttribute) as! AXUIElement? ?? (copy(appElement, kAXWindowsAttribute) as? [AXUIElement])?.first let windowTitle = window.flatMap { copy($0, kAXTitleAttribute) as? String } ?? "" let windowFrame = window.flatMap(frame(of:)) ?? .zero let focusedElement = copy(appElement, kAXFocusedUIElementAttribute) as! AXUIElement? // Open menus are children of the app, not the window, and cover everything else. let appChildren = copy(appElement, kAXChildrenAttribute) as? [AXUIElement] ?? [] let openMenus = appChildren.filter { (copy($0, kAXRoleAttribute) as? String) == "AXMenu" } let roots = openMenus + (window.map { [$0] } ?? []) var elements: [ScreenElement] = [] var texts: [String] = [] var textChars = 0 var seenTexts = Set() var queue = roots[...] var visited = 0 let bounds = windowFrame.isEmpty ? CGRect.infinite : windowFrame.insetBy(dx: -4, dy: -4) while let node = queue.popFirst(), visited < maxVisited, elements.count < maxElements { visited += 1 let attrs = attributes(node, [ kAXRoleAttribute, kAXSubroleAttribute, kAXTitleAttribute, kAXDescriptionAttribute, kAXValueAttribute, kAXPlaceholderValueAttribute, kAXHelpAttribute, kAXEnabledAttribute, kAXChildrenAttribute, ]) let axRole = attrs[kAXRoleAttribute] as? String ?? "" let subrole = attrs[kAXSubroleAttribute] as? String let children = attrs[kAXChildrenAttribute] as? [AXUIElement] ?? [] if axRole == "AXStaticText" || axRole == "AXHeading" { if let text = (attrs[kAXValueAttribute] as? String ?? attrs[kAXTitleAttribute] as? String)? .trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty, textChars < maxTextChars, seenTexts.insert(text).inserted { texts.append(String(text.prefix(300))) textChars += min(text.count, 300) } } let effectiveRole = subrole == "AXSearchField" ? "AXSearchField" : subrole == "AXTabButton" ? "AXTab" : subrole == "AXSwitch" ? "AXSwitch" : axRole let canPress = actions(of: node).contains(kAXPressAction as String) let isControl = roleNames[effectiveRole] != nil let enabled = attrs[kAXEnabledAttribute] as? Bool ?? true if (isControl || canPress), enabled, let rect = frame(of: node), rect.width > 1, rect.height > 1, bounds.intersects(rect) || !openMenus.isEmpty { let isText = textRoles.contains(effectiveRole) let rawValue = attrs[kAXValueAttribute] as? String var label = firstNonEmpty( attrs[kAXTitleAttribute] as? String, attrs[kAXDescriptionAttribute] as? String, isText ? nil : rawValue, attrs[kAXPlaceholderValueAttribute] as? String, attrs[kAXHelpAttribute] as? String ) ?? "" if label.isEmpty { label = descendantText(of: node) ?? "" } // Unlabeled generic clickables (layout groups with a press action) are noise. if isControl || !label.isEmpty { elements.append(ScreenElement( id: "e\(elements.count)", axRole: effectiveRole, role: roleNames[effectiveRole] ?? "clickable \(axRole.replacingOccurrences(of: "AX", with: "").lowercased())", label: String(label.prefix(80)), value: isText ? rawValue.map { String($0.prefix(120)) } : nil, frame: rect, element: node, canPress: canPress, isFocused: focusedElement.map { CFEqual($0, node) } ?? false )) } } queue.append(contentsOf: children) } Logger.computer.info("Observed \(app.localizedName ?? "?", privacy: .public) — \(elements.count, privacy: .public) elements, \(texts.count, privacy: .public) texts, \(visited, privacy: .public) nodes") return Observation( appName: app.localizedName ?? "Unknown app", bundleID: app.bundleIdentifier, pid: app.processIdentifier, windowTitle: windowTitle, windowFrame: windowFrame, elements: elements, texts: texts ) } static func frontmostApp() -> NSRunningApplication? { let me = ProcessInfo.processInfo.processIdentifier if let app = NSWorkspace.shared.frontmostApplication, app.processIdentifier != me { return app } return NSWorkspace.shared.menuBarOwningApplication.flatMap { $0.processIdentifier == me ? nil : $0 } } // MARK: - AX helpers static func copy(_ element: AXUIElement, _ attribute: String) -> CFTypeRef? { var value: CFTypeRef? guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else { return nil } return value } private static func attributes(_ element: AXUIElement, _ names: [String]) -> [String: CFTypeRef] { var values: CFArray? guard AXUIElementCopyMultipleAttributeValues(element, names as CFArray, AXCopyMultipleAttributeOptions(rawValue: 0), &values) == .success, let array = values as? [CFTypeRef] else { return [:] } var result: [String: CFTypeRef] = [:] for (name, value) in zip(names, array) { // Missing attributes come back as AXValue-wrapped errors. if CFGetTypeID(value) == AXValueGetTypeID(), AXValueGetType(value as! AXValue) == .axError { continue } result[name] = value } return result } private static func actions(of element: AXUIElement) -> [String] { var names: CFArray? guard AXUIElementCopyActionNames(element, &names) == .success else { return [] } return names as? [String] ?? [] } static func frame(of element: AXUIElement) -> CGRect? { guard let posValue = copy(element, kAXPositionAttribute), let sizeValue = copy(element, kAXSizeAttribute) else { return nil } var origin = CGPoint.zero, size = CGSize.zero guard AXValueGetValue(posValue as! AXValue, .cgPoint, &origin), AXValueGetValue(sizeValue as! AXValue, .cgSize, &size) else { return nil } return CGRect(origin: origin, size: size) } /// Text of the first static-text descendant, for controls labeled by their contents (web links, cells). static func descendantText(of element: AXUIElement, depth: Int = 3) -> String? { guard depth > 0 else { return nil } for child in copy(element, kAXChildrenAttribute) as? [AXUIElement] ?? [] { if (copy(child, kAXRoleAttribute) as? String) == "AXStaticText", let text = firstNonEmpty(copy(child, kAXValueAttribute) as? String, copy(child, kAXTitleAttribute) as? String) { return text } if let text = descendantText(of: child, depth: depth - 1) { return text } } return nil } static func firstNonEmpty(_ candidates: String?...) -> String? { candidates.lazy .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) } .first { !$0.isEmpty } } }