Skip to content

Open source CapCut alternative.

TypeScript

feat(app): route by action surface and retarget the app from observation

David Le95e9a9892f2f
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 68c6d978..fdfd45bd 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -453,11 +453,10 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
) async -> UserQueryCommandHandlingResult {
// A resume pins the task's original target, so it can drive that app even when it (or nothing) is
// frontmost — which is the common case right after a relaunch. Resolve the frontmost app up front
- // (no guard yet): its name feeds the understanding prompt, and a conversational turn needs no app
- // at all — only the action path below requires one.
+ // (no guard yet): its name feeds the understanding prompt, and neither a conversational turn nor an
+ // app-less action turn needs an app at all — only a GUI-driving turn below does.
let frontmost = MacWindowResolver().frontmostUserAppTarget()
let frontmostAppName = frontmost?.appName ?? forcedDriveTarget?.appName ?? "the frontmost app"
- let frontmostBundleIdentifier = frontmost?.bundleIdentifier ?? forcedDriveTarget?.bundleIdentifier
// The backend is needed by BOTH paths — the conversational responder and the action loop — so it
// is built before the turn is classified.
@@ -549,27 +548,34 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
)
}
- // ACTION PATH from here down. These guards are action-only — a conversational turn already
- // returned above, so it never needs input permission or a frontmost app window to drive.
- guard permissionPolicy.allowedCapabilities.contains(.input) else {
- return await failHarnessRun(
- command: command,
- response: "Vision navigation needs input permission, which isn't granted.",
- reason: "inputNotPermitted",
- appName: frontmostAppName,
- traceID: traceID,
- conversationID: conversationID,
- agentID: agentID,
- preparedTurnMetadata: preparedTurnMetadata,
- transcript: transcript
+ // ACTION PATH from here down — a conversational turn already returned above. Resolve which app, if
+ // any, this turn drives: a resume pins its original target; otherwise the understanding boundary's
+ // typed surface decides. An `.appless` turn (artifact/system work — make an image, fetch the web,
+ // change a setting) and a turn with nothing in front both resolve to nil and run APP-LESS: the
+ // planner works through shell/web/file/generative tools with no app to focus and no pointer to move,
+ // so the run is never blocked on a missing frontmost window the way a GUI task would be.
+ let driveTarget: (appName: String, bundleIdentifier: String?)?
+ if let forcedDriveTarget {
+ driveTarget = forcedDriveTarget
+ } else {
+ // A frontmost candidate with no resolvable name is no drive target — same as nothing in front.
+ let frontmostTarget: (appName: String, bundleIdentifier: String?)? = frontmost.flatMap { candidate in
+ candidate.appName.map { (appName: $0, bundleIdentifier: candidate.bundleIdentifier) }
+ }
+ driveTarget = Self.resolveDriveTarget(
+ understanding: understanding,
+ frontmost: frontmostTarget
)
}
- // A fresh turn with no frontmost app and no pinned target has nothing to drive, so it fails cleanly.
- guard forcedDriveTarget != nil || frontmost != nil else {
+
+ // Input permission gates a GUI-driving run only: that path clicks and types. An app-less run moves
+ // no pointer and presses no keys, so it proceeds without the grant. Gated on the typed surface
+ // (driveTarget == nil), never the user's words.
+ if driveTarget != nil, !permissionPolicy.allowedCapabilities.contains(.input) {
return await failHarnessRun(
command: command,
- response: "I couldn't find a frontmost app window to navigate. Focus the app you want, then type your request.",
- reason: "noFrontmostApp",
+ response: "Vision navigation needs input permission, which isn't granted.",
+ reason: "inputNotPermitted",
appName: frontmostAppName,
traceID: traceID,
conversationID: conversationID,
@@ -582,32 +588,24 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
progress?(restated)
}
- // Drive the understood target app whenever it names a running or installed app; else the
- // frontmost app. An installed-but-not-running target stays pinned by name — the see/act tools
- // re-resolve its window each call, so it works as soon as the planner launches it. A resume pins
- // the task's original target so the work continues against the right app, not whatever is in front.
- let driveTarget: (appName: String, bundleIdentifier: String?)
- if let forcedDriveTarget {
- driveTarget = (forcedDriveTarget.appName, forcedDriveTarget.bundleIdentifier)
- } else {
- driveTarget = Self.resolveDriveTarget(
- understanding: understanding,
- frontmostAppName: frontmostAppName,
- frontmostBundleIdentifier: frontmostBundleIdentifier
- )
- }
- let appName = driveTarget.appName
- let bundleIdentifier = driveTarget.bundleIdentifier
+ // An app-less run carries an empty app name and no bundle id; the see/act providers below resolve
+ // no window and the planner reaches for app-less tools instead.
+ let appName = driveTarget?.appName ?? ""
+ let bundleIdentifier = driveTarget?.bundleIdentifier
// Pin the resolved target on the task so a later resume drives the same app (see forcedDriveTarget).
+ // An app-less run records an empty name, so a resume re-derives the surface and stays app-less.
await genericHarnessLifecycle.coordinator.recordMetadata(agentID: agentID, [
Self.driveTargetAppMetadataKey: appName,
Self.driveTargetBundleMetadataKey: bundleIdentifier ?? ""
])
- let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(
- forApp: appName,
- bundleIdentifier: bundleIdentifier
- )
+ // App guidance is the drive app's own playbook; an app-less run has no app, so it loads none.
+ let appGuidance = driveTarget != nil
+ ? BuiltInLocalAppSkillPacks.appOperatingGuidance(
+ forApp: appName,
+ bundleIdentifier: bundleIdentifier
+ )
+ : nil
// Preload the full guides for the capability skills the understanding boundary picked for this task
// (`relevantSkillIDs`) — the same "preload the right playbook" treatment app skills get via
@@ -615,10 +613,12 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
// depending on the planner to discover and load it. Skip the drive-target app's own skill (already
// in appGuidance) and cap the count so the prompt stays bounded; anything else stays loadable from
// the catalog via skill.load.
- let appSkillID = BuiltInLocalAppSkillPacks.appSkillDescriptor(
- forApp: appName,
- bundleIdentifier: bundleIdentifier
- )?.id.lowercased()
+ let appSkillID = driveTarget != nil
+ ? BuiltInLocalAppSkillPacks.appSkillDescriptor(
+ forApp: appName,
+ bundleIdentifier: bundleIdentifier
+ )?.id.lowercased()
+ : nil
let preloadedSkillGuides: [String] = (understanding?.relevantSkillIDs ?? [])
.filter { $0.lowercased() != appSkillID }
.prefix(2)
@@ -631,7 +631,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
// vision is just one tool among many. The always-on warm-cache monitor is suspended for the
// duration so it never races us on a parse.
let analyzer = HostedDebugUIInspectionAnalyzer(backend: backend)
- let appKey = (bundleIdentifier?.isEmpty == false ? bundleIdentifier! : appName)
// Built-in action/lifecycle/skill tools, minus the placeholder see/act tools that the real AX +
// vision tools below replace, and restricted to what this turn is permitted to run.
@@ -697,21 +696,22 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
// An unattended auto-resume forces background so it never raises an app or moves the cursor while
// the user is away; an interactive turn lets the understanding boundary decide.
let executionPreference = forcedExecutionPreference ?? understanding?.executionPreference ?? .background
+ // One shared, mutable target the three see/act providers read per call: an observe/capture step
+ // that names an `app:` retargets it, and every later act/scroll/keystroke follows to that app.
+ // Seeded with the run's resolved app — empty on an app-less run, which acquires its first app the
+ // moment the planner observes one by name. This is what unbinds the run from a single pinned app.
+ let targetContext = HarnessTargetContext(appName: appName, bundleIdentifier: bundleIdentifier)
let axProvider = AXComputerUseToolProvider(
- appName: appName,
- bundleIdentifier: bundleIdentifier,
+ target: targetContext,
executionPreference: executionPreference
)
let visionProvider = VisionComputerUseToolProvider(
- appName: appName,
- appKey: appKey,
- bundleIdentifier: bundleIdentifier,
+ target: targetContext,
executionPreference: executionPreference,
analyzer: analyzer
)
let pointerProvider = PointerComputerUseToolProvider(
- appName: appName,
- bundleIdentifier: bundleIdentifier,
+ target: targetContext,
executionPreference: executionPreference
)
// Native music playback (MusicKit): search/play/transport/status with no Music-app GUI or
@@ -1457,18 +1457,20 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
])
}
- /// Picks the app the harness drive operates. The understood target app wins whenever it names a
- /// real app: a running window resolves to its exact name and bundle id, and an installed-but-not-
- /// running app is still pinned by name — the see/act providers re-resolve the target window on
- /// every call, so the target starts working the moment the planner launches it. Pinning to the
- /// frontmost app instead aims every observe/click (and the focus guard's recovery activation) at
- /// an unrelated window for the whole run, and preloads the wrong app's guidance. Only a name that
- /// matches nothing running and nothing installed falls back to the frontmost app.
+ /// Picks the app the harness drive operates, or nil for an app-less run. An `.appless` turn (the
+ /// understanding boundary's typed signal for artifact/system work — make an image, fetch the web,
+ /// change a setting) drives no app at all and returns nil, so it is never pinned to a window and never
+ /// blocked on one. Otherwise the understood target app wins whenever it names a real app: a running
+ /// window resolves to its exact name and bundle id, and an installed-but-not-running app is still
+ /// pinned by name — the see/act providers re-resolve the target window on every call, so the target
+ /// starts working the moment the planner launches it. Pinning to the frontmost app instead aims every
+ /// observe/click (and the focus guard's recovery activation) at an unrelated window for the whole run,
+ /// and preloads the wrong app's guidance. A name that matches nothing running and nothing installed
+ /// falls back to the frontmost app, and with no frontmost app the run is app-less rather than failed.
@MainActor
static func resolveDriveTarget(
understanding: HarnessRequestUnderstanding?,
- frontmostAppName: String,
- frontmostBundleIdentifier: String?,
+ frontmost: (appName: String, bundleIdentifier: String?)?,
resolveRunningWindow: (String) -> (appName: String?, bundleIdentifier: String?)? = { requested in
AccessibilityObserver.resolveTarget(appName: requested, bundleIdentifier: nil)
.map { ($0.appName, $0.bundleIdentifier) }
@@ -1476,12 +1478,15 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
resolveInstalledBundle: (String) -> URL? = { requested in
MacAppScriptabilityProbe().bundleURL(bundleIdentifier: nil, appName: requested)
}
- ) -> (appName: String, bundleIdentifier: String?) {
+ ) -> (appName: String, bundleIdentifier: String?)? {
+ // An app-less turn drives nothing — the planner produces the result with system/web/generative tools.
+ if understanding?.actionSurface == .appless { return nil }
guard let requested = understanding?.targetAppName,
!requested.isEmpty,
- requested.caseInsensitiveCompare(frontmostAppName) != .orderedSame
+ requested.caseInsensitiveCompare(frontmost?.appName ?? "") != .orderedSame
else {
- return (frontmostAppName, frontmostBundleIdentifier)
+ // No named target (or it IS the front app): drive the front app, or run app-less when none.
+ return frontmost
}
if let resolved = resolveRunningWindow(requested) {
return (resolved.appName ?? requested, resolved.bundleIdentifier)
@@ -1489,7 +1494,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
if let bundleURL = resolveInstalledBundle(requested) {
return (requested, Bundle(url: bundleURL)?.bundleIdentifier)
}
- return (frontmostAppName, frontmostBundleIdentifier)
+ return frontmost
}
/// A compact, one-line-per-skill catalog of every installed app skill — id, description, the apps it
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift
index afec0b12..9d99f394 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift
@@ -22,6 +22,11 @@ public struct HarnessRequestUnderstanding: Sendable, Equatable {
/// system tools (finding files, launching/quitting apps, reading or changing settings/state) —
/// those have no GUI target and the planner drives them with shell_exec.
public var targetAppName: String?
+ /// Whether this turn drives a GUI app or is produced app-less through system/web/generative tools.
+ /// Disambiguates an empty `targetAppName` — "operate the front app" vs "no app at all" — so the caller
+ /// can run an artifact/system task (generate an image, fetch the web, change a setting) without pinning
+ /// it to a window or demanding one be frontmost. Set by the model; defaults to `.guiApp`.
+ public var actionSurface: HarnessActionSurface
/// Structured parameters extracted from the request (e.g. title, recipient, query).
public var parameters: [String: String]
/// What, observable on screen, would mean the goal is done.
@@ -52,6 +57,7 @@ public struct HarnessRequestUnderstanding: Sendable, Equatable {
turnKind: HarnessTurnKind = .act,
restatedGoal: String,
targetAppName: String? = nil,
+ actionSurface: HarnessActionSurface = .guiApp,
parameters: [String: String] = [:],
successCriteria: String? = nil,
needsClarification: Bool = false,
@@ -63,6 +69,7 @@ public struct HarnessRequestUnderstanding: Sendable, Equatable {
self.turnKind = turnKind
self.restatedGoal = restatedGoal
self.targetAppName = targetAppName
+ self.actionSurface = actionSurface
self.parameters = parameters
self.successCriteria = successCriteria
self.needsClarification = needsClarification
@@ -216,6 +223,7 @@ public final class HostedHarnessRequestUnderstanding {
turnKind: wire.turnKind.flatMap { HarnessTurnKind(rawValue: $0) } ?? .act,
restatedGoal: restated,
targetAppName: wire.targetAppName.flatMap { $0.isEmpty ? nil : $0 },
+ actionSurface: wire.actionSurface.flatMap { HarnessActionSurface(rawValue: $0) } ?? .guiApp,
parameters: wire.parameters ?? [:],
successCriteria: wire.successCriteria.flatMap { $0.isEmpty ? nil : $0 },
needsClarification: wire.needsClarification ?? false,
@@ -256,6 +264,7 @@ public final class HostedHarnessRequestUnderstanding {
var turnKind: String?
var restatedGoal: String?
var targetAppName: String?
+ var actionSurface: String?
var parameters: [String: String]?
var successCriteria: String?
var needsClarification: Bool?
@@ -265,7 +274,7 @@ public final class HostedHarnessRequestUnderstanding {
var conversationReply: String?
private enum CodingKeys: String, CodingKey {
- case turnKind, restatedGoal, targetAppName, parameters, successCriteria, needsClarification, clarifyingQuestion
+ case turnKind, restatedGoal, targetAppName, actionSurface, parameters, successCriteria, needsClarification, clarifyingQuestion
case executionPreference, relevantSkillIDs, conversationReply
}
@@ -274,6 +283,7 @@ public final class HostedHarnessRequestUnderstanding {
turnKind = try container.decodeIfPresent(String.self, forKey: .turnKind)
restatedGoal = try container.decodeIfPresent(String.self, forKey: .restatedGoal)
targetAppName = try container.decodeIfPresent(String.self, forKey: .targetAppName)
+ actionSurface = try container.decodeIfPresent(String.self, forKey: .actionSurface)
successCriteria = try container.decodeIfPresent(String.self, forKey: .successCriteria)
clarifyingQuestion = try container.decodeIfPresent(String.self, forKey: .clarifyingQuestion)
needsClarification = try container.decodeIfPresent(Bool.self, forKey: .needsClarification)
@@ -350,6 +360,10 @@ public final class HostedHarnessRequestUnderstanding {
]),
"restatedGoal": .object(["type": .string("string")]),
"targetAppName": .object(["type": .string("string")]),
+ "actionSurface": .object([
+ "type": .string("string"),
+ "enum": .array([.string("guiApp"), .string("appless")])
+ ]),
"parameters": .object([
"type": .string("object"),
"additionalProperties": .object(["type": .string("string")])
diff --git a/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift
index bdaaa654..5acb655b 100644
--- a/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift
+++ b/apps/Donkey/Sources/DonkeyAI/PointerComputerUseTools.swift
@@ -20,17 +20,19 @@ public final class PointerComputerUseToolProvider {
public static let drag = "mouse.drag"
}
- private let appName: String
- private let bundleIdentifier: String?
+ /// The app this run is currently driving — shared with the AX/vision providers and mutable when an
+ /// observe step retargets it. Read per call so a scroll/drag follows to the app the planner last
+ /// observed; the pointer tools never retarget themselves (they act on whatever was just observed).
+ private let target: HarnessTargetContext
+ private var appName: String { target.appName }
+ private var bundleIdentifier: String? { target.bundleIdentifier }
private let executionPreference: ExecutionPreference
public init(
- appName: String,
- bundleIdentifier: String?,
+ target: HarnessTargetContext,
executionPreference: ExecutionPreference = .foreground
) {
- self.appName = appName
- self.bundleIdentifier = bundleIdentifier
+ self.target = target
self.executionPreference = executionPreference
}
diff --git a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift
index 0aa5891e..653706f8 100644
--- a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift
+++ b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift
@@ -36,9 +36,13 @@ public final class VisionComputerUseToolProvider {
public var elementCount: Int
}
- let appName: String
- let appKey: String
- let bundleIdentifier: String?
+ /// The app this run is currently driving — shared with the AX/pointer providers and mutable when an
+ /// observe step retargets it. Read per call (via the computed accessors) so capture/click/keystroke
+ /// always resolve against the app the planner last looked at, not one pinned for the whole run.
+ let target: HarnessTargetContext
+ var appName: String { target.appName }
+ var appKey: String { target.appKey }
+ var bundleIdentifier: String? { target.bundleIdentifier }
let executionPreference: ExecutionPreference
let analyzer: any DebugUIInspectionAnalyzing
let store: ParsedVisionStore
@@ -61,9 +65,7 @@ public final class VisionComputerUseToolProvider {
public private(set) var lastCaptureMetrics: CaptureMetrics?
public init(
- appName: String,
- appKey: String,
- bundleIdentifier: String?,
+ target: HarnessTargetContext,
executionPreference: ExecutionPreference = .foreground,
analyzer: any DebugUIInspectionAnalyzing,
store: ParsedVisionStore = .shared,
@@ -74,9 +76,7 @@ public final class VisionComputerUseToolProvider {
desktopCapture: @escaping DesktopCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().captureDesktop() },
uptimeMS: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime * 1_000 }
) {
- self.appName = appName
- self.appKey = appKey
- self.bundleIdentifier = bundleIdentifier
+ self.target = target
self.executionPreference = executionPreference
self.analyzer = analyzer
self.store = store
@@ -93,9 +93,12 @@ 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 frontmost 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. 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."],
- optionalInputKeys: ["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. 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."
+ ],
+ optionalInputKeys: ["scope", "app"],
outputSchema: ["elements": "Detected element IDs, labels, roles, and click eligibility."],
requiredPermissions: [.screenCapture],
safetyClass: .readOnly,
@@ -163,6 +166,14 @@ public final class VisionComputerUseToolProvider {
// MARK: - Capture + analyze
private func captureAndAnalyze(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {
+ // 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)
+ }
+ 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")
}
@@ -606,6 +617,16 @@ 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) {
+ if let resolved = AccessibilityObserver.resolveTarget(appName: requestedApp, bundleIdentifier: nil) {
+ target.retarget(appName: resolved.appName ?? requestedApp, bundleIdentifier: resolved.bundleIdentifier)
+ } else {
+ target.retarget(appName: requestedApp, bundleIdentifier: nil)
+ }
+ }
+
private func trimmed(_ value: String?) -> String? {
guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {
return nil
diff --git a/apps/Donkey/Sources/DonkeyContracts/HarnessActionSurface.swift b/apps/Donkey/Sources/DonkeyContracts/HarnessActionSurface.swift
new file mode 100644
index 00000000..ebf99048
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyContracts/HarnessActionSurface.swift
@@ -0,0 +1,20 @@
+import Foundation
+
+/// Whether an actionable turn drives a macOS app's GUI, or is produced entirely through system, web, and
+/// generative tools with no app at all.
+///
+/// Like ``HarnessTurnKind`` and ``ExecutionPreference``, this is a typed field the request-understanding
+/// boundary sets — never inferred by matching the user's words. It exists because an empty
+/// ``HarnessRequestUnderstanding/targetAppName`` is ambiguous on its own: it can mean "operate whatever app
+/// is already in front" or "no app is involved at all" (generate an image, fetch the web, read or change a
+/// setting, write a file). Deterministic code reads this enum to decide whether the run pins an app and
+/// requires input permission, or runs app-less — so an artifact task is never blocked on a missing frontmost
+/// window, and an app-less task is never pinned to whatever app happened to be in front.
+public enum HarnessActionSurface: String, Codable, Equatable, Sendable {
+ /// The work operates a macOS app through its GUI — a specific named app, or the one already in front.
+ /// The run pins that app, requires input permission, and drives it with the AX/vision/pointer tools.
+ case guiApp
+ /// The work needs no GUI app. The planner produces it with system, web, file, and generative tools
+ /// (`shell_exec`, `web.*`, `files.*`, `image.generate`) — no app to focus, no pointer to move.
+ case appless
+}
diff --git a/apps/Donkey/Sources/DonkeyContracts/HarnessTargetContext.swift b/apps/Donkey/Sources/DonkeyContracts/HarnessTargetContext.swift
new file mode 100644
index 00000000..4a140ffb
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyContracts/HarnessTargetContext.swift
@@ -0,0 +1,46 @@
+import Foundation
+
+/// The app a computer-use run is currently driving — shared, and mutable mid-run.
+///
+/// A run is no longer bound to one app for its whole life. The see/act providers (AX, vision, pointer)
+/// all hold ONE of these and read it at call time, so when an observe step retargets it (the planner
+/// passed `app:` to look at a different app), every later act/scroll/keystroke follows to the new app.
+/// That is the structural form of "the model routes per step, like computer use": observation picks the
+/// app, and because the planner always observes the surface it is about to act on, the current target is
+/// the right one by construction.
+///
+/// A reference type so the three providers share a single instance; `@MainActor` because every read and
+/// retarget happens on the main actor, where the providers and window resolution already live.
+@MainActor
+public final class HarnessTargetContext {
+ /// The current target app's display name. Empty means no app is targeted yet — an app-less run that
+ /// has not acquired one. The planner acquires an app by passing `app:` to an observe/capture tool.
+ public private(set) var appName: String
+ /// 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?
+
+ public init(appName: String, bundleIdentifier: String?) {
+ self.appName = appName
+ self.bundleIdentifier = bundleIdentifier
+ }
+
+ /// A stable per-app cache key (bundle id when present, else the name), used by the vision parse store.
+ public var appKey: String {
+ if let bundleIdentifier, !bundleIdentifier.isEmpty { return bundleIdentifier }
+ return appName
+ }
+
+ /// True when no app is targeted — an app-less run before it has acquired one. Observe/capture report
+ /// this cleanly instead of resolving an empty name.
+ public var isEmpty: Bool {
+ 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?) {
+ self.appName = appName
+ self.bundleIdentifier = bundleIdentifier
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift
index 8e56264e..1702926f 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/AXComputerUseTools.swift
@@ -19,19 +19,21 @@ public final class AXComputerUseToolProvider {
public static let selectAndPress = "ax.select_and_press"
}
- private let appName: String
- private let bundleIdentifier: String?
+ /// 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.
+ private let target: HarnessTargetContext
+ private var appName: String { target.appName }
+ private var bundleIdentifier: String? { target.bundleIdentifier }
private let executionPreference: ExecutionPreference
private let actionBackend: ActionEngineInputBackend
public init(
- appName: String,
- bundleIdentifier: String?,
+ target: HarnessTargetContext,
executionPreference: ExecutionPreference = .foreground,
actionBackend: ActionEngineInputBackend = MacAccessibilityActionEngineInputBackend()
) {
- self.appName = appName
- self.bundleIdentifier = bundleIdentifier
+ self.target = target
self.executionPreference = executionPreference
self.actionBackend = actionBackend
}
@@ -58,7 +60,9 @@ public final class AXComputerUseToolProvider {
HarnessToolDescriptor(
name: ToolName.observe,
pluginID: "core.computer-use.ax",
- summary: "Read the frontmost app's Accessibility tree and return its actionable controls. Fast and structured; prefer this for native apps.",
+ 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"],
outputSchema: ["elements": "Accessibility control IDs, labels, roles, and click eligibility."],
requiredPermissions: [.accessibility],
safetyClass: .readOnly,
@@ -117,6 +121,14 @@ 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.
+ if let requested = trimmed(context.call.input["app"]) {
+ retarget(to: requested)
+ }
+ 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")
}
@@ -376,6 +388,17 @@ public final class AXComputerUseToolProvider {
// MARK: - Helpers
+ /// 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) {
+ if let resolved = AccessibilityObserver.resolveTarget(appName: requestedApp, bundleIdentifier: nil) {
+ target.retarget(appName: resolved.appName ?? requestedApp, bundleIdentifier: resolved.bundleIdentifier)
+ } else {
+ target.retarget(appName: requestedApp, bundleIdentifier: nil)
+ }
+ }
+
private func trimmed(_ value: String?) -> String? {
guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { return nil }
return value
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ComputerUseRetargetingTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ComputerUseRetargetingTests.swift
new file mode 100644
index 00000000..0b5fdb57
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ComputerUseRetargetingTests.swift
@@ -0,0 +1,62 @@
+import DonkeyAI
+import DonkeyContracts
+import DonkeyHarness
+import DonkeyRuntime
+import Foundation
+import Testing
+
+/// Locks the structural unbinding of a computer-use run from a single pinned app: the run carries one
+/// shared, mutable `HarnessTargetContext`, and the see-tools advertise an `app` input so the planner can
+/// retarget per step (observe X → act on X; observe Y → act on Y), the way computer use does.
+@Suite
+@MainActor
+struct ComputerUseRetargetingTests {
+ @Test
+ func targetContextSeedsAndRetargets() {
+ let target = HarnessTargetContext(appName: "Music", bundleIdentifier: "com.apple.Music")
+ #expect(!target.isEmpty)
+ #expect(target.appName == "Music")
+ #expect(target.appKey == "com.apple.Music")
+
+ // An observe step naming a different app retargets the run; later actions read the new identity.
+ target.retarget(appName: "Preview", bundleIdentifier: "com.apple.Preview")
+ #expect(target.appName == "Preview")
+ #expect(target.bundleIdentifier == "com.apple.Preview")
+ #expect(target.appKey == "com.apple.Preview")
+ }
+
+ @Test
+ func anAppLessRunStartsEmptyAndAcquiresAnApp() {
+ // An app-less run (artifact/system work) seeds an empty target — there is no app to drive yet.
+ let target = HarnessTargetContext(appName: "", bundleIdentifier: nil)
+ #expect(target.isEmpty)
+ // The cache key degrades to the (empty) name rather than crashing on a nil bundle.
+ #expect(target.appKey == "")
+
+ // It acquires its first app the moment the planner observes one by name.
+ target.retarget(appName: "Numbers", bundleIdentifier: nil)
+ #expect(!target.isEmpty)
+ #expect(target.appKey == "Numbers")
+ }
+
+ @Test
+ func appKeyPrefersBundleButFallsBackToName() {
+ #expect(HarnessTargetContext(appName: "Notes", bundleIdentifier: nil).appKey == "Notes")
+ #expect(HarnessTargetContext(appName: "Notes", bundleIdentifier: "").appKey == "Notes")
+ #expect(HarnessTargetContext(appName: "Notes", bundleIdentifier: "com.apple.Notes").appKey == "com.apple.Notes")
+ }
+
+ @Test
+ func observeToolsAdvertiseTheAppRetargetInput() {
+ // The planner-facing contract that makes retargeting reachable: both see-tools accept `app`. Without
+ // this on the descriptor, the model could never name an app to switch to and the run would stay
+ // pinned to whatever it started on.
+ let axObserve = AXComputerUseToolProvider.descriptors.first { $0.name == "ax.observe" }
+ #expect(axObserve?.optionalInputKeys.contains("app") == true)
+ #expect(axObserve?.inputSchema["app"] != nil)
+
+ let visionCapture = VisionComputerUseToolProvider.descriptors.first { $0.name == "vision.capture" }
+ #expect(visionCapture?.optionalInputKeys.contains("app") == true)
+ #expect(visionCapture?.inputSchema["app"] != nil)
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift
index 9c47dcfc..e34e5ab3 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessRequestUnderstandingTests.swift
@@ -50,6 +50,28 @@ struct HostedHarnessRequestUnderstandingTests {
"""#)
#expect(result?.turnKind == .act)
}
+
+ @Test
+ func decodesAnApplessActionSurface() async {
+ // "show the fifa standings in a nice image": an artifact task the planner produces with
+ // generative/web tools. The decoded `.appless` surface is what lets the caller run it without an
+ // app and without demanding a frontmost window.
+ let result = await understanding(forResponseJSON: #"""
+ {"turnKind":"act","restatedGoal":"Generate an image of the FIFA standings.","targetAppName":"","actionSurface":"appless","needsClarification":false}
+ """#)
+ #expect(result?.turnKind == .act)
+ #expect(result?.actionSurface == .appless)
+ }
+
+ @Test
+ func aMissingActionSurfaceDefaultsToGuiApp() async {
+ // An older model or partial output omits the field; the conservative default is the GUI path, so a
+ // turn that really does drive an app is never accidentally treated as app-less.
+ let result = await understanding(forResponseJSON: #"""
+ {"turnKind":"act","restatedGoal":"Make every slide title bold.","targetAppName":"Keynote","needsClarification":false}
+ """#)
+ #expect(result?.actionSurface == .guiApp)
+ }
}
private final class SingleResponseHTTPClient: AIHTTPClient, @unchecked Sendable {
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ResolveDriveTargetTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ResolveDriveTargetTests.swift
index ad5db6e5..80c0dee7 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/ResolveDriveTargetTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ResolveDriveTargetTests.swift
@@ -1,4 +1,5 @@
import DonkeyAI
+import DonkeyContracts
import Foundation
import Testing
@testable import Donkey
@@ -10,14 +11,13 @@ struct ResolveDriveTargetTests {
func runningUnderstoodTargetWinsWithItsResolvedIdentity() {
let target = LocalAppUserQueryCommandHandler.resolveDriveTarget(
understanding: HarnessRequestUnderstanding(restatedGoal: "Play music", targetAppName: "Music"),
- frontmostAppName: "iTerm2",
- frontmostBundleIdentifier: "com.googlecode.iterm2",
+ frontmost: ("iTerm2", "com.googlecode.iterm2"),
resolveRunningWindow: { _ in (appName: "Music", bundleIdentifier: "com.apple.Music") },
resolveInstalledBundle: { _ in nil }
)
- #expect(target.appName == "Music")
- #expect(target.bundleIdentifier == "com.apple.Music")
+ #expect(target?.appName == "Music")
+ #expect(target?.bundleIdentifier == "com.apple.Music")
}
@Test
@@ -27,14 +27,13 @@ struct ResolveDriveTargetTests {
// aimed at the wrong app. An installed target must stay pinned even with no window yet.
let target = LocalAppUserQueryCommandHandler.resolveDriveTarget(
understanding: HarnessRequestUnderstanding(restatedGoal: "Play music", targetAppName: "Music"),
- frontmostAppName: "iTerm2",
- frontmostBundleIdentifier: "com.googlecode.iterm2",
+ frontmost: ("iTerm2", "com.googlecode.iterm2"),
resolveRunningWindow: { _ in nil },
resolveInstalledBundle: { _ in URL(fileURLWithPath: "/System/Applications/Music.app") }
)
- #expect(target.appName == "Music")
- #expect(target.bundleIdentifier == "com.apple.Music")
+ #expect(target?.appName == "Music")
+ #expect(target?.bundleIdentifier == "com.apple.Music")
}
@Test
@@ -43,41 +42,70 @@ struct ResolveDriveTargetTests {
// must not pin the run to a window that can never resolve.
let target = LocalAppUserQueryCommandHandler.resolveDriveTarget(
understanding: HarnessRequestUnderstanding(restatedGoal: "Do a thing", targetAppName: "Nonexistent App"),
- frontmostAppName: "iTerm2",
- frontmostBundleIdentifier: "com.googlecode.iterm2",
+ frontmost: ("iTerm2", "com.googlecode.iterm2"),
resolveRunningWindow: { _ in nil },
resolveInstalledBundle: { _ in nil }
)
- #expect(target.appName == "iTerm2")
- #expect(target.bundleIdentifier == "com.googlecode.iterm2")
+ #expect(target?.appName == "iTerm2")
+ #expect(target?.bundleIdentifier == "com.googlecode.iterm2")
}
@Test
func noNamedTargetKeepsFrontmost() {
let target = LocalAppUserQueryCommandHandler.resolveDriveTarget(
understanding: HarnessRequestUnderstanding(restatedGoal: "Check battery", targetAppName: nil),
- frontmostAppName: "iTerm2",
- frontmostBundleIdentifier: "com.googlecode.iterm2",
+ frontmost: ("iTerm2", "com.googlecode.iterm2"),
resolveRunningWindow: { _ in nil },
resolveInstalledBundle: { _ in nil }
)
- #expect(target.appName == "iTerm2")
- #expect(target.bundleIdentifier == "com.googlecode.iterm2")
+ #expect(target?.appName == "iTerm2")
+ #expect(target?.bundleIdentifier == "com.googlecode.iterm2")
}
@Test
func targetMatchingFrontmostKeepsFrontmostIdentity() {
let target = LocalAppUserQueryCommandHandler.resolveDriveTarget(
understanding: HarnessRequestUnderstanding(restatedGoal: "Type here", targetAppName: "iterm2"),
- frontmostAppName: "iTerm2",
- frontmostBundleIdentifier: "com.googlecode.iterm2",
+ frontmost: ("iTerm2", "com.googlecode.iterm2"),
resolveRunningWindow: { _ in nil },
resolveInstalledBundle: { _ in nil }
)
- #expect(target.appName == "iTerm2")
- #expect(target.bundleIdentifier == "com.googlecode.iterm2")
+ #expect(target?.appName == "iTerm2")
+ #expect(target?.bundleIdentifier == "com.googlecode.iterm2")
+ }
+
+ @Test
+ func applessSurfaceDrivesNoAppEvenWithFrontmost() {
+ // The "show the fifa standings in a nice image" failure: an artifact task is produced with
+ // generative/web tools, not by driving an app. It must NOT pin whatever happens to be in front —
+ // the typed `.appless` surface resolves to no drive target regardless of the frontmost app.
+ let target = LocalAppUserQueryCommandHandler.resolveDriveTarget(
+ understanding: HarnessRequestUnderstanding(
+ restatedGoal: "Generate an image of the current FIFA standings",
+ actionSurface: .appless
+ ),
+ frontmost: ("Finder", "com.apple.finder"),
+ resolveRunningWindow: { _ in nil },
+ resolveInstalledBundle: { _ in nil }
+ )
+
+ #expect(target == nil)
+ }
+
+ @Test
+ func noNamedTargetAndNoFrontmostRunsAppless() {
+ // A GUI-ish turn typed into the notch with nothing in front (frontmost == nil) has nothing to
+ // drive. It resolves to nil — an app-less run — instead of the old hard `noFrontmostApp` abort.
+ let target = LocalAppUserQueryCommandHandler.resolveDriveTarget(
+ understanding: HarnessRequestUnderstanding(restatedGoal: "Make a chart of this", targetAppName: nil),
+ frontmost: nil,
+ resolveRunningWindow: { _ in nil },
+ resolveInstalledBundle: { _ in nil }
+ )
+
+ #expect(target == nil)
}
}
diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.md
index 1bfc6dd7..7c51921e 100644
--- a/docs/guides/agent-harness.md
+++ b/docs/guides/agent-harness.md
@@ -102,15 +102,21 @@ but never a command. Only an `act` turn reaches the planner and the Mac. This is
the structural form of "conversations first": action is unreachable until the
turn is typed actionable, not merely discouraged by a prompt.
-For an actionable turn the same boundary also names the target app (or leaves it
-empty for system-tool tasks), extracts parameters and success criteria, flags
-whether clarification is needed, and chooses whether the work runs in the
-background (the agent acts without taking over the cursor or raising the app)
-or the foreground (the user is meant to watch — pulling something up, a
-walkthrough). Background is the default; foreground is the typed exception, and
-like every other field it is decided here, never matched from raw text. Every
-later step plans against this stable, typed goal instead of re-reading the
-user's words.
+For an actionable turn the same boundary also names the target app — or marks
+the turn *app-less*, a typed surface for work produced through system, web, and
+generative tools (find a file, change a setting, generate an image, research a
+question) that drives no app at all. That mark is the fact an empty target app
+used to leave ambiguous — "operate the front app" versus "no app is involved" —
+and it routes the run past the GUI machinery: an actionable turn is never
+blocked on a missing frontmost window, because only a GUI turn needs one, and an
+artifact task is never pinned to whatever app happened to be in front. The
+boundary also extracts parameters and success criteria, flags whether
+clarification is needed, and chooses whether the work runs in the background
+(the agent acts without taking over the cursor or raising the app) or the
+foreground (the user is meant to watch — pulling something up, a walkthrough).
+Background is the default; foreground is the typed exception, and like every
+other field it is decided here, never matched from raw text. Every later step
+plans against this stable, typed goal instead of re-reading the user's words.
Context sent to the model is always bounded. Compaction keeps the current
turn, relevant task state, recent useful evidence, summaries, memory snippets,
@@ -208,8 +214,8 @@ protected system folders.
Driving a GUI is the fallback, used only when the task truly needs it (canvas,
Electron, or proprietary interfaces with no command-line equivalent). This
preference lives in the planner doctrine and a built-in `system-tools` skill.
-For system-tool tasks the understanding boundary leaves the target app empty,
-so they're never pinned to a GUI app.
+For system-tool tasks the understanding boundary marks the turn app-less, so
+they're never pinned to a GUI app and never blocked on one being in front.
Shell safety is consent-based, not denylist-based. Each command is classified
by its argv tokens (typed fields, never natural language) into a risk tier:
@@ -254,6 +260,16 @@ run: nothing parses the screen in the background to stay warm — the planner pa
for a parse only when it chooses to look, and a re-look at an unchanged screen
within the same run reuses that parse instead of paying again.
+A run is not bound to one app. The see-tools take an `app` argument: naming an
+app on an observe/capture step switches the run's *active target* to it, and
+because every act, scroll, and keystroke resolves against that current target,
+the planner operates whatever it just looked at — observe Mail, act on Mail;
+observe Preview, act on Preview. The target is one small piece of shared state
+the providers read per step, seeded from the understood app and mutable
+thereafter; an app-less run starts with no target and acquires its first app the
+moment the planner observes one by name. This is the computer-use shape: the
+model routes per step instead of the run pre-committing to a single app.
+
Three things keep the planner aware of the whole screen, not just the front
window. Capture widens in scopes, smallest first — `scope=window` (default),
`scope=screen` (the display, for things drawn outside the window like a modal