Open source CapCut alternative.
TypeScript
feat(app): read transcripts via Accessibility and target app windows by title
David Lea325d6f68874
diff --git a/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swiftindex 5a01d641..7a539d13 100644--- a/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift@@ -188,7 +188,7 @@ public final class PointerComputerUseToolProvider {/// otherwise it brings the target frontmost (one recovery activation, never any other app) and/// returns a nil input target for the HID path. Returns nil only when a required activation failed.private func resolveRouting() async -> (target: MacWindowTargetCandidate, inputTarget: InputTarget?)? {- guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier, windowTitleHint: self.target.windowTitleHint) else {return nil}switch TargetActionGuard.resolve(candidate: target, preference: executionPreference, lane: .pidEventPost) {diff --git a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swiftindex 383a4ad8..e8dc312d 100644--- a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift@@ -93,12 +93,13 @@ public final class VisionComputerUseToolProvider {HarnessToolDescriptor(name: ToolName.captureAndAnalyze,pluginID: "core.computer-use.vision",- summary: "Screenshot and detect UI elements with vision. Three scopes, smallest first: scope=window (default) captures the target window; scope=screen captures the WHOLE display the window is on — use it for things drawn outside the window like a modal confirmation dialog/sheet or a system prompt; scope=desktop captures the ENTIRE desktop across all displays — the fallback when what you need isn't on the active display (another monitor, a background app's window). Widen only as far as you must. Pass app=\"<App Name>\" to capture a specific app and make it the active target for the actions that follow; omit it to capture the current target. vision.click works the same on elements from any scope.",+ summary: "Screenshot and detect UI elements with vision. Three scopes, smallest first: scope=window (default) captures the target window; scope=screen captures the WHOLE display the window is on — use it for things drawn outside the window like a modal confirmation dialog/sheet or a system prompt; scope=desktop captures the ENTIRE desktop across all displays — the fallback when what you need isn't on the active display (another monitor, a background app's window). Widen only as far as you must. Pass app=\"<App Name>\" to capture a specific app and make it the active target for the actions that follow; omit it to capture the current target. Pass window=\"<title text>\" when the app has more than one window open to pin the one whose title matches. vision.click works the same on elements from any scope.",inputSchema: ["scope": "\"window\" (default), \"screen\" (whole display) for modals/dialogs, or \"desktop\" (all displays) when the target is off the active screen.",- "app": "Optional app name to capture and switch the run's active target to; omit to use the current target."+ "app": "Optional app name to capture and switch the run's active target to; omit to use the current target.",+ "window": "Optional window title (or a distinctive part of it) to pin a specific window when the app has several open; sticks to the target for the following steps."],- optionalInputKeys: ["scope", "app"],+ optionalInputKeys: ["scope", "app", "window"],outputSchema: ["elements": "Detected element IDs, labels, roles, and click eligibility."],requiredPermissions: [.screenCapture],safetyClass: .readOnly,@@ -172,13 +173,13 @@ public final class VisionComputerUseToolProvider {// The planner can name an app to look at; that becomes the active target for the actions that// follow, so a run can capture and drive any app (or acquire its first one on an app-less run).if let requested = trimmed(context.call.input["app"]) {- retarget(to: requested)+ retarget(to: requested, window: trimmed(context.call.input["window"]))}guard !self.target.isEmpty else {return result(context, status: .failed, summary: "No active app to capture. Pass app=\"<App Name>\" to target one, or open the app first.", reason: "noActiveTarget")}- guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {- return result(context, status: .failed, summary: "No window for \(appName).", reason: "noWindowForApp")+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier, windowTitleHint: self.target.windowTitleHint) else {+ return result(context, status: .failed, summary: noWindowSummary, reason: "noWindowForApp")}switch trimmed(context.call.input["scope"])?.lowercased() {case "screen": return await captureWideAndAnalyze(context, target: target, scope: "screen")@@ -280,6 +281,28 @@ public final class VisionComputerUseToolProvider {)}+ /// Capture the current target window and OCR its visible text, in reading order — the reading path+ /// for apps whose content isn't in the Accessibility tree (a chat transcript's bubbles, custom-drawn+ /// lists). This uses on-device text recognition, NOT the UI-element detector `captureAndAnalyze` uses:+ /// that detector finds controls (buttons, fields) and so returns a window's chrome while missing the+ /// message text drawn between the controls — which is exactly the content a harvest is trying to read.+ /// Screen capture reads the window's buffer without raising or focusing it, so this stays fully in the+ /// background. Best-effort: returns [] when there is no window or the capture fails. Distinct lines,+ /// preserving first-seen order, so the harvest loop can de-duplicate across scroll passes.+ public func readVisibleTextLines() async -> [String] {+ guard !target.isEmpty,+ let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier, windowTitleHint: target.windowTitleHint),+ let shot = try? await capture(target) else {+ return []+ }+ var seen = Set<String>()+ var lines: [String] = []+ for text in ScreenTextRecognizer.recognizeLines(inPNG: shot.pngData) where seen.insert(text).inserted {+ lines.append(text)+ }+ return lines+ }+/// Capture wider than the target window and analyze it. `scope=screen` grabs the whole display the/// window sits on (modal sheets, system prompts, right-click menus drawn outside the window);/// `scope=desktop` grabs the entire desktop across all displays (a target on another monitor or a@@ -388,8 +411,8 @@ public final class VisionComputerUseToolProvider {let geometry = Self.geometry(from: element.metadata) else {return result(context, status: .failed, summary: "Element \(elementID) cannot be clicked.", reason: "elementNotClickable")}- guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {- return result(context, status: .failed, summary: "No window for \(appName).", reason: "noWindowForApp")+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier, windowTitleHint: self.target.windowTitleHint) else {+ return result(context, status: .failed, summary: noWindowSummary, reason: "noWindowForApp")}guard let routing = await inputRouting(for: target) else {return notFrontmost(context)@@ -431,7 +454,7 @@ public final class VisionComputerUseToolProvider {guard let text = context.call.input["text"], !text.isEmpty else {return result(context, status: .invalidInput, summary: "text.enter requires non-empty text.", reason: "missingText")}- guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier),+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier, windowTitleHint: self.target.windowTitleHint),let routing = await inputRouting(for: target) else {return notFrontmost(context)}@@ -450,7 +473,7 @@ public final class VisionComputerUseToolProvider {guard let key = trimmed(context.call.input["key"]) else {return result(context, status: .invalidInput, summary: "keyboard.press requires a key.", reason: "missingKey")}- guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier),+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier, windowTitleHint: self.target.windowTitleHint),let routing = await inputRouting(for: target) else {return notFrontmost(context)}@@ -621,12 +644,22 @@ public final class VisionComputerUseToolProvider {/// Switch the run's active target to `requestedApp`. Resolves it to a running window's exact identity/// when open; otherwise pins it by name so a re-capture after the planner launches it resolves cleanly.- private func retarget(to requestedApp: String) {+ private func retarget(to requestedApp: String, window: String? = nil) {if let resolved = AccessibilityObserver.resolveTarget(appName: requestedApp, bundleIdentifier: nil) {- target.retarget(appName: resolved.appName ?? requestedApp, bundleIdentifier: resolved.bundleIdentifier)+ target.retarget(appName: resolved.appName ?? requestedApp, bundleIdentifier: resolved.bundleIdentifier, windowTitleHint: window)} else {- target.retarget(appName: requestedApp, bundleIdentifier: nil)+ target.retarget(appName: requestedApp, bundleIdentifier: nil, windowTitleHint: window)+ }+ }++ /// The failure line when no target window resolves. When a specific window was pinned but isn't open,+ /// point the planner at opening it instead of the generic "no window", which reads as the whole app+ /// being gone.+ private var noWindowSummary: String {+ if let hint = target.windowTitleHint, !hint.isEmpty {+ return "No window titled \"\(hint)\" in \(appName). Open that window first, then retry."}+ return "No window for \(appName)."}private func trimmed(_ value: String?) -> String? {diff --git a/apps/Donkey/Sources/DonkeyContracts/HarnessTargetContext.swift b/apps/Donkey/Sources/DonkeyContracts/HarnessTargetContext.swiftindex 4a140ffb..9947b9a2 100644--- a/apps/Donkey/Sources/DonkeyContracts/HarnessTargetContext.swift+++ b/apps/Donkey/Sources/DonkeyContracts/HarnessTargetContext.swift@@ -19,10 +19,17 @@ public final class HarnessTargetContext {/// The current target's bundle id, when known. Pins observation/action to the exact app even if two/// apps share a display name.public private(set) var bundleIdentifier: String?+ /// The title of the specific window this run is driving, when the target app has several open at once+ /// (a chat app's contact list AND a conversation window, a browser's many tabs). Empty/nil means "any+ /// window of the app" — the first the resolver finds. When set, every see/act tool resolves the app+ /// window whose title matches this, so a read/scroll/click lands on the conversation the planner named,+ /// not whichever window of the app happens to be frontmost.+ public private(set) var windowTitleHint: String?- public init(appName: String, bundleIdentifier: String?) {+ public init(appName: String, bundleIdentifier: String?, windowTitleHint: String? = nil) {self.appName = appNameself.bundleIdentifier = bundleIdentifier+ self.windowTitleHint = windowTitleHint}/// A stable per-app cache key (bundle id when present, else the name), used by the vision parse store.@@ -37,10 +44,14 @@ public final class HarnessTargetContext {appName.isEmpty && (bundleIdentifier?.isEmpty ?? true)}- /// Point the run at a different app. Called by an observe/capture step that named an `app:` to look at,- /// so subsequent actions resolve, focus, and route input to that app rather than the run's first one.- public func retarget(appName: String, bundleIdentifier: String?) {+ /// Point the run at a different app, and optionally a specific window of it. Called by an observe/capture+ /// step that named an `app:` (and maybe a `window:`) to look at, so subsequent actions resolve, focus,+ /// and route input to that app's chosen window rather than the run's first one. A retarget without a+ /// window hint clears any prior one — the planner looked at the app broadly, so we no longer pin a+ /// window.+ public func retarget(appName: String, bundleIdentifier: String?, windowTitleHint: String? = nil) {self.appName = appNameself.bundleIdentifier = bundleIdentifier+ self.windowTitleHint = windowTitleHint}}diff --git a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swiftindex 03a13677..eca47d5a 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift@@ -17,8 +17,22 @@ public final class AXComputerUseToolProvider {public static let observe = "ax.observe"public static let click = "ax.click"public static let selectAndPress = "ax.select_and_press"+ public static let harvest = "content.harvest"}+ /// Lines to advance per harvest scroll pass. Deliberately smaller than a viewport so consecutive+ /// reads overlap — de-duplication drops the overlap, and nothing between two views is skipped.+ private static let harvestScrollLines = 8++ /// A first Accessibility read yielding fewer distinct text lines than this means the app draws its+ /// content outside the AX tree (a chat transcript's bubbles, a custom-drawn list). When a vision reader+ /// is available, harvest switches to reading the pixels instead of returning chrome.+ private static let harvestAXProductiveThreshold = 8++ /// Cap on scroll passes when harvest reads through vision. Each pass is a screenshot + hosted parse+ /// (seconds, rate-limited), so the vision path is bounded tighter than the cheap AX path.+ private static let harvestMaxVisionScrolls = 6+/// The app this run is currently driving — shared with the vision/pointer providers and mutable when/// an observe step retargets it. Read per call (via the computed accessors below) so action always/// resolves against the app the planner last looked at, not one app pinned for the whole run.@@ -27,15 +41,21 @@ public final class AXComputerUseToolProvider {private var bundleIdentifier: String? { target.bundleIdentifier }private let executionPreference: ExecutionPreferenceprivate let actionBackend: ActionEngineInputBackend+ /// Reads the current target window's visible text through vision (screenshot + parse), for+ /// `content.harvest` to fall back on when the Accessibility tree is too thin to hold the content.+ /// Injected by the run so this module needn't depend on the vision stack; nil leaves harvest AX-only.+ private let visionTextReader: (@MainActor () async -> [String])?public init(target: HarnessTargetContext,executionPreference: ExecutionPreference = .foreground,- actionBackend: ActionEngineInputBackend = MacAccessibilityActionEngineInputBackend()+ actionBackend: ActionEngineInputBackend = MacAccessibilityActionEngineInputBackend(),+ visionTextReader: (@MainActor () async -> [String])? = nil) {self.target = targetself.executionPreference = executionPreferenceself.actionBackend = actionBackend+ self.visionTextReader = visionTextReader}/// The semantic AX action to attempt for a click gesture, or nil to take the coordinate path. Gated@@ -60,9 +80,12 @@ public final class AXComputerUseToolProvider {HarnessToolDescriptor(name: ToolName.observe,pluginID: "core.computer-use.ax",- summary: "Read the target app's Accessibility tree and return its actionable controls. Fast and structured; prefer this for native apps. Pass app=\"<App Name>\" to observe a specific app and make it the active target for the actions that follow; omit it to observe the current target.",- inputSchema: ["app": "Optional app name to observe and switch the run's active target to; omit to use the current target."],- optionalInputKeys: ["app"],+ summary: "Read the target app's Accessibility tree and return its actionable controls. Fast and structured; prefer this for native apps. Pass app=\"<App Name>\" to observe a specific app and make it the active target for the actions that follow; omit it to observe the current target. Pass window=\"<title text>\" when the app has more than one window open (a chat app's contact list AND a conversation window) to pin the one whose title matches — every later act/scroll/read then resolves that window, not whichever is frontmost.",+ inputSchema: [+ "app": "Optional app name to observe and switch the run's active target to; omit to use the current target.",+ "window": "Optional window title (or a distinctive part of it, e.g. a person's name) to pin a specific window when the app has several open; sticks to the target for the following steps."+ ],+ optionalInputKeys: ["app", "window"],outputSchema: ["elements": "Accessibility control IDs, labels, roles, and click eligibility."],requiredPermissions: [.accessibility],safetyClass: .readOnly,@@ -101,6 +124,27 @@ public final class AXComputerUseToolProvider {safetyClass: .guardedInput,requiredContext: ["frontmost target"],verificationHints: ["re-observe to confirm the row is gone / the action took effect"]+ ),+ HarnessToolDescriptor(+ name: ToolName.harvest,+ pluginID: "core.computer-use.ax",+ summary: "Read content that spans MORE than one screen — a chat transcript, a long feed, a scrolling list — in a single call. It reads the visible on-screen text (the Accessibility text, or the pixels via OCR when the app draws its own content that isn't in the Accessibility tree) and scrolls, over and over, collecting the distinct lines it sees, so you don't loop observe/scroll/observe yourself (each of which costs a planning step). It scrolls through the app's own scroll view where it can, so the read stays in the background. Use direction=up for older history (a chat backlog above the newest message), down for later content. Returns the gathered text; read it directly.",+ inputSchema: [+ "direction": "\"up\" to gather older/earlier content (e.g. chat history above the newest message), or \"down\" for later content. Default \"up\".",+ "maxItems": "Stop once this many distinct text lines are collected (default 60). Ask for a little more than you need and pick from the result.",+ "maxScrolls": "Cap on scroll passes before returning what was gathered so far (default 20).",+ "window": "Optional window title (or a distinctive part of it, e.g. a person's name) to read when the app has more than one window open — a chat's conversation window vs. its contact list. Without it the read uses whatever window the run last pinned, else the app's first.",+ "elementID": "Observed element to scroll at (the scrolling pane), when a specific region must receive the scroll; omit for the window center."+ ],+ optionalInputKeys: ["direction", "maxItems", "maxScrolls", "window", "elementID"],+ outputSchema: ["text": "The distinct text lines gathered across the scroll; most-recent first when direction=up."],+ requiredPermissions: [.accessibility, .input],+ safetyClass: .guardedInput,+ requiredContext: ["a resolved target window"],+ verificationHints: ["the returned text is the gathered content; read it directly rather than re-scrolling"],+ // A scrolling read reflects live state and moves the view, so the run's read cache must+ // never serve a prior harvest — re-harvesting is the whole point of calling it again.+ metadata: [HarnessToolDescriptor.volatileResultMetadataKey: "true"])]}@@ -118,6 +162,7 @@ public final class AXComputerUseToolProvider {case ToolName.observe: return observe(context)case ToolName.click: return await click(context)case ToolName.selectAndPress: return await selectAndPress(context)+ case ToolName.harvest: return await harvest(context)default:return result(context, status: .unknownTool, summary: "Unknown AX tool.", reason: "unknownAXTool")}@@ -126,14 +171,17 @@ public final class AXComputerUseToolProvider {private func observe(_ context: HarnessToolExecutionContext) -> HarnessToolResult {// The planner can name an app to look at; that becomes the active target for the actions that// follow. This is what unbinds the run from one app — observe X, act on X; observe Y, act on Y.+ // It can also name a specific window (a conversation, a document) so a multi-window app resolves+ // the right one; that pin sticks to the target for the later act/scroll steps.if let requested = trimmed(context.call.input["app"]) {- retarget(to: requested)+ retarget(to: requested, window: trimmed(context.call.input["window"]))}guard !target.isEmpty else {return result(context, status: .failed, summary: "No active app to observe. Pass app=\"<App Name>\" to target one, or open the app first.", reason: "noActiveTarget")}- guard let observation = AccessibilityObserver.observe(appName: appName, bundleIdentifier: bundleIdentifier) else {- return result(context, status: .failed, summary: "Accessibility is unavailable for \(appName).", reason: "axUnavailable")+ guard let observation = AccessibilityObserver.observe(appName: appName, bundleIdentifier: bundleIdentifier, windowTitleHint: target.windowTitleHint) else {+ let windowNote = target.windowTitleHint.map { " No window titled \"\($0)\" is open — open that chat/document first." } ?? ""+ return result(context, status: .failed, summary: "Accessibility is unavailable for \(appName).\(windowNote)", reason: "axUnavailable")}let worldElements = observation.controls.compactMap { Self.worldElement(from: $0) }return HarnessToolResult(@@ -161,11 +209,17 @@ public final class AXComputerUseToolProvider {guard let element = context.worldModel.elements.first(where: { $0.id == elementID }) else {return result(context, status: .failed, summary: "Control \(elementID) is not in the latest observation.", reason: "elementNotFound")}- guard element.isActionEligible, let center = Self.screenCenter(from: element.metadata) else {- return result(context, status: .failed, summary: "Control \(elementID) cannot be clicked.", reason: "elementNotClickable")+ // A location on screen is the only hard requirement for a click: a coordinate click lands on the+ // control's frame regardless of what the Accessibility tree reports about it. `isActionEligible`+ // (the control's AX enabled bit) gates only the SEMANTIC AX action below — it must not veto the+ // click, because apps that draw their own controls (chat rows, custom lists) report+ // an unreliable enabled bit, and returning "cannot be clicked" there dead-ends the planner into+ // escalating to a focus-stealing shell fallback.+ guard let center = Self.screenCenter(from: element.metadata) else {+ return result(context, status: .failed, summary: "Control \(elementID) has no on-screen location to click; re-observe, or use vision.click.", reason: "elementNotOnScreen")}- guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {- return result(context, status: .failed, summary: "No window for \(appName).", reason: "noWindowForApp")+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier, windowTitleHint: target.windowTitleHint) else {+ return result(context, status: .failed, summary: noWindowSummary, reason: "noWindowForApp")}let label = element.label.isEmpty ? elementID : element.labellet button: MacPointerInput.Button = context.call.input["button"] == "right" ? .right : .left@@ -177,7 +231,8 @@ public final class AXComputerUseToolProvider {// a semantic action, we act without raising the app or moving the cursor. Anything the background// lane can't drive (no advertised action, an unsafe surface, or a foreground turn) falls through to// the foreground path below, which is always available.- if case .background(let inputTarget) = TargetActionGuard.resolve(+ if element.isActionEligible,+ case .background(let inputTarget) = TargetActionGuard.resolve(candidate: target,preference: executionPreference,lane: .axAction@@ -194,6 +249,26 @@ public final class AXComputerUseToolProvider {)}+ // COORDINATE fallback on a background turn: the control advertises no semantic action, reports+ // itself disabled, or its AX action didn't land (an opaque or custom-drawn row). A coordinate click+ // only lands on the ACTIVE app — a click posted to a backgrounded window is dropped (verified) — so+ // briefly bring the target to the front, click on the real event tap, and hand focus back. The+ // truly-background AX-action path above handled controls that expose a semantic action; this is the+ // honest fallback for the rest. If the target can't be fronted, fall through and report the blocker.+ if case .background = TargetActionGuard.resolve(+ candidate: target,+ preference: executionPreference,+ lane: .pidEventPost+ ) {+ let clicked = await TargetFocusRecovery.withForeground(processID: pid_t(target.processID), restore: true) { () -> Bool in+ MacPointerInput.moveAndClick(at: center, button: button, clickCount: clicks, target: nil)+ return true+ }+ if clicked == true {+ return clickSucceeded(context, elementID: elementID, label: label, strategy: "coordinate-focus-restore", point: center)+ }+ }+// Foreground path (unchanged behavior): activate the target, then prefer a native Accessibility// action — it works even when a coordinate click would miss (partially obscured, scrolled,// zero-size hit area) — and fall back to a guarded coordinate click on the frame center when no@@ -206,7 +281,8 @@ public final class AXComputerUseToolProvider {reason: "targetNotFrontmost")}- if let bundleIdentifier, !bundleIdentifier.isEmpty,+ if element.isActionEligible,+ let bundleIdentifier, !bundleIdentifier.isEmpty,let action = Self.semanticAction(button: button, clicks: clicks, advertised: advertised),await axPerform(nodeID: element.id, action: action, bundleIdentifier: bundleIdentifier, background: nil) {return clickSucceeded(@@ -234,21 +310,12 @@ public final class AXComputerUseToolProvider {guard let key = trimmed(context.call.input["key"]) else {return result(context, status: .invalidInput, summary: "ax.select_and_press requires a `key` to press.", reason: "missingKey")}- guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {- return result(context, status: .failed, summary: "No window for \(appName).", reason: "noWindowForApp")+ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier, windowTitleHint: target.windowTitleHint) else {+ return result(context, status: .failed, summary: noWindowSummary, reason: "noWindowForApp")}let pid = pid_t(target.processID)- guard await TargetFocusRecovery.ensureFrontmost(processID: pid) else {- return result(- context,- status: .failed,- summary: "\(appName) is not frontmost; \(TargetFocusRecovery.frontmostAppName()) is in front and refocusing failed.",- reason: "targetNotFrontmost"- )- }- // Select the row + focus its container via Accessibility (the reliable, deterministic part), then- // also coordinate-click it: harmless when already selected, and a real click latches selection +- // key focus if the AX select didn't take.+ // Select the row + focus its container via Accessibility (cross-process, no front needed) first;+ // that part is a reliable background RPC.guard let frame = AccessibilityActionExecutor.selectListRow(processID: pid, label: label) else {return result(context,@@ -257,28 +324,49 @@ public final class AXComputerUseToolProvider {reason: "rowNotFound")}- _ = MacPointerInput.moveAndClick(at: AccessibilityActionExecutor.clickPoint(for: frame))- try? await Task.sleep(nanoseconds: 350_000_000)+ let clickPoint = AccessibilityActionExecutor.clickPoint(for: frame)let modifiers = trimmed(context.call.input["modifiers"]).map { [$0] } ?? []- MacKeyboardInput.pressKey(key, modifiers: modifiers)- try? await Task.sleep(nanoseconds: 800_000_000)-+ let confirm = trimmed(context.call.input["confirm"])let chord = modifiers.first.map { "\($0)+\(key)" } ?? key- if let confirm = trimmed(context.call.input["confirm"]) {+ // The click that latches selection and the keypress only land on the ACTIVE app, so run them with+ // the target briefly fronted, then hand focus back on a background turn. The click is harmless when+ // the row is already selected; it latches key focus if the AX select didn't take, and the keypress+ // rides the same window while the row still holds focus.+ let outcome = await TargetFocusRecovery.withForeground(+ processID: pid,+ restore: executionPreference == .background+ ) { () async -> (confirmStuck: Bool, confirmed: Bool) in+ _ = MacPointerInput.moveAndClick(at: clickPoint, target: nil)+ try? await Task.sleep(nanoseconds: 350_000_000)+ MacKeyboardInput.pressKey(key, modifiers: modifiers, target: nil)+ try? await Task.sleep(nanoseconds: 800_000_000)+ guard let confirm else { return (false, false) }AccessibilityActionExecutor.pressModalButton(processID: pid, title: confirm)try? await Task.sleep(nanoseconds: 800_000_000)- if AccessibilityActionExecutor.hasModalPopup(processID: pid) {- return result(- context,- status: .failed,- summary: "Pressed \(chord) on \"\(label)\" but the confirmation dialog is still open.",- reason: "confirmDialogStuck"- )- }+ let stuck = AccessibilityActionExecutor.hasModalPopup(processID: pid)+ return (stuck, !stuck)+ }+ guard let outcome else {+ return result(+ context,+ status: .failed,+ summary: "\(appName) could not be brought to the front to act on \"\(label)\"; \(TargetFocusRecovery.frontmostAppName()) is in front.",+ reason: "targetNotFrontmost"+ )+ }+ if outcome.confirmStuck {+ return result(+ context,+ status: .failed,+ summary: "Pressed \(chord) on \"\(label)\" but the confirmation dialog is still open.",+ reason: "confirmDialogStuck"+ )+ }+ if outcome.confirmed {return result(context,status: .succeeded,- summary: "Selected \"\(label)\", pressed \(chord), and confirmed the \"\(confirm)\" dialog.",+ summary: "Selected \"\(label)\", pressed \(chord), and confirmed the \"\(confirm ?? "")\" dialog.",reason: "actedAndConfirmed")}@@ -290,6 +378,210 @@ public final class AXComputerUseToolProvider {)}+ /// Reads content that spans more than one screen in a single call by alternating an Accessibility read+ /// with a scroll, collecting the distinct text lines it sees. This collapses what would otherwise be+ /// many observe/scroll planning steps — each a full model round-trip — into one tool call: the scroll+ /// and re-read happen locally, and only the assembled text goes back to the planner. Consecutive views+ /// overlap (the scroll advances less than a viewport) so de-duplication drops the overlap without+ /// skipping anything between two reads. Stops at `maxItems`, at `maxScrolls`, or when two passes in a+ /// row surface nothing new (the end of the content).+ private func harvest(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ guard !target.isEmpty else {+ return result(context, status: .failed, summary: "No active app to read. Observe an app first (ax.observe app=\"<App Name>\") or open it.", reason: "noActiveTarget")+ }+ let direction = trimmed(context.call.input["direction"])?.lowercased() ?? "up"+ guard direction == "up" || direction == "down" else {+ return result(context, status: .invalidInput, summary: "content.harvest direction must be \"up\" or \"down\".", reason: "invalidDirection")+ }+ let maxItems = max(1, min(context.call.input["maxItems"].flatMap(Int.init) ?? 60, 500))+ let maxScrolls = max(1, min(context.call.input["maxScrolls"].flatMap(Int.init) ?? 20, 40))+ // Capture the pinned window title once, before the local `target` below shadows the shared context,+ // so the probe/loop reads resolve the same window the whole harvest. An explicit window= on this+ // call pins it directly (and sticks to the target for later steps), so a harvest is self-contained+ // even without a preceding observe; otherwise inherit whatever window the run last pinned.+ let windowTitleHint: String?+ if let requestedWindow = trimmed(context.call.input["window"]) {+ target.retarget(appName: appName, bundleIdentifier: bundleIdentifier, windowTitleHint: requestedWindow)+ windowTitleHint = requestedWindow+ } else {+ windowTitleHint = target.windowTitleHint+ }++ guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier, windowTitleHint: windowTitleHint) else {+ return result(context, status: .failed, summary: noWindowSummary, reason: "noWindowForApp")+ }+ let scrollPoint = harvestScrollPoint(context: context, windowBounds: target.bounds)+ // CGEvent sign convention, shared with mouse.scroll: +y scrolls up, -y scrolls down.+ let deltaY = direction == "up" ? Self.harvestScrollLines : -Self.harvestScrollLines++ // Resolve the scrollable content pane ONCE. The Accessibility page-scroll action on this handle is a+ // cross-process RPC — it scrolls whether or not the app is frontmost and moves no cursor — so a read+ // through it stays fully in the background. Most AppKit lists expose such an area even when the+ // content itself is drawn outside the AX tree (a chat transcript's bubbles). When the window has+ // none, scrolling falls back to a synthetic wheel event, which a backgrounded window drops, so that+ // path briefly fronts the target and restores focus after.+ let scrollArea = AccessibilityActionExecutor.pageScrollAreaHandle(processID: pid_t(target.processID), windowBounds: target.bounds)+ let useAXScroll = scrollArea != nil++ // Choose the READ path from the CONTENT pane, not the whole window: measure the AX text inside the+ // scroll area we will actually read, so a chrome-heavy sidebar or header can't mask a content pane+ // that is drawn outside the tree. When there's a scroll area we read it directly, so the shallow+ // whole-window probe is only needed as the no-scroll-area fallback (and to prove AX is available).+ let probeControls = scrollArea == nil+ ? AccessibilityObserver.observe(appName: appName, bundleIdentifier: bundleIdentifier, windowTitleHint: windowTitleHint)?.controls+ : nil+ let probeLines = probeControls.map(Self.harvestLines(from:)) ?? []+ let contentLineCount = scrollArea.map(AccessibilityActionExecutor.scrollAreaTextLineCount) ?? probeLines.count+ let useVision = contentLineCount < Self.harvestAXProductiveThreshold && visionTextReader != nil+ if !useVision, scrollArea == nil, probeControls == nil {+ return result(context, status: .failed, summary: "Accessibility is unavailable for \(appName) and no vision reader is available. Try vision.capture.", reason: "axUnavailable")+ }+ let cap = useVision ? min(maxScrolls, Self.harvestMaxVisionScrolls) : maxScrolls+ let settle: UInt64 = useVision ? 700_000_000 : 400_000_000++ let scrollUp = direction == "up"+ let scrollStep: () -> Bool = {+ if let scrollArea {+ return AccessibilityActionExecutor.performPageScroll(scrollArea, up: scrollUp)+ }+ return MacPointerInput.scroll(at: scrollPoint, deltaX: 0, deltaY: deltaY, target: nil)+ }++ let visionReader = visionTextReader+ let harvestAppName = appName+ let harvestBundleID = bundleIdentifier+ let harvestWindowHint = windowTitleHint+ // When the content pane is an AX scroll area, read its text DIRECTLY (static text + message-body+ // text areas + links), in reading order — this is what gets a chat transcript's bubbles, which the+ // shallow whole-window snapshot misses. Present newest-first for an "up" harvest so the most-recent+ // lines survive the `maxItems` cap. Falls back to the whole-window observe when there's no scroll+ // area, and to vision only when the content isn't in the tree at all.+ let directReader: (() -> [String])? = scrollArea.map { area in+ {+ let lines = AccessibilityActionExecutor.scrollAreaTextLines(area)+ return scrollUp ? lines.reversed() : lines+ }+ }+ // The whole-window observe read was already paid for by the probe above; seed the loop with it so+ // that fallback path doesn't observe the same unchanged view twice. The direct-reader and vision+ // paths read their own first pass.+ let seedLines: [String]? = (useVision || directReader != nil) ? nil : probeLines+ let runLoop: () async -> (lines: [String], scrolls: Int) = {+ var orderedLines: [String] = []+ var seen = Set<String>()+ var scrolls = 0+ var emptyPasses = 0+ var pending = seedLines+ while true {+ let passLines: [String]+ if let seeded = pending {+ passLines = seeded+ pending = nil+ } else if useVision {+ passLines = await visionReader?() ?? []+ } else if let directReader {+ passLines = directReader()+ } else {+ passLines = AccessibilityObserver.observe(appName: harvestAppName, bundleIdentifier: harvestBundleID, windowTitleHint: harvestWindowHint)+ .map { Self.harvestLines(from: $0.controls) } ?? []+ }+ let before = orderedLines.count+ for text in passLines where !seen.contains(text) {+ seen.insert(text)+ orderedLines.append(text)+ }+ let added = orderedLines.count - before+ if orderedLines.count >= maxItems { break }+ if scrolls >= cap { break }+ // Two consecutive passes with nothing new means the scroll reached the end of the content.+ if added == 0 {+ emptyPasses += 1+ if emptyPasses >= 2 { break }+ } else {+ emptyPasses = 0+ }+ guard scrollStep() else { break }+ scrolls += 1+ // Let the app render the newly revealed rows before the next read.+ try? await Task.sleep(nanoseconds: settle)+ }+ return (Array(orderedLines.prefix(maxItems)), scrolls)+ }++ // The AX-scroll path needs no focus borrow — it runs fully in the background. The synthetic+ // fallback borrows the foreground for the read and restores focus after on a background turn; it+ // returns nil only when the target could not be fronted.+ let harvested: (lines: [String], scrolls: Int)?+ if useAXScroll {+ harvested = await runLoop()+ } else {+ harvested = await TargetFocusRecovery.withForeground(+ processID: pid_t(target.processID),+ restore: executionPreference == .background,+ runLoop+ )+ }+ guard let harvested else {+ return result(+ context,+ status: .failed,+ summary: "\(appName) could not be brought to the front to read; \(TargetFocusRecovery.frontmostAppName()) is in front and refocusing failed.",+ reason: "targetNotFrontmost"+ )+ }+ let collected = harvested.lines+ let scrolls = harvested.scrolls+ let via = useVision ? " via vision" : ""+ guard !collected.isEmpty else {+ return result(+ context,+ status: .succeeded,+ summary: "Harvested no readable text from \(appName)\(via) over \(scrolls) scroll(s). The content may be images or off-screen — try vision.capture scope=screen, or the view may be empty.",+ reason: "harvestEmpty"+ )+ }+ let order = direction == "up" ? "most-recent first" : "in scroll order"+ let body = collected.joined(separator: "\n")+ return HarnessToolResult(+ callID: context.call.id,+ toolName: context.call.name,+ status: .succeeded,+ summary: "Harvested \(collected.count) distinct line(s) from \(appName)\(via) over \(scrolls) scroll(s), \(order):\n\(body)",+ observations: HarnessObservationDelta(facts: [+ "lastAcceptedTool": context.call.name,+ "content.harvest.lineCount": String(collected.count)+ ]),+ metadata: ["direction": direction, "scrolls": String(scrolls), "lineCount": String(collected.count), "source": useVision ? "vision" : "accessibility"]+ )+ }++ /// The distinct-ready text lines a single Accessibility read contributes to a harvest: each control's+ /// label and value, trimmed and non-empty. The harvest loop de-duplicates across passes.+ private static func harvestLines(from controls: [LocalAppDiscoveredControl]) -> [String] {+ var lines: [String] = []+ for control in controls {+ for candidate in [control.label, control.valueSummary ?? ""] {+ let text = candidate.trimmingCharacters(in: .whitespacesAndNewlines)+ if !text.isEmpty { lines.append(text) }+ }+ }+ return lines+ }++ /// The screen point a harvest scroll acts at: the observed scrolling pane when `elementID` names one,+ /// otherwise the target window's center. Mirrors mouse.scroll's targeting.+ private func harvestScrollPoint(context: HarnessToolExecutionContext, windowBounds: WindowTargetBounds) -> CGPoint {+ if let elementID = trimmed(context.call.input["elementID"]),+ let element = context.worldModel.elements.first(where: { $0.id == elementID }),+ let center = Self.screenCenter(from: element.metadata) {+ return center+ }+ return CGPoint(+ x: windowBounds.x + windowBounds.width / 2,+ y: windowBounds.y + windowBounds.height / 2+ )+ }+/// Performs an AX `action` (e.g. `AXPress`, `AXShowMenu`, `AXOpen`) on the control identified by/// `nodeID` via the action backend. Foreground (`background: nil`) re-checks that `bundleIdentifier`/// is the frontmost app before acting; passing a pinned `background` target instead routes the RPC to@@ -394,11 +686,11 @@ public final class AXComputerUseToolProvider {/// Switch the run's active target to `requestedApp`. Resolves it to a running window's exact identity/// when it's already open; otherwise pins it by name so a re-observe after the planner launches it/// resolves cleanly (this observe then reports "no window" rather than acting on the wrong app).- private func retarget(to requestedApp: String) {+ private func retarget(to requestedApp: String, window: String? = nil) {if let resolved = AccessibilityObserver.resolveTarget(appName: requestedApp, bundleIdentifier: nil) {- target.retarget(appName: resolved.appName ?? requestedApp, bundleIdentifier: resolved.bundleIdentifier)+ target.retarget(appName: resolved.appName ?? requestedApp, bundleIdentifier: resolved.bundleIdentifier, windowTitleHint: window)} else {- target.retarget(appName: requestedApp, bundleIdentifier: nil)+ target.retarget(appName: requestedApp, bundleIdentifier: nil, windowTitleHint: window)}}@@ -407,6 +699,16 @@ public final class AXComputerUseToolProvider {return value}+ /// The failure line when no target window resolves. When a specific window was pinned but isn't open,+ /// say so and point the planner at opening it, rather than the generic "no window" that reads as the+ /// whole app being gone.+ private var noWindowSummary: String {+ if let hint = target.windowTitleHint, !hint.isEmpty {+ return "No window titled \"\(hint)\" in \(appName). Open that chat/document first (e.g. double-click it in the list), then retry."+ }+ return "No window for \(appName)."+ }+private func result(_ context: HarnessToolExecutionContext,status: HarnessToolResultStatus,diff --git a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swiftindex 0a58f5a2..25e18a99 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift@@ -438,6 +438,122 @@ public enum AccessibilityActionExecutor {?? windows.first}+ /// The AX window whose on-screen position matches `bounds` — so a scroll acts on the window the run is+ /// actually reading when an app has several windows open at once (a sidebar list AND a detail window).+ /// Falls back to the primary window when nothing lines up.+ private static func window(of app: AXUIElement, matching bounds: WindowTargetBounds) -> AXUIElement? {+ var value: CFTypeRef?+ guard AXUIElementCopyAttributeValue(app, kAXWindowsAttribute as CFString, &value) == .success,+ let windows = value as? [AXUIElement] else { return primaryWindow(of: app) }+ for window in windows {+ var posValue: CFTypeRef?+ guard AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posValue) == .success,+ let posValue else { continue }+ var position = CGPoint.zero+ AXValueGetValue(posValue as! AXValue, .cgPoint, &position)+ if abs(position.x - bounds.x) < 4, abs(position.y - bounds.y) < 4 { return window }+ }+ return primaryWindow(of: app)+ }++ /// The target window's scrollable CONTENT pane, or nil when it has none. A window can hold several+ /// scroll areas (a chat's transcript AND its one-line compose box AND a sidebar), so keep only the ones+ /// we can actually drive — those that implement the page-scroll action, or expose a settable vertical+ /// scroll bar (the fallback for AppKit apps like KakaoTalk whose scroll views don't implement the+ /// action) — then pick the one with the most readable text. That is the transcript/feed, not the+ /// compose field or a thin sidebar.+ private static func pageScrollArea(processID: pid_t, windowBounds: WindowTargetBounds) -> AXUIElement? {+ let app = AXUIElementCreateApplication(processID)+ guard let window = window(of: app, matching: windowBounds) else { return nil }+ let scrollable = descendants(of: window, role: kAXScrollAreaRole as String, limit: 30).filter { area in+ advertisesPageScroll(area) || verticalScrollBar(of: area) != nil+ }+ return scrollable.max { scrollAreaTextLineCount($0) < scrollAreaTextLineCount($1) }+ }++ private static func advertisesPageScroll(_ area: AXUIElement) -> Bool {+ var names: CFArray?+ guard AXUIElementCopyActionNames(area, &names) == .success, let list = names as? [String] else { return false }+ return list.contains("AXScrollUpByPage") && list.contains("AXScrollDownByPage")+ }++ /// The scroll area's vertical scroll bar, whose `AXValue` (0 = top … 1 = bottom) is settable even when+ /// the scroll area's own page-scroll action isn't implemented. Prefers the bar explicitly marked+ /// vertical, else the only bar present.+ private static func verticalScrollBar(of area: AXUIElement) -> AXUIElement? {+ let bars = children(area).filter { axString($0, kAXRoleAttribute as CFString) == (kAXScrollBarRole as String) }+ return bars.first { axString($0, kAXOrientationAttribute as CFString) == (kAXVerticalOrientationValue as String) } ?? bars.first+ }++ /// The target window's page-scrollable Accessibility scroll area, resolved ONCE so a scroll loop can+ /// act on the same handle every pass instead of re-walking the whole tree each time. Nil when the+ /// window exposes none — the caller then falls back to a synthetic wheel event. Whether this is+ /// non-nil is also the deciding fact for whether a background read can stay off the foreground.+ public static func pageScrollAreaHandle(processID: pid_t, windowBounds: WindowTargetBounds) -> AXUIElement? {+ pageScrollArea(processID: processID, windowBounds: windowBounds)+ }++ /// Scrolls a resolved scroll area one page, staying fully in the background (no frontmost requirement,+ /// no cursor). Prefers the native `AXScrollUpByPage`/`AXScrollDownByPage` action where the scroll view+ /// implements it; otherwise steps the vertical scroll bar's value (0 = top … 1 = bottom) by a fraction+ /// of the range so consecutive reads overlap. Many AppKit apps (KakaoTalk) advertise the page-scroll+ /// action but don't implement it — it returns an error — yet accept a scroll-bar value set. Returns+ /// false when it can't move (no scroll bar, or already at the edge with nothing more to load), which+ /// ends the harvest loop.+ public static func performPageScroll(_ area: AXUIElement, up: Bool) -> Bool {+ if AXUIElementPerformAction(area, (up ? "AXScrollUpByPage" : "AXScrollDownByPage") as CFString) == .success {+ return true+ }+ guard let bar = verticalScrollBar(of: area) else { return false }+ var current: CFTypeRef?+ guard AXUIElementCopyAttributeValue(bar, kAXValueAttribute as CFString, ¤t) == .success,+ let value = (current as? NSNumber)?.doubleValue else { return false }+ let next = up ? max(0, value - 0.2) : min(1, value + 0.2)+ guard abs(next - value) > 0.0005 else { return false }+ return AXUIElementSetAttributeValue(bar, kAXValueAttribute as CFString, next as CFNumber) == .success+ }++ /// The scroll area's on-screen text in reading order (top-to-bottom, then left-to-right). Collects+ /// static text (timestamps, sender names), TEXT AREAS (where chat apps like KakaoTalk put the actual+ /// message body — NOT static text), and link titles, so a transcript reads as real content rather than+ /// just its chrome. Walks the content pane directly and deeply, so a message nested far below the+ /// window root isn't cut the way the shallow whole-window snapshot is.+ public static func scrollAreaTextLines(_ area: AXUIElement) -> [String] {+ struct Positioned { var y: Double; var x: Double; var text: String }+ var collected: [Positioned] = []+ func walk(_ element: AXUIElement, depth: Int) {+ guard depth <= 22, collected.count <= 4000 else { return }+ for child in children(element) {+ let role = axString(child, kAXRoleAttribute as CFString) ?? ""+ let text: String?+ if role == (kAXStaticTextRole as String) || role == (kAXTextAreaRole as String) || role == (kAXTextFieldRole as String) {+ text = axString(child, kAXValueAttribute as CFString)+ } else if role == "AXLink" {+ text = axString(child, kAXTitleAttribute as CFString) ?? axString(child, kAXValueAttribute as CFString)+ } else {+ text = nil+ }+ if let trimmed = text?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty {+ let frame = elementFrame(child)+ collected.append(Positioned(y: frame?.y ?? 0, x: frame?.x ?? 0, text: trimmed))+ }+ walk(child, depth: depth + 1)+ }+ }+ walk(area, depth: 0)+ return collected+ .sorted { $0.y != $1.y ? $0.y < $1.y : $0.x < $1.x }+ .map(\.text)+ }++ /// The count of distinct content lines the scroll area exposes — the signal for whether the content it+ /// scrolls is AX-readable (a native list, a chat whose bubbles are text areas) or drawn outside the+ /// tree (a canvas), which decides AX vs. vision reading. Counts the same text roles `scrollAreaTextLines`+ /// reads, so a transcript whose bodies are text areas isn't mistaken for empty.+ public static func scrollAreaTextLineCount(_ area: AXUIElement) -> Int {+ Set(scrollAreaTextLines(area)).count+ }+private static func matchingRow(in list: AXUIElement, label: String) -> AXUIElement? {for row in descendants(of: list, role: kAXRowRole as String, limit: 400) {if rowText(row).contains(label) { return row }diff --git a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityObserver.swift b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityObserver.swiftindex 14e1d723..03103724 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityObserver.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityObserver.swift@@ -15,10 +15,16 @@ public enum AccessibilityObserver {static func observe(appName: String?,bundleIdentifier: String?,+ windowTitleHint: String? = nil,resolver: MacWindowResolver = MacWindowResolver()) -> ResolvedAccessibilityObservation? {guard AXIsProcessTrusted(),- let target = resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier, resolver: resolver)+ let target = resolveTarget(+ appName: appName,+ bundleIdentifier: bundleIdentifier,+ windowTitleHint: windowTitleHint,+ resolver: resolver+ )else {return nil}@@ -49,14 +55,14 @@ public enum AccessibilityObserver {public static func resolveTarget(appName: String?,bundleIdentifier: String?,+ windowTitleHint: String? = nil,resolver: MacWindowResolver = MacWindowResolver()) -> MacWindowTargetCandidate? {if appName != nil || bundleIdentifier != nil {// A specific app was requested: only ever return that app's window. If it isn't running /// has no window, return nil — never fall back to the frontmost window, which would// silently ground (and potentially click) in an unrelated app the user didn't name.- let candidates = resolver.enumerateCandidates()- return candidates.first { candidate in+ let appWindows = resolver.enumerateCandidates().filter { candidate inif let bundleIdentifier, let candidateBundle = candidate.bundleIdentifier {return candidateBundle.caseInsensitiveCompare(bundleIdentifier) == .orderedSame}@@ -65,7 +71,29 @@ public enum AccessibilityObserver {}return false}+ // A specific window was named (a conversation, a document): return the app window whose title+ // matches it, and NEVER fall back to another window when none match — silently reading or+ // clicking the wrong window of the app is exactly the failure this pin exists to prevent. The+ // caller reports "no such window; open it first" so the planner opens the chat rather than+ // acting on the contact list.+ if let hint = windowTitleHint?.trimmingCharacters(in: .whitespacesAndNewlines), !hint.isEmpty {+ return appWindows.first { candidate in+ guard let title = candidate.title, !title.isEmpty else { return false }+ return titleMatches(title, hint)+ }+ }+ return appWindows.first}return try? resolver.selectTarget()}++ /// Whether a window's title identifies the window the planner named. Case-insensitive containment in+ /// either direction so a hint of "Juyoung" matches a window titled "Juyoung Lee", and a CG title that+ /// the system truncated still matches a longer hint. Matching by the human name the user already gave+ /// keeps this app-agnostic — no per-app window heuristics.+ static func titleMatches(_ title: String, _ hint: String) -> Bool {+ let normalizedTitle = title.lowercased()+ let normalizedHint = hint.lowercased()+ return normalizedTitle.contains(normalizedHint) || normalizedHint.contains(normalizedTitle)+ }}diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/kakao/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/kakao/SKILL.mdnew file mode 100644index 00000000..ab4e4f92--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/kakao/SKILL.md@@ -0,0 +1,34 @@+# KakaoTalk++id: kakao+description: Read and send KakaoTalk chats through the GUI — there is no API or AppleScript. Find a person by search, read the transcript with content.harvest, and confirm before sending anything.+tags: messages, kakao, kakaotalk, chat, local-app+keywords: kakao, kakaotalk, message, chat, dm, conversation, read, reply, send, korean+apps: KakaoTalk, com.kakao.KakaoTalkMac+tools: app_skill++KakaoTalk has no API and is not scriptable, so drive it through the window with `ax.observe`, `ax.click`, `content.harvest`, and `mouse.scroll`. Reading is an Accessibility + vision job; sending is external and irreversible — it lands on someone else's phone.++## Open the person's chat+- `ax.observe` the main window. The chat list and the search field are Accessibility-readable even though the message bubbles are not.+- Find a person by typing their name into the search field, then `ax.click` the result row to open the chat. A chat opens scrolled to the newest message at the bottom.+- Each chat opens in its OWN separate window, titled with the person's name. The contact list stays in a different window, so from here on you must tell the tools which window you mean.+- Names may be Korean; use the exact text the search returns rather than transliterating.++## Read the conversation+- Read the chat window by name: `content.harvest window="<person's name>" direction=up`. The `window=` is essential — it resolves the conversation window, not the contact list; without it harvest reads the list's row previews instead of the transcript. If it reports no window titled that, the chat isn't open yet; open it from the list first.+- KakaoTalk's bubbles are not in the Accessibility tree, so harvest reads them through vision on its own — you do not need a separate `vision.capture` or scroll loop. It gathers the visible text, scrolls up, and repeats in one call.+- Ask for a bit more than you need — for "the last 10 messages" pass maxItems around 20 — then take the most recent from the result. With direction=up the result is most-recent first.+- The gathered lines mix sender names, timestamps, and bubble text together. Read them in order and pick out the actual messages and who sent them.+- Older messages load lazily: KakaoTalk shows only the most recent bubbles, with earlier ones behind a "View Previous Chats" button. If the harvest returns fewer messages than requested, `ax.click` "View Previous Chats" (or scroll up) to load more, then harvest again — repeat until you have the count or the conversation runs out. Save whatever exists when it does.++## Save to a file+- Write the collected messages to the conversation's working folder with `files.write` (e.g. one message per line with the sender), then confirm the file exists before completing.++## Sending requires confirmation+- Before sending anything, confirm the exact recipient and the exact text with the user (`user.clarify`), unless they already dictated both precisely.+- Send by opening the person's chat, typing into the message field, and pressing return.++## Verify+- After reading, confirm you have the requested count of messages before completing.+- After sending, re-observe the transcript and confirm the sent bubble appears.diff --git a/apps/Donkey/Sources/DonkeyRuntime/ScreenTextRecognizer.swift b/apps/Donkey/Sources/DonkeyRuntime/ScreenTextRecognizer.swiftnew file mode 100644index 00000000..b6764091--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/ScreenTextRecognizer.swift@@ -0,0 +1,51 @@+import CoreGraphics+import Foundation+import ImageIO+import Vision++/// On-device OCR of a screenshot's pixels into text lines, in reading order. This is the read path for+/// content that is drawn rather than exposed in the Accessibility tree — a chat transcript's bubbles, a+/// canvas, a custom list. It reads the actual visible text, which the+/// UI-element detector does not: that detector finds controls (buttons, fields), so it returns a window's+/// chrome and misses the message text sitting between the controls. Native Vision framework, so it runs+/// without a network round-trip and reads whatever language is on screen.+public enum ScreenTextRecognizer {+ /// Recognized lines from PNG-encoded screenshot bytes, ordered top-to-bottom then left-to-right — the+ /// reading order a transcript or feed needs. Empty when the image can't be decoded or holds no legible+ /// text (a photo, an icon grid).+ public static func recognizeLines(inPNG pngData: Data) -> [String] {+ guard let source = CGImageSourceCreateWithData(pngData as CFData, nil),+ let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else {+ return []+ }+ return recognizeLines(in: image)+ }++ /// Recognized lines from a decoded image, in reading order.+ public static func recognizeLines(in image: CGImage) -> [String] {+ let request = VNRecognizeTextRequest()+ request.recognitionLevel = .accurate+ request.usesLanguageCorrection = true+ // Let Vision pick the language from the pixels instead of pinning one, so a chat that mixes Korean+ // and English (or any other script) reads correctly without the caller naming languages per app.+ if #available(macOS 13.0, *) {+ request.automaticallyDetectsLanguage = true+ }+ let handler = VNImageRequestHandler(cgImage: image, options: [:])+ guard (try? handler.perform([request])) != nil else { return [] }+ // Vision returns observations in no guaranteed order. The bounding box origin is bottom-left and+ // normalized, so a larger y sits higher on screen. Quantize y into normalized bands and sort by+ // band (descending, top first) then x (ascending, left first): bands group the fragments of one+ // visual line together left-to-right, and comparing integer bands is a TOTAL order — a raw+ // near-equal-y threshold is intransitive (A~B, B~C, but A≁C) and lets the sort scramble lines.+ return (request.results ?? [])+ .sorted { lhs, rhs in+ let lband = (lhs.boundingBox.origin.y * 100).rounded()+ let rband = (rhs.boundingBox.origin.y * 100).rounded()+ if lband != rband { return lband > rband }+ return lhs.boundingBox.origin.x < rhs.boundingBox.origin.x+ }+ .compactMap { $0.topCandidates(1).first?.string.trimmingCharacters(in: .whitespacesAndNewlines) }+ .filter { !$0.isEmpty }+ }+}