Open source CapCut alternative.
TypeScript
Add accessibility-grounded cursor path builder (overlay phase 1)
David Leb14486a3c38c
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityCursorPathBuilder.swift b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityCursorPathBuilder.swiftnew file mode 100644index 00000000..fbc7df32--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityCursorPathBuilder.swift@@ -0,0 +1,142 @@+import DonkeyContracts+import Foundation++/// A control to point at, resolved from an accessibility observation by text.+public struct AccessibilityCursorPathTarget: Equatable, Sendable {+ /// Text used to resolve the control (matched against control label / id / metadata controlID).+ public var query: String+ /// Human-facing label shown on the overlay for this step.+ public var label: String+ /// Path-step semantics (e.g. `.targetControl` to point, `.act` to indicate a click).+ public var kind: AgentPathStepKind++ public init(query: String, label: String, kind: AgentPathStepKind = .targetControl) {+ self.query = query+ self.label = label+ self.kind = kind+ }+}++/// Builds a grounded cursor path from an accessibility observation, decoupled from any execution+/// backend. Works for any app that exposes an accessibility tree — native or Electron (Chromium) —+/// which is exactly the case where AppleScript cannot help.+///+/// This type is pure: it takes already-observed controls + the target window bounds and produces+/// `normalizedTarget` `AgentPathStep`s. Live capture (snapshot → controls) and overlay presentation+/// are wired separately. Targets that cannot be resolved to a positive-area control are dropped, so+/// the overlay never invents motion to an ungrounded point.+public enum AccessibilityCursorPathBuilder {+ public static func buildSteps(+ targetApp: String,+ windowBounds: WindowTargetBounds,+ controls: [LocalAppDiscoveredControl],+ targets: [AccessibilityCursorPathTarget],+ phaseID: String = ""+ ) -> [AgentPathStep] {+ guard windowBounds.width > 0, windowBounds.height > 0 else { return [] }+ var usedControlIDs: Set<String> = []+ return targets.compactMap { target in+ guard let control = resolve(target.query, in: controls, excluding: usedControlIDs),+ let frame = control.frame,+ frame.hasPositiveArea,+ let bounds = normalized(frame, in: windowBounds)+ else {+ return nil+ }+ usedControlIDs.insert(control.id)+ return AgentPathStep(+ id: stepID(for: target.query),+ phaseID: phaseID,+ kind: target.kind,+ label: target.label,+ targetApp: targetApp,+ point: center(of: bounds),+ bounds: bounds,+ controlID: control.id,+ source: .accessibility,+ status: .observed+ )+ }+ }++ // MARK: - Control resolution++ /// Resolves the best control for `query` by normalized-text relevance. Prefers an exact label+ /// match, then containment, then token overlap; ties break toward the larger control.+ static func resolve(+ _ query: String,+ in controls: [LocalAppDiscoveredControl],+ excluding used: Set<String> = []+ ) -> LocalAppDiscoveredControl? {+ let normalizedQuery = LocalAppTextNormalizer.normalizedPhrase(query)+ guard !normalizedQuery.isEmpty else { return nil }+ let queryTokens = Set(normalizedQuery.split(separator: " ").map(String.init))++ var best: (control: LocalAppDiscoveredControl, score: Double)?+ for control in controls where !used.contains(control.id) {+ guard let frame = control.frame, frame.hasPositiveArea else { continue }+ let candidates = [control.label, control.metadata["controlID"] ?? "", control.id]+ .map(LocalAppTextNormalizer.normalizedPhrase)+ .filter { !$0.isEmpty }+ guard !candidates.isEmpty else { continue }++ var score = 0.0+ for candidate in candidates {+ if candidate == normalizedQuery {+ score = max(score, 1_000)+ } else if candidate.contains(normalizedQuery) || normalizedQuery.contains(candidate) {+ score = max(score, 500)+ } else {+ let candidateTokens = Set(candidate.split(separator: " ").map(String.init))+ let overlap = queryTokens.intersection(candidateTokens).count+ if overlap > 0 {+ score = max(score, Double(overlap))+ }+ }+ }+ guard score > 0 else { continue }+ // Tie-break toward the larger control (more likely the intended, prominent target).+ let area = frame.width * frame.height+ let composite = score * 1_000_000 + area+ if best == nil || composite > best!.score {+ best = (control, composite)+ }+ }+ return best?.control+ }++ // MARK: - Geometry++ /// Normalizes a screen-space control frame to the target window's `normalizedTarget` space,+ /// clamping each edge so the rect stays within [0, 1] even for controls partly off-window.+ static func normalized(_ frame: WindowTargetBounds, in window: WindowTargetBounds) -> HotLoopRect? {+ guard window.width > 0, window.height > 0 else { return nil }+ let left = clamp((frame.x - window.x) / window.width)+ let top = clamp((frame.y - window.y) / window.height)+ let right = clamp((frame.x + frame.width - window.x) / window.width)+ let bottom = clamp((frame.y + frame.height - window.y) / window.height)+ let width = right - left+ let height = bottom - top+ guard width > 0, height > 0 else { return nil }+ return HotLoopRect(x: left, y: top, width: width, height: height, space: .normalizedTarget)+ }++ private static func center(of bounds: HotLoopRect) -> HotLoopPoint {+ HotLoopPoint(+ x: clamp(bounds.origin.x + bounds.size.width / 2),+ y: clamp(bounds.origin.y + bounds.size.height / 2),+ space: .normalizedTarget+ )+ }++ private static func clamp(_ value: Double) -> Double {+ min(max(value, 0), 1)+ }++ private static func stepID(for query: String) -> String {+ let slug = LocalAppTextNormalizer.normalizedPhrase(query)+ .split(separator: " ")+ .joined(separator: "-")+ return slug.isEmpty ? "target" : slug+ }+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AccessibilityCursorPathBuilderTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AccessibilityCursorPathBuilderTests.swiftnew file mode 100644index 00000000..bdaad7da--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AccessibilityCursorPathBuilderTests.swift@@ -0,0 +1,125 @@+import DonkeyContracts+@testable import DonkeyRuntime+import Foundation+import Testing++@Suite+struct AccessibilityCursorPathBuilderTests {+ // A 1000x800 window at screen origin (200, 100).+ private let window = WindowTargetBounds(x: 200, y: 100, width: 1_000, height: 800)++ private func control(+ id: String,+ label: String,+ kind: LocalAppControlKind = .button,+ x: Double,+ y: Double,+ width: Double,+ height: Double,+ controlID: String? = nil+ ) -> LocalAppDiscoveredControl {+ LocalAppDiscoveredControl(+ id: id,+ kind: kind,+ label: label,+ frame: WindowTargetBounds(x: x, y: y, width: width, height: height),+ metadata: controlID.map { ["controlID": $0] } ?? [:]+ )+ }++ @Test+ func groundsResolvedControlsToNormalizedTargetSteps() {+ // Search field centered horizontally near the top; a result row lower-left.+ let controls = [+ control(id: "search", label: "Search", kind: .searchField, x: 600, y: 140, width: 200, height: 40),+ control(id: "row-1", label: "Yellow — Coldplay", kind: .listItem, x: 260, y: 400, width: 480, height: 60)+ ]+ let steps = AccessibilityCursorPathBuilder.buildSteps(+ targetApp: "Spotify",+ windowBounds: window,+ controls: controls,+ targets: [+ AccessibilityCursorPathTarget(query: "Search", label: "Search box", kind: .targetControl),+ AccessibilityCursorPathTarget(query: "Yellow Coldplay", label: "Play Yellow", kind: .act)+ ]+ )++ #expect(steps.count == 2)++ // Search field center: x=(700-200)/1000=0.5, y=(160-100)/800=0.075.+ let search = steps[0]+ #expect(search.kind == .targetControl)+ #expect(search.source == .accessibility)+ #expect(search.controlID == "search")+ let searchPoint = try! #require(search.point)+ #expect(searchPoint.space == .normalizedTarget)+ #expect(abs(searchPoint.x - 0.5) < 0.0001)+ #expect(abs(searchPoint.y - 0.075) < 0.0001)++ // Result row center: x=(500-200)/1000=0.3, y=(430-100)/800=0.4125.+ let play = steps[1]+ #expect(play.kind == .act)+ #expect(play.controlID == "row-1")+ let playPoint = try! #require(play.point)+ #expect(abs(playPoint.x - 0.3) < 0.0001)+ #expect(abs(playPoint.y - 0.4125) < 0.0001)+ }++ @Test+ func dropsTargetsThatDoNotResolveOrLackGeometry() {+ let controls = [+ control(id: "search", label: "Search", kind: .searchField, x: 600, y: 140, width: 200, height: 40),+ // Zero-area control must be ignored even though its label matches.+ control(id: "ghost", label: "Settings", x: 10, y: 10, width: 0, height: 0)+ ]+ let steps = AccessibilityCursorPathBuilder.buildSteps(+ targetApp: "Spotify",+ windowBounds: window,+ controls: controls,+ targets: [+ AccessibilityCursorPathTarget(query: "Search", label: "Search"),+ AccessibilityCursorPathTarget(query: "Settings", label: "Settings"), // zero-area → dropped+ AccessibilityCursorPathTarget(query: "Nonexistent", label: "Nope") // no match → dropped+ ]+ )+ #expect(steps.map(\.controlID) == ["search"])+ }++ @Test+ func prefersExactLabelOverPartialMatch() {+ let controls = [+ control(id: "play-pause", label: "Play / Pause", x: 500, y: 700, width: 40, height: 40),+ control(id: "playlist", label: "Play", kind: .button, x: 260, y: 300, width: 80, height: 30)+ ]+ let resolved = AccessibilityCursorPathBuilder.resolve("Play", in: controls)+ #expect(resolved?.id == "playlist")+ }++ @Test+ func returnsEmptyForDegenerateWindow() {+ let steps = AccessibilityCursorPathBuilder.buildSteps(+ targetApp: "Spotify",+ windowBounds: WindowTargetBounds(x: 0, y: 0, width: 0, height: 0),+ controls: [control(id: "search", label: "Search", x: 10, y: 10, width: 20, height: 20)],+ targets: [AccessibilityCursorPathTarget(query: "Search", label: "Search")]+ )+ #expect(steps.isEmpty)+ }++ @Test+ func clampsOffWindowControlsIntoUnitRange() {+ // A control partly outside the window must clamp to [0, 1].+ let controls = [control(id: "edge", label: "Edge", x: 1_150, y: 850, width: 200, height: 200)]+ let steps = AccessibilityCursorPathBuilder.buildSteps(+ targetApp: "App",+ windowBounds: window,+ controls: controls,+ targets: [AccessibilityCursorPathTarget(query: "Edge", label: "Edge")]+ )+ let bounds = try! #require(steps.first?.bounds)+ #expect(bounds.origin.x >= 0 && bounds.origin.x <= 1)+ #expect(bounds.origin.y >= 0 && bounds.origin.y <= 1)+ #expect(bounds.origin.x + bounds.size.width <= 1.0001)+ #expect(bounds.origin.y + bounds.size.height <= 1.0001)+ }+}diff --git a/apps/Donkey/docs/adaptive-grounded-overlay-plan.md b/apps/Donkey/docs/adaptive-grounded-overlay-plan.mdnew file mode 100644index 00000000..bc123fc0--- /dev/null+++ b/apps/Donkey/docs/adaptive-grounded-overlay-plan.md@@ -0,0 +1,126 @@+# Adaptive grounded pointer overlay — implementation plan++## Context++Donkey can drive scriptable apps via AppleScript (e.g. Music, now playing reliably through the+`music-media` skill). But:++- **Electron / non-scriptable apps** (Spotify, Slack, Discord, VS Code) have no useful AppleScript+ dictionary, so the AppleScript path can't act on them.+- Users also ask **"show me where X is" / "how do I X"** — a guidance intent where Donkey should+ *point*, not act.++The pointer overlay must therefore be **grounded in accessibility, decoupled from the execution+backend**. AppleScript is one way to *act*; the overlay only needs *coordinates*, which come from+the accessibility (AX) tree — available for native **and** Electron apps. The harness must+**self-select** the strategy rather than have it hard-wired.++## Goal++The harness figures out, per turn:++```+Classify intent:+ "show me / how do I / where is X" → GUIDANCE+ "do X" (play, open, send, …) → ACTION++GUIDANCE → AX-grounded cursor path, overlay only (realPointerMoved=false). No input.++ACTION:+ 1. Target app scriptable + skill/AppleScript available → AppleScript (today's path).+ 2. App not scriptable (Electron) OR AppleScript fails/blocked+ → AX + screenshot fallback: observe → resolve target control → grounded path+ → move real pointer + click/type (input backend, focus+safety guards)+ → overlay tracks the pointer → verify.+```++## What already exists (reuse, don't rebuild)++| Capability | Where |+| --- | --- |+| Cursor overlay window + animation | `PointerCoachCursorOverlayController` (Donkey), `PointerCoachCursorOverlayView`/`…ViewModel` (DonkeyUI) |+| Visualize tool (grounded steps → overlay request) | `agent.path.visualize` in `GenericHarnessBuiltInToolExecutors`; `AgentPathStep`/`AgentVisualizationPlan` (DonkeyContracts) |+| Overlay presented from a run result | `UserQueryOverlayModel.agentVisualizationPresenter` consumes `result.cursorOverlayRequest` (and streaming `agentVisualizationChanged`) |+| AX element frames | `MacAccessibilitySnapshotCaptureService`, `LocalAppAccessibilityControls` (`frame: WindowTargetBounds`) |+| Screen→normalizedTarget grounding | `LocalAppObservationGeometry.normalizedStepBounds` / coordinate mapper |+| Real input (mouse + keyboard via CGEvent) | `MacKeyboardActionEngineInputBackend` (`leftMouseDown/Up`, keyboard) |+| Engine selection | `LocalAppTaskActionEngines.keyboardOrAutomation(for:)` |+| Safety guards | `ActionEngineGuardrails` / `ActionEngineConfiguration.liveInputEnabled`, focus guard, `targetIsSafeForInput` |+| Live-run → visualization | `LocalAppTaskAgentVisualizationBuilder.plan(for:)` (currently grounds at window level → `noGroundedTargets`) |++The gap is the **decision logic** plus an **AX-grounded path builder** that resolves a target+control to element-level `normalizedTarget` coordinates (today grounding only reaches window level,+which is why skill/AppleScript runs produce `noGroundedTargets`).++## Design / new components++### A. Intent classification (GUIDANCE vs ACTION)+- Add a `guidance` route alongside `localAppTask`/`conversation`/`clarification` in the planner+ (`HostedTaskIntentParsingAdapter` instructions + `generic_harness_planning` schema route enum,+ `TaskIntentWireCodec`). Guidance = "show/point/where is/how do I", no state change.+- Guidance carries the target app + a target description (what to point at), no action payload.++### B. AX-grounded path builder (the shared foundation) — new in DonkeyRuntime+`AccessibilityCursorPathBuilder` (working name):+- Input: target app + ordered list of target descriptions (label/role/text).+- Observe via `MacAccessibilitySnapshotCaptureService` (works for Electron — Chromium AX), discover+ controls with frames via `LocalAppAccessibilityControls`.+- Resolve each description to the best-matching control (reuse `LocalAppTextNormalizer` matching).+- Normalize each control `frame` → `normalizedTarget` `HotLoopRect`/`HotLoopPoint`+ (`LocalAppObservationGeometry`).+- Emit grounded `AgentPathStep[]` (kind `.targetControl`/`.act`, `source: .accessibility`,+ `status: .observed/.executed`).+- Returns `nil`/`blocked` for ungrounded targets (overlay refuses to invent motion — existing tool+ contract).++### C. Strategy router + automatic fallback+- **Capability detection**: is the target app scriptable? Signals: app-finder catalog control+ profile / a known-scriptable allowlist (Music, Notes, …) vs Electron markers; plus **runtime**+ signal — AppleScript generate returns `canGenerate=false`/blocked or `automation.applescript.execute`+ / `skill.script.execute` fails.+- Router (in `UserQueryCommandHandler` run path / `executeGenericHarnessLoop`):+ - GUIDANCE → builder (B) → `agent.path.visualize` → overlay; never run input.+ - ACTION scriptable → AppleScript (today).+ - ACTION non-scriptable OR AppleScript failed → builder (B) → execute grounded path via input+ backend (pointer move + click/type) with guards; overlay tracks.++### D. Action execution on Electron (real input)+- Use `MacKeyboardActionEngineInputBackend` (CGEvent mouse move + click, keyboard) driven by the+ grounded path's screen coordinates.+- Gate with `ActionEngineConfiguration.liveInputEnabled` + focus guard + `targetIsSafeForInput`.+- Overlay (`realPointerMoved=true` here, or mirror) tracks the executed path.++### E. Overlay wiring+- Guidance/visualization already flows: result `cursorOverlayRequest` →+ `UserQueryOverlayModel.agentVisualizationPresenter` → controller. Ensure the guidance route and+ the AX-action path both populate `cursorOverlayRequest`/stream `agentVisualizationChanged`.++## Phased implementation (each independently verifiable)++1. **AX-grounded path builder (B).** New `AccessibilityCursorPathBuilder` + unit tests with a+ synthetic AX snapshot (element frames → expected `normalizedTarget` steps). No app needed.+2. **Guidance route + overlay (A, E).** Planner emits `guidance`; handler builds path via (B) and+ shows the overlay; no input. Verify live on an Electron app ("show me the search box in Spotify")+ — pointer animates to it, nothing is clicked.+3. **Strategy router + fallback (C).** Capability detection + AppleScript-failure fallback wired in+ the run loop. Verify: Music still uses AppleScript; a non-scriptable app routes to the AX path.+4. **Electron real-pointer action (D).** Execute the grounded path with the input backend + guards;+ overlay tracks. Verify live: "play <song> on Spotify" moves the pointer to the result and clicks.++## Verification++- Unit: builder grounding math (synthetic AX frames → normalized steps); router decision table+ (guidance/action × scriptable/non-scriptable × applescript-ok/failed).+- Live smoke (env-gated, like `MusicPlaybackLiveSmokeTests`): guidance overlay on Spotify (phase 2);+ AX action on Spotify (phase 4). Requires Spotify installed + Accessibility granted to the runner.++## Risks / open questions++- **Real input is safety-sensitive** (moves the actual mouse/clicks). Phase 4 stays behind+ `liveInputEnabled` + focus guard; default off outside explicit live runs.+- **Element resolution quality** on Electron: AX labels can be sparse; may need the screenshot ++ local-UI-understanding fallback (`strategyOrder: accessibility,windowMetadata,screenshotForLocalModel`)+ to locate controls when AX is thin.+- **Capability detection** accuracy (scriptable vs not) — start with an allowlist + runtime failure+ fallback; refine over time.+- Environment for live demo: Spotify must be installed/running and the runner AX-granted.