Open source CapCut alternative.
TypeScript
feat(app): add general ax.select_and_press; drop the Music-specific playlist delete
David Le1b827847a6ab
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swiftindex 3e4dcd4b..4b6e90ea 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift@@ -16,6 +16,7 @@ public final class AXComputerUseToolProvider {public enum ToolName {public static let observe = "ax.observe"public static let click = "ax.click"+ public static let selectAndPress = "ax.select_and_press"}private let appName: String@@ -51,6 +52,22 @@ public final class AXComputerUseToolProvider {safetyClass: .guardedInput,requiredContext: ["frontmost target", "observed control"],verificationHints: ["re-observe to confirm the click changed state"]+ ),+ HarnessToolDescriptor(+ name: ToolName.selectAndPress,+ pluginID: "core.computer-use.ax",+ summary: "Select a named list/sidebar/table row and press a key on it — ATOMICALLY in one call, so the keypress lands while the row still holds selection and keyboard focus. Doing this as separate observe/click/press steps loses that focus and the key hits nothing. Use it for keyboard-driven row actions in any app: delete a row (key=delete), open it (key=return), or move a file to Trash (key=delete, modifiers=command). Pass confirm=<button title> to also press a confirmation dialog's button that appears afterward (e.g. confirm=Delete). Find the exact row text with ax.observe first if unsure. Re-observe after to verify the effect.",+ inputSchema: [+ "label": "Exact visible text of the list/sidebar/table row to act on.",+ "key": "Key to press once the row is selected (e.g. delete, return).",+ "modifiers": "Optional modifier for the key (e.g. command).",+ "confirm": "Optional title of a confirmation-dialog button to press afterward (e.g. Delete, OK)."+ ],+ optionalInputKeys: ["modifiers", "confirm"],+ requiredPermissions: [.input],+ safetyClass: .guardedInput,+ requiredContext: ["frontmost target"],+ verificationHints: ["re-observe to confirm the row is gone / the action took effect"])]}@@ -67,6 +84,7 @@ public final class AXComputerUseToolProvider {switch context.call.name {case ToolName.observe: return observe(context)case ToolName.click: return await click(context)+ case ToolName.selectAndPress: return await selectAndPress(context)default:return result(context, status: .unknownTool, summary: "Unknown AX tool.", reason: "unknownAXTool")}@@ -134,6 +152,75 @@ public final class AXComputerUseToolProvider {return clickSucceeded(context, elementID: elementID, label: label, strategy: "coordinate", point: center)}+ /// Atomically selects a named list/sidebar/table row and presses a key on it (optionally confirming+ /// a dialog) — the general, app-agnostic version of "delete the selected row". Splitting select and+ /// keypress across separate planner steps loses the row's keyboard focus (the app re-activates, the+ /// overlay takes key focus), so the key lands nowhere; doing both here, with no step gap, mirrors a+ /// real user. Works for any app's list UI (playlists, notes, mail, files); grids/collections aren't+ /// row-based and aren't covered.+ private func selectAndPress(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ guard let label = trimmed(context.call.input["label"]) else {+ return result(context, status: .invalidInput, summary: "ax.select_and_press requires the row's `label`.", reason: "missingLabel")+ }+ 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")+ }+ 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.+ guard let frame = AccessibilityActionExecutor.selectListRow(processID: pid, label: label) else {+ return result(+ context,+ status: .failed,+ summary: "No row labeled \"\(label)\" in a list/sidebar/table of \(appName). Re-observe; it may be offscreen, still syncing, or named differently.",+ reason: "rowNotFound"+ )+ }+ _ = MacPointerInput.moveAndClick(at: AccessibilityActionExecutor.clickPoint(for: frame))+ try? await Task.sleep(nanoseconds: 350_000_000)+ let modifiers = trimmed(context.call.input["modifiers"]).map { [$0] } ?? []+ MacKeyboardInput.pressKey(key, modifiers: modifiers)+ try? await Task.sleep(nanoseconds: 800_000_000)++ let chord = modifiers.first.map { "\($0)+\(key)" } ?? key+ if let confirm = trimmed(context.call.input["confirm"]) {+ 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"+ )+ }+ return result(+ context,+ status: .succeeded,+ summary: "Selected \"\(label)\", pressed \(chord), and confirmed the \"\(confirm)\" dialog.",+ reason: "actedAndConfirmed"+ )+ }+ return result(+ context,+ status: .succeeded,+ summary: "Selected \"\(label)\" and pressed \(chord).",+ reason: "acted"+ )+ }+/// Performs an `AXPress` on the control identified by `nodeID` via the Accessibility action backend,/// which re-checks that `bundleIdentifier` is the frontmost app before acting. Returns whether the/// press landed.diff --git a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swiftindex 66e953ed..9d5ca944 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AccessibilityActionExecutor.swift@@ -1,6 +1,8 @@+@preconcurrency import ApplicationServicesimport CoreGraphicsimport DonkeyContractsimport Foundation+import OSLog/// Low-level keyboard input via CGEvent. Real input — gate behind explicit permission/guards.public enum MacKeyboardInput {@@ -278,4 +280,173 @@ public enum AccessibilityActionExecutor {nonisolated static func clickPoint(for frame: WindowTargetBounds) -> CGPoint {CGPoint(x: frame.x + frame.width / 2, y: frame.y + frame.height / 2)}++ // MARK: - Deterministic list-row deletion primitives++ private static let log = Logger(subsystem: "com.donkeyuse.Donkey", category: "ax-delete")++ /// Selects a list/outline/table row whose label matches `label`, and gives its enclosing list+ /// keyboard focus — the deterministic equivalent of a user clicking the row. Returns the row's+ /// screen frame (top-left origin) on success so the caller can also coordinate-click it. This is+ /// what a synthetic coordinate click alone fails to do reliably for AppKit sidebars: the row ends+ /// up genuinely selected AND its container holds key focus, so a following Delete key acts on it.+ public static func selectListRow(processID: pid_t, label: String) -> WindowTargetBounds? {+ let app = AXUIElementCreateApplication(processID)+ guard let window = primaryWindow(of: app) else {+ log.error("selectListRow: no window for pid \(processID)")+ return nil+ }+ guard let list = firstDescendant(of: window, role: kAXOutlineRole as String)+ ?? firstDescendant(of: window, role: kAXTableRole as String)+ ?? firstDescendant(of: window, role: kAXListRole as String) else {+ log.error("selectListRow: no outline/table/list in window")+ return nil+ }+ guard let row = matchingRow(in: list, label: label) else {+ log.error("selectListRow: no row labeled \(label, privacy: .public)")+ return nil+ }+ // Select the row and focus its container — the two halves a real click does.+ AXUIElementSetAttributeValue(row, kAXSelectedAttribute as CFString, kCFBooleanTrue)+ AXUIElementSetAttributeValue(list, kAXFocusedAttribute as CFString, kCFBooleanTrue)+ let frame = elementFrame(row)+ log.info("selectListRow: selected \(label, privacy: .public) frame=\(String(describing: frame), privacy: .public)")+ return frame+ }++ /// Presses (AXPress) the button titled `title` inside the app's frontmost modal — a separate dialog+ /// window (subrole `AXDialog`/`AXSystemDialog`) or an attached sheet. Music's delete confirmation has+ /// NO default button, so a Return keystroke can't dismiss it; a direct AX press is the reliable+ /// confirm. Matches only inside a modal subtree so a same-named button elsewhere can't be hit.+ @discardableResult+ public static func pressModalButton(processID: pid_t, title: String) -> Bool {+ let app = AXUIElementCreateApplication(processID)+ var value: CFTypeRef?+ guard AXUIElementCopyAttributeValue(app, kAXWindowsAttribute as CFString, &value) == .success,+ let windows = value as? [AXUIElement] else { return false }+ for window in windows {+ if let button = modalButton(in: window, title: title, inModal: false, depth: 0),+ AXUIElementPerformAction(button, kAXPressAction as CFString) == .success {+ log.info("pressModalButton: pressed \(title, privacy: .public)")+ return true+ }+ }+ return false+ }++ /// True if the app has a modal popup open (separate `AXDialog`/`AXSystemDialog` window or `AXModal`).+ public static func hasModalPopup(processID: pid_t) -> Bool {+ let app = AXUIElementCreateApplication(processID)+ var value: CFTypeRef?+ guard AXUIElementCopyAttributeValue(app, kAXWindowsAttribute as CFString, &value) == .success,+ let windows = value as? [AXUIElement] else { return false }+ for window in windows {+ let subrole = axString(window, kAXSubroleAttribute as CFString)+ if subrole == (kAXDialogSubrole as String) || subrole == (kAXSystemDialogSubrole as String) {+ return true+ }+ var modal: CFTypeRef?+ if AXUIElementCopyAttributeValue(window, kAXModalAttribute as CFString, &modal) == .success,+ (modal as? Bool) == true { return true }+ }+ return false+ }++ // MARK: - Raw AX helpers++ private static func primaryWindow(of app: AXUIElement) -> AXUIElement? {+ var value: CFTypeRef?+ guard AXUIElementCopyAttributeValue(app, kAXWindowsAttribute as CFString, &value) == .success,+ let windows = value as? [AXUIElement] else { return nil }+ // Prefer the standard window (skip dialogs/panels); fall back to the first window.+ return windows.first { axString($0, kAXSubroleAttribute as CFString) == (kAXStandardWindowSubrole as String) }+ ?? windows.first+ }++ 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 }+ }+ return nil+ }++ /// All visible text under a row (its static texts / value), joined — so we can match by label.+ private static func rowText(_ row: AXUIElement) -> String {+ var parts: [String] = []+ if let v = axString(row, kAXValueAttribute as CFString) { parts.append(v) }+ if let t = axString(row, kAXTitleAttribute as CFString) { parts.append(t) }+ for text in descendants(of: row, role: kAXStaticTextRole as String, limit: 20) {+ if let v = axString(text, kAXValueAttribute as CFString) { parts.append(v) }+ }+ return parts.joined(separator: " ")+ }++ private static func firstDescendant(of element: AXUIElement, role: String, depth: Int = 0) -> AXUIElement? {+ guard depth < 12 else { return nil }+ for child in children(element) {+ if axString(child, kAXRoleAttribute as CFString) == role { return child }+ if let found = firstDescendant(of: child, role: role, depth: depth + 1) { return found }+ }+ return nil+ }++ private static func descendants(of element: AXUIElement, role: String, limit: Int, depth: Int = 0, found: Int = 0) -> [AXUIElement] {+ guard depth < 14, found < limit else { return [] }+ var result: [AXUIElement] = []+ for child in children(element) {+ if axString(child, kAXRoleAttribute as CFString) == role { result.append(child) }+ if result.count + found >= limit { break }+ result.append(contentsOf: descendants(of: child, role: role, limit: limit, depth: depth + 1, found: found + result.count))+ if result.count + found >= limit { break }+ }+ return result+ }++ private static func children(_ element: AXUIElement) -> [AXUIElement] {+ var value: CFTypeRef?+ guard AXUIElementCopyAttributeValue(element, kAXChildrenAttribute as CFString, &value) == .success,+ let kids = value as? [AXUIElement] else { return [] }+ return kids+ }++ private static func elementFrame(_ element: AXUIElement) -> WindowTargetBounds? {+ var posValue: CFTypeRef?+ var sizeValue: CFTypeRef?+ guard AXUIElementCopyAttributeValue(element, kAXPositionAttribute as CFString, &posValue) == .success,+ AXUIElementCopyAttributeValue(element, kAXSizeAttribute as CFString, &sizeValue) == .success,+ let posValue, let sizeValue,+ CFGetTypeID(posValue) == AXValueGetTypeID(), CFGetTypeID(sizeValue) == AXValueGetTypeID()+ else { return nil }+ var point = CGPoint.zero+ var size = CGSize.zero+ AXValueGetValue(posValue as! AXValue, .cgPoint, &point)+ AXValueGetValue(sizeValue as! AXValue, .cgSize, &size)+ guard size.width > 0, size.height > 0 else { return nil }+ return WindowTargetBounds(x: Double(point.x), y: Double(point.y), width: Double(size.width), height: Double(size.height))+ }++ private static func modalButton(in element: AXUIElement, title: String, inModal: Bool, depth: Int) -> AXUIElement? {+ guard depth < 8 else { return nil }+ let role = axString(element, kAXRoleAttribute as CFString)+ let subrole = axString(element, kAXSubroleAttribute as CFString)+ let nowModal = inModal+ || role == (kAXSheetRole as String)+ || subrole == (kAXDialogSubrole as String)+ || subrole == (kAXSystemDialogSubrole as String)+ if nowModal, role == (kAXButtonRole as String), axString(element, kAXTitleAttribute as CFString) == title {+ return element+ }+ for child in children(element) {+ if let found = modalButton(in: child, title: title, inModal: nowModal, depth: depth + 1) { return found }+ }+ return nil+ }++ private static func axString(_ element: AXUIElement, _ attribute: CFString) -> String? {+ var value: CFTypeRef?+ guard AXUIElementCopyAttributeValue(element, attribute, &value) == .success else { return nil }+ if let s = value as? String { return s }+ if let n = value as? NSNumber { return n.stringValue }+ return nil+ }}diff --git a/apps/Donkey/Sources/DonkeyRuntime/MusicPlaybackTools.swift b/apps/Donkey/Sources/DonkeyRuntime/MusicPlaybackTools.swiftindex 89dc8af2..050b9ac0 100644--- a/apps/Donkey/Sources/DonkeyRuntime/MusicPlaybackTools.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/MusicPlaybackTools.swift@@ -99,10 +99,10 @@ public final class MusicPlaybackToolProvider {HarnessToolDescriptor(name: ToolName.playlist,pluginID: "media.music",- summary: "Manage Apple Music library playlists natively: list them, create one, add catalog songs (ids from music.search), or read a playlist's entries. Play one via music.play kind=playlist id=<id>. Removing tracks and deleting playlists are NOT possible (no Apple API) — tell the user instead of attempting it.",+ summary: "Manage Apple Music library playlists through Apple's API: list them, create one, add catalog songs (ids from music.search), or read a playlist's entries. Play one via music.play kind=playlist id=<id>. Deleting a whole playlist has no API — do it in the GUI with ax.select_and_press (label=<playlist name> key=delete confirm=Delete). Removing individual tracks has no Apple API either (tell the user).",inputSchema: ["action": PlaylistAction.schemaList,- "name": "Playlist name (create).",+ "name": "Playlist name (create, delete).","description": "Playlist description (create, optional).","playlistID": "Library playlist id from action=list or create (add, entries).","songIDs": "Comma-separated catalog song ids from music.search (add).",@@ -447,16 +447,28 @@ public final class MusicPlaybackToolProvider {)}guard let action = PlaylistAction(rawValue: rawAction) else {- // remove/delete are real Apple-platform gaps (no API); anything else is a typo.- if rawAction == "remove" || rawAction == "delete" {+ // `music.playlist` covers only the operations Apple exposes through an API. Matching is on the+ // typed action field, never raw user text.+ if rawAction == "remove" {+ // Removing individual tracks has no Apple API and no GUI affordance worth driving.return result(context,status: .failed,- summary: "Removing tracks or deleting playlists is not possible — Apple provides no API for it. "+ summary: "Removing individual tracks is not possible — Apple provides no API for it. "+ "Tell the user to do that in the Music app; do not retry.",reason: "unsupportedByPlatform")}+ if rawAction == "delete" {+ // Deleting a whole playlist has no API — it's a general GUI row action, not a music tool.+ return result(+ context,+ status: .failed,+ summary: "music.playlist has no delete (Apple exposes no playlist-delete API). Delete it in the GUI "+ + "with ax.select_and_press: label=<playlist name>, key=delete, confirm=Delete.",+ reason: "noDeleteAPI"+ )+ }return result(context,status: .invalidInput,diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music/SKILL.mdindex 2192fe0f..f45dafc5 100644--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music/SKILL.md+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music/SKILL.md@@ -1,15 +1,15 @@# Musicid: music-description: Play and control Apple Music natively with the music.* tools — never the Music app GUI, AppleScript, or a web player.+description: Play and control Apple Music natively with the music.* tools — playback never uses the Music app GUI, AppleScript, or a web player. Deleting a playlist is the lone exception: no API exists, so it is done through the GUI with the general see/act tools.tags: media, music, playback, local-appkeywords: play, listen, music, song, track, tune, album, playlist, artist, band, audio, radio, pause, resume, skip, volume, shuffle, repeat, queue, seek, rewindapps: Music, Apple Music, com.apple.Musictools: music.play, music.search, music.transport, music.status, music.playlist, shell_exec, web.search-Use this for any music request: "play baby don't cry", "play top 80s hits", "play the latest album from Taylor Swift", "play something by Coldplay", "pause the music", "skip this", "what's playing?", "make me a workout playlist", "add this song to my mix".+Use this for any music request: playing tracks/albums/artists/genres, transport (pause, skip, what's playing), and the user's own playlists.-Playback is low-risk and reversible: act directly, don't ask for confirmation. Everything goes through the native music tools — never launch, focus, script, or click the Music app, and never open YouTube, Spotify web, Apple Music web, or any browser player. Do not over-explain — the user wants the music to start.+Playback goes entirely through the native music tools — for playback never launch, focus, script, or click the Music app, and never open YouTube, Spotify web, Apple Music web, or any browser player. (Deleting a playlist is the one task that does use the Music GUI — see Playlists.)## Step 1: Pick the tool@@ -33,7 +33,7 @@ Bad queries: `play baby don't cry` · `listen to coldplay` — no command phrase## Step 4: Trust the tool's verification-A successful `music.play` already verified playback — the play position was sampled until it advanced. Report what's playing and `run.complete`; do not re-verify with another tool. A failure summary states the exact cause (permission not granted, no Apple Music subscription, app signing/token problem, item unavailable). Relay that cause plainly, do not retry the same call, and never fall back to driving the Music app's GUI.+A successful `music.play` already verified playback — position was sampled until it advanced; report what's playing and `run.complete` without re-verifying. A failure summary names the exact cause (permission, no subscription, signing/token, item unavailable) — relay it plainly.## Transport, volume, now playing@@ -52,15 +52,12 @@ A successful `music.play` already verified playback — the play position was sa- "add this song to X" → the currently playing song's id is in the world model facts (`music.playing.id`) when this run started it; otherwise `music.search` for it. Then action=add.- "what's in X" → action=entries.- A successful create/add is confirmed by the Apple Music API — that is the evidence; report it and complete. Use action=entries only when the user asks what's inside.-- Removing tracks, deleting playlists, and renaming are NOT possible — Apple provides no API. Say so plainly and point the user to the Music app; never claim success and never fall back to the GUI.--## Ambiguity--Pick the best likely match for ordinary ambiguity: "play hello" → the most popular likely match; "play drake" → a popular Drake result; "play 80s music" → `kind=playlist` or `kind=station`. Ask only when the user explicitly wants to choose between versions, when interpretations are equally likely AND very different, or when the request isn't actually about music. Keep it short: "Which one did you mean: Adele, Lionel Richie, or another artist?"+- Removing individual tracks and renaming have no Apple API and no GUI path worth driving — say so plainly, point the user to the Music app, don't fake success.+- Deleting a WHOLE playlist has no API (no MusicKit delete; AppleScript `delete playlist` errors -1708), so do it in the GUI with the general row tool, in one call: `ax.select_and_press` with `label=<playlist name>`, `key=delete`, `confirm=Delete`. That selects the sidebar row, presses Delete, and confirms the dialog atomically; then `ax.observe` to verify the row is gone. The sidebar is the source of truth, not `music.playlist action=list` (the MusicKit list can lag). If the row isn't found, the playlist was just created and hasn't synced from iCloud yet — `wait` briefly and retry.## Failure behavior-Never fail silently; never say playback started unless the tool verified it; never retry the same query repeatedly; never open a web player; never drive the Music app GUI. The tool's failure summary names the exact blocker — pass it on, e.g. "I couldn't start playback: this Mac's Apple ID has no active Apple Music subscription."+Never open a web player; never drive the Music GUI for playback (deleting a playlist is the lone sanctioned GUI use). The tool's failure summary names the exact blocker — pass it on, e.g. "I couldn't start playback: this Mac's Apple ID has no active Apple Music subscription."## Response stylediff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaybackToolsTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaybackToolsTests.swiftindex d18cf6b4..7b5924aa 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaybackToolsTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MusicPlaybackToolsTests.swift@@ -437,8 +437,8 @@ struct MusicPlaybackToolsTests {@Testfunc playlistRemoveIsHonestlyUnsupported() async {- // Apple ships no API for removing tracks or deleting playlists. The tool must say so- // plainly instead of failing generically or pretending.+ // Apple ships no API for removing individual tracks. The tool must say so plainly and send the+ // user to the Music app instead of failing generically or pretending.let provider = MusicPlaybackToolProvider(service: FakeMusicService())let result = await run(@@ -452,6 +452,24 @@ struct MusicPlaybackToolsTests {#expect(result.summary.contains("no API"))}+ @Test+ func playlistDeleteHasNoAPIAndPointsToTheGeneralRowTool() async {+ // Deleting a whole playlist has no Apple API. It is a general GUI row action, not a music tool —+ // `music.playlist` rejects `delete` and points the planner at the app-agnostic `ax.select_and_press`+ // (select the sidebar row + Delete key + confirm dialog), so there is no bespoke per-app delete here.+ let provider = MusicPlaybackToolProvider(service: FakeMusicService())++ let result = await run(+ provider,+ tool: MusicPlaybackToolProvider.ToolName.playlist,+ input: ["action": "delete", "name": "My Mix"]+ )++ #expect(result.status == .failed)+ #expect(result.metadata["reason"] == "noDeleteAPI")+ #expect(result.summary.contains("ax.select_and_press"))+ }+@Testfunc playlistEntriesListsTitlesAndArtists() async {let service = FakeMusicService()