Skip to content

Open source CapCut alternative.

TypeScript

fix(app): keep background turns off the foreground

David Ledcb11c4f544e
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index f3864456..d3772310 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -695,9 +695,16 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
// duration so it never races us on a parse.
let analyzer = HostedDebugUIInspectionAnalyzer(backend: backend)
+ // The turn's foreground/background choice — resolved here (not just at input-tool construction
+ // below) so the shell path can keep a background turn off the foreground: a `shell_exec` that
+ // raises an app (`osascript … activate`) has its focus steal handed straight back.
+ let executionPreference = forcedExecutionPreference ?? understanding?.executionPreference ?? .background
+
// 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.
- var harnessServices = LocalAppUserQueryHarnessServices.builtInSkillBackedServices()
+ var harnessServices = LocalAppUserQueryHarnessServices.builtInSkillBackedServices(
+ backgroundTurn: executionPreference == .background
+ )
let appleScriptGenerationAdapter = HostedAppleScriptGenerationAdapter()
harnessServices.appleScriptGenerator = { request in
await appleScriptGenerationAdapter.generateAppleScript(request)
@@ -835,22 +842,30 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
// understanding is unavailable we still default to background (each lane degrades to foreground on
// its own when an action can't be delivered that way).
// 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
+ // the user is away; an interactive turn lets the understanding boundary decide. (Resolved once
+ // above, before the built-in services are built, so the shell path shares the same decision.)
// 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(
- target: targetContext,
- executionPreference: executionPreference
- )
let visionProvider = VisionComputerUseToolProvider(
target: targetContext,
executionPreference: executionPreference,
analyzer: analyzer
)
+ // Let content.harvest read the pixels when the Accessibility tree is too thin to hold the content
+ // (a chat transcript's bubbles, a custom-drawn list). Wired only when this turn holds screen-capture, so
+ // harvest stays AX-only otherwise. The reader captures the window's buffer — no app raise.
+ var harvestVisionReader: (@MainActor () async -> [String])?
+ if granted.contains(.screenCapture) {
+ harvestVisionReader = { await visionProvider.readVisibleTextLines() }
+ }
+ let axProvider = AXComputerUseToolProvider(
+ target: targetContext,
+ executionPreference: executionPreference,
+ visionTextReader: harvestVisionReader
+ )
let pointerProvider = PointerComputerUseToolProvider(
target: targetContext,
executionPreference: executionPreference
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift
index 8a3a0b30..496293b7 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessRuntime.swift
@@ -718,6 +718,12 @@ public struct GenericHarnessRuntime: Sendable {
// A plain read-only tool that doesn't opt into caching re-runs freely (re-reading/observing is
// cheap and legitimately reflects fresh state).
if isReadOnly, !isCacheableRead { return nil }
+ // A VOLATILE tool re-reflects live, changed state on every call — a scrolling `content.harvest`
+ // after a "load more" click, a fresh capture — so re-running it with the same input is the whole
+ // point, not a redundant repeat. It is never deduped (the read cache above already exempts it; this
+ // exempts it from the "already done" block below, which fires for non-read-only tools like harvest
+ // and would otherwise trap the load-more→re-harvest loop into repeating "already done" forever).
+ if descriptor?.metadata[HarnessToolDescriptor.volatileResultMetadataKey] == "true" { return nil }
let signature = Self.canonicalInput(call.input)
let runHistory = Self.currentRunHistory(task.toolHistory)
guard let priorIndex = runHistory.lastIndex(where: { record in
diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
index aa5c4248..f42ffe7f 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
@@ -14,18 +14,22 @@ public enum DonkeyCommandBackends {
/// Build the closure wired into `HarnessBuiltInToolServices.commandExecutor`.
/// Returns a result for a recognized command, or `nil` so harness dispatch
/// falls through to its `unknownTool` handling.
- public static func makeExecutor() -> @Sendable (HarnessToolExecutionContext) async -> HarnessToolResult? {
- { context in await execute(context) }
+ /// `backgroundTurn` marks a turn the user is not watching: the shell path then restores the frontmost
+ /// app after each command so a `shell_exec` that raises an app (an `osascript … activate`) can't leave
+ /// it in front. Defaults false so callers that don't run background work (the Live voice session) keep
+ /// the foreground behavior unchanged.
+ public static func makeExecutor(backgroundTurn: Bool = false) -> @Sendable (HarnessToolExecutionContext) async -> HarnessToolResult? {
+ { context in await execute(context, backgroundTurn: backgroundTurn) }
}
@MainActor
- static func execute(_ context: HarnessToolExecutionContext) async -> HarnessToolResult? {
+ static func execute(_ context: HarnessToolExecutionContext, backgroundTurn: Bool = false) async -> HarnessToolResult? {
guard let command = DonkeyCommandLayer.Command(rawValue: context.call.name) else {
return nil
}
switch command {
case .shellExec:
- return await shellExec(context)
+ return await shellExec(context, backgroundTurn: backgroundTurn)
case .appsList:
return listApps(context)
case .appSkill:
@@ -845,7 +849,8 @@ public enum DonkeyCommandBackends {
return "… [earlier output truncated]\n" + String(output.suffix(shellFailureDiagnosticMaxLength))
}
- private static func shellExec(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {
+ @MainActor
+ private static func shellExec(_ context: HarnessToolExecutionContext, backgroundTurn: Bool = false) async -> HarnessToolResult {
guard let command = trimmed(context.call.input["command"]) ?? trimmed(context.call.input["cmd"]) else {
return invalidInput(context, "shell_exec requires a `command`.")
}
@@ -893,9 +898,30 @@ public enum DonkeyCommandBackends {
// plus the user's home when they approved this command at a prompt, so the approved write lands.
// nil → no folder yet.
let policy = shellPolicy(owned: owned, consented: !unprompted)
+ // On a background turn the user is not watching, so no command may leave another app in front.
+ // A shell command can raise one as a side effect (`osascript … activate`, `open -a`) outside the
+ // input guard, so snapshot the frontmost app before the run and hand focus back after — the steal
+ // never survives the call. Foreground turns keep whatever the command intentionally brought up.
+ let restoreTarget = backgroundTurn ? TargetFocusRecovery.frontmostProcessID() : nil
let result = await Task.detached(priority: .userInitiated) {
runShellSync(command, timeout: timeout, workingDirectory: workingDirectory, policy: policy)
}.value
+ if let restoreTarget {
+ // `open -a` raises the app ASYNCHRONOUSLY — it returns before the window server makes the app
+ // frontmost — so the steal may still be pending here. Poll briefly for the raise to land, then
+ // hand focus back; without the wait the restore sees "still frontmost, nothing moved", no-ops,
+ // and the app comes forward a beat later and stays. The poll exits the instant focus moves, so a
+ // synchronous raise (`osascript … activate`, which blocks until the app is up) costs nothing;
+ // only a slow async raise waits, and the cap is short so a non-raising write barely pays. A read
+ // never raises an app, so it skips the wait and the restore just confirms nothing moved.
+ if classification.tier != .read {
+ for _ in 0..<5 {
+ if TargetFocusRecovery.frontmostProcessID() != restoreTarget { break }
+ try? await Task.sleep(nanoseconds: 40_000_000)
+ }
+ }
+ TargetFocusRecovery.restoreFrontmost(to: restoreTarget)
+ }
let stdout = boundedOutput(result.stdout)
guard result.exitCode == 0 else {
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift
index 33b76ba1..c8ee3b04 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift
@@ -6,7 +6,10 @@ import os
public enum LocalAppUserQueryHarnessServices {
private static let logger = Logger(subsystem: "com.donkey.app", category: "skill-script")
- public static func builtInSkillBackedServices() -> HarnessBuiltInToolServices {
+ /// `backgroundTurn` flows to the shell path so a background run hands focus back after any command that
+ /// raises an app, keeping the turn off the foreground. Defaults false for callers with no background
+ /// context.
+ public static func builtInSkillBackedServices(backgroundTurn: Bool = false) -> HarnessBuiltInToolServices {
HarnessBuiltInToolServices(
skillRegistry: HarnessSkillRegistry(skills: BuiltInLocalAppSkillPacks.descriptors()),
generatedScripts: HarnessGeneratedScriptStore(artifacts: builtInValidatedScriptArtifacts()),
@@ -46,8 +49,9 @@ public enum LocalAppUserQueryHarnessServices {
},
// The Command Layer (incl. shell_exec) is intentionally available to
// the local planner as well as the Gemini Live session; both go
- // through the same DonkeyCommandBackends guardrails.
- commandExecutor: DonkeyCommandBackends.makeExecutor()
+ // through the same DonkeyCommandBackends guardrails. backgroundTurn flows on so a background
+ // run hands focus back after a command that raises an app.
+ commandExecutor: DonkeyCommandBackends.makeExecutor(backgroundTurn: backgroundTurn)
)
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/TargetFocusRecovery.swift b/apps/Donkey/Sources/DonkeyRuntime/TargetFocusRecovery.swift
index eb83ed8a..2cab7966 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/TargetFocusRecovery.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/TargetFocusRecovery.swift
@@ -24,4 +24,53 @@ public enum TargetFocusRecovery {
public static func frontmostAppName() -> String {
NSWorkspace.shared.frontmostApplication?.localizedName ?? "another app"
}
+
+ /// The pid of the app in front right now, captured just before a background action that could steal
+ /// focus (a `shell_exec` running `osascript … activate`, an `open -a`) so it can be handed back after.
+ public static func frontmostProcessID() -> pid_t? {
+ NSWorkspace.shared.frontmostApplication?.processIdentifier
+ }
+
+ /// Put the user's app back in front when a background action pulled another app forward. A background
+ /// turn promises no focus steal, but a shell command can raise an app as a side effect outside the
+ /// input guard; snapshotting the frontmost pid before the command and restoring it here makes that
+ /// steal impossible to leave standing. No-op when nothing moved (still frontmost), when the snapshot
+ /// app has since quit, or when it is Donkey itself — a background run never forces Donkey forward.
+ public static func restoreFrontmost(to processID: pid_t) {
+ guard processID != ProcessInfo.processInfo.processIdentifier,
+ NSWorkspace.shared.frontmostApplication?.processIdentifier != processID,
+ let app = NSRunningApplication(processIdentifier: processID) else {
+ return
+ }
+ app.activate()
+ }
+
+ /// Run a mouse/keyboard gesture with the target briefly brought to the front, then hand focus back.
+ ///
+ /// This exists because a synthetic mouse click or scroll only lands on the ACTIVE app — macOS drops it
+ /// for a backgrounded window no matter how it is posted (verified against a real app: pid-post, PSN-post,
+ /// and the raw event-record post all leave a backgrounded window untouched; only the frontmost app moves).
+ /// So a gesture on a background turn cannot be delivered invisibly; the honest path is to activate the
+ /// target for the moment of the gesture and restore the user's app after. `body` runs the gesture on the
+ /// real event tap while the target is front; `settle` lets the app process the last events before focus
+ /// leaves. Reads (Accessibility, screenshot OCR) never take this path — only gestures that click or scroll.
+ ///
+ /// Returns `nil` WITHOUT running `body` when the target could not be brought to the front, so a caller
+ /// never reports a gesture as done when it never landed. Pass `restore: false` on a foreground turn to
+ /// leave the target up (the user is meant to watch it).
+ public static func withForeground<T>(
+ processID: pid_t,
+ restore: Bool,
+ settle: UInt64 = 180_000_000,
+ _ body: () async -> T
+ ) async -> T? {
+ let previous = restore ? frontmostProcessID() : nil
+ guard await ensureFrontmost(processID: processID) else { return nil }
+ let out = await body()
+ if restore {
+ try? await Task.sleep(nanoseconds: settle)
+ if let previous, previous != processID { restoreFrontmost(to: previous) }
+ }
+ return out
+ }
}