Skip to content

Open source CapCut alternative.

TypeScript

feat(app): give the planner a multimodal world model

David Lea3c08f3b471a
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 49e075ed..50d5d32f 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -303,12 +303,25 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
}
let backend = DonkeyBackendInferenceClient(configuration: configuration)
+ // The thread is the COMPLETE, human-readable record of the turn (like ChatGPT/Claude), written
+ // live as markdown. It is opened here — before the very first model call — so the trace manager
+ // can record even the pre-loop understanding decision into it. The header uses the frontmost app
+ // (the app in front when the user asked); the resolved drive target is shown in the planning
+ // block below.
+ let transcript = ThreadTranscript(id: taskID)
+ transcript.begin(id: taskID, app: frontmostAppName)
+ transcript.userMessage(command)
+ // The turn-trace manager: the single sink every model call and every executed step reports to,
+ // so the whole decision path — prompts, replies, sensing modality, and per-call timing — is
+ // traceable in the thread file. The model boundaries hold it as `any HarnessTurnTracing`.
+ let trace = HarnessTurnTrace(transcript: transcript)
+
// Understand the request ONCE before the loop: restate the goal, identify the target app,
// extract parameters, and decide whether to clarify. Degrades to driving the raw command when
// it returns nil — or when the call outlives its deadline — so a backend hiccup never
// dead-ends or silently stalls the run.
progress?("Working out what you need")
- let understandingBoundary = HostedHarnessRequestUnderstanding(backend: backend)
+ let understandingBoundary = HostedHarnessRequestUnderstanding(backend: backend, trace: trace)
let understanding = await AIDeadline.race(seconds: Self.understandingTimeoutSeconds) {
await understandingBoundary.understand(command: command, frontmostAppName: frontmostAppName)
}
@@ -395,6 +408,10 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
)
let plannerDescriptors = await registry.descriptors()
let environmentSummary = await SystemToolCapabilityProbe.shared.summary()
+ // Every step, surface the other windows on screen (all apps/displays) to the planner so a
+ // request that lives in a window the user isn't looking at can be found and switched to. Donkey's
+ // own windows are filtered out by bundle id so the agent never targets its own overlay.
+ let ownBundleID = Bundle.main.bundleIdentifier
let planner = HostedHarnessStepPlanner(
backend: backend,
descriptors: plannerDescriptors,
@@ -402,7 +419,24 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
appGuidance: appGuidance,
understanding: understanding,
environmentSummary: environmentSummary,
- skillCatalog: Self.installedSkillCatalog()
+ skillCatalog: Self.installedSkillCatalog(),
+ trace: trace,
+ openWindows: {
+ MacWindowResolver().enumerateCandidates().filter { candidate in
+ guard let ownBundleID, let candidateBundle = candidate.bundleIdentifier else { return true }
+ return candidateBundle.caseInsensitiveCompare(ownBundleID) != .orderedSame
+ }
+ },
+ // Attach a compressed screenshot of the user's frontmost window to every step so a multimodal
+ // planner always sees the screen, not just AX/vision text. Best-effort: a capture failure
+ // returns nil and the step proceeds text-only, never breaking the planner.
+ captureScreenshot: {
+ guard let target = MacWindowResolver().frontmostUserAppTarget(),
+ let shot = try? await ScreenCaptureKitWindowScreenshotCapturer().capture(target: target) else {
+ return nil
+ }
+ return ScreenshotCompression.compressedForModel(shot).base64DataURL
+ }
)
_ = await genericHarnessLifecycle.coordinator.startRunning(
taskID: taskID,
@@ -420,13 +454,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
// planner's one-line reason, falling back to the tool's own summary), and after each step that
// physically moved the pointer (a click), animate the overlay cursor traveling to that exact
// target, so the visualization tracks what the harness is actually doing.
- // The thread: the real conversation record (like ChatGPT/Claude), written live as markdown —
- // user request, the assistant's thinking, each tool call and result, and the final answer — so
- // the full reasoning trace is readable (and renderable to the user later), and a stuck run is
- // visible instead of a mystery.
- let transcript = ThreadTranscript(id: taskID)
- transcript.begin(id: taskID, app: appName)
- transcript.userMessage(command)
+ //
// The thread is the COMPLETE session record: the turn's upfront planning (or its absence) is
// part of the conversation, not just an internal step. A follow-up turn (clarification
// answer, permission grant) appends its own planning block mid-thread.
@@ -449,12 +477,13 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
await MainActor.run {
let narration = Self.stepNarration(for: step, planner: planner)
if let result = step.toolResult {
- // One grouped block per step: the model's full thought summary (persisted here
- // and nowhere else, so the planning context stays bounded), its one-line reason,
- // the action with its input, and the output — plus any planning retries hit
- // while choosing this step, so a step that needed recovery reads as one unit.
- // The overlay/progress gets only the clipped one-line narration below.
- transcript.step(
+ // One grouped block per step through the trace manager: the model's full thought
+ // summary (persisted here and nowhere else, so the planning context stays bounded),
+ // its one-line reason, the action with its input, the output, any planning retries
+ // hit while choosing this step, and the timing the manager attaches — decision time
+ // vs. tool time plus which sensing modality the step used. The overlay/progress gets
+ // only the clipped one-line narration below.
+ trace.recordStep(
number: step.task.toolHistory.count,
thought: planner.lastThinking,
reason: planner.lastNarration,
@@ -462,7 +491,10 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
input: step.task.toolHistory.last?.call.input ?? [:],
status: result.status.rawValue,
output: result.summary,
- planningErrors: planner.lastPlanningErrors
+ planningErrors: planner.lastPlanningErrors,
+ modality: Self.sensingModality(forTool: result.toolName),
+ cacheHit: result.metadata["usedCache"].map { $0 == "true" },
+ elementCount: result.metadata["elementCount"].flatMap(Int.init)
)
} else {
// No tool executed (the call never ran), but planning failures are still part of
@@ -480,6 +512,11 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
if let progress, let narration {
progress(narration)
}
+ // The animated cursor playback is cosmetic and separate from the real input. It animates
+ // an overlay panel's window frame, which can re-enter AppKit's layout cycle on some macOS
+ // builds; this escape hatch turns the playback off (text narration still updates) so a
+ // run can proceed without it.
+ guard !Self.cursorVisualizationDisabled else { return }
guard let present = visualize else { return }
let screenSize = (NSScreen.main ?? NSScreen.screens.first)?.frame.size ?? .zero
guard let plan = Self.cursorVisualizationPlan(
@@ -520,6 +557,10 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
"complete traceID=\(traceID) app=\(appName) completed=\(completed) reason=\(outcomeReason) turns=\(turns) usedCache=\(anyTurnUsedCache) parseMS=\(Self.formatLatency(totalParseMS)) e2eTotalMS=\(Self.formatLatency(e2eTotalMS)) timeToFirstActionMS=\(Self.formatLatency(timeToFirstActionMS ?? 0)) avgPerTurnMS=\(Self.formatLatency(averagePerTurnMS))"
)
+ // Close the per-step trace with a compact whole-turn timing line, so the run's total cost and
+ // time-to-first-action sit at the foot of the thread next to the per-step breakdown.
+ trace.recordTurnTiming(e2eTotalMS: e2eTotalMS, timeToFirstActionMS: timeToFirstActionMS, steps: turns)
+
// Record the assistant's final answer to close the turn, then write a compacted, structured
// thread summary. A deterministic summary lands immediately; an LLM-written one replaces it in
// the background so the result isn't delayed by the summary call.
@@ -540,7 +581,17 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
THREAD:
\(threadText)
"""
- if let enhanced = await textGenerator.generate(prompt), !enhanced.isEmpty {
+ let summaryStartedAt = RunTraceTimestamp.now()
+ let enhanced = await textGenerator.generate(prompt)
+ trace.recordModelCall(TraceModelCall(
+ kind: .threadSummary,
+ prompt: prompt,
+ response: enhanced ?? "<no output>",
+ status: (enhanced?.isEmpty == false) ? .ok : .empty,
+ startedAt: summaryStartedAt,
+ endedAt: .now()
+ ))
+ if let enhanced, !enhanced.isEmpty {
transcript.writeSummary(enhanced)
}
}
@@ -810,6 +861,25 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
return narration
}
+ /// Which sensing modality a step used, matched on the executed tool's typed registry name (never on
+ /// user text). Only the two observation tools sense fresh elements; everything else (clicks, input,
+ /// shell, wait, verify) senses nothing, so its step shows no modality.
+ private static func sensingModality(forTool toolName: String) -> TraceModality {
+ switch toolName {
+ case "ax.observe": return .accessibility
+ case "vision.capture": return .vision
+ default: return .none
+ }
+ }
+
+ /// Escape hatch to suppress the cosmetic animated-cursor playback (set `DONKEY_DISABLE_CURSOR_VIZ=1`).
+ /// The playback animates an overlay window's frame, which can trip a re-entrant AppKit layout crash on
+ /// some macOS builds; turning it off lets a run proceed (the harness still does the real vision input
+ /// and the text narration still updates).
+ static var cursorVisualizationDisabled: Bool {
+ ProcessInfo.processInfo.environment["DONKEY_DISABLE_CURSOR_VIZ"] == "1"
+ }
+
private static func uptimeMilliseconds() -> Double {
ProcessInfo.processInfo.systemUptime * 1_000
}
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
index 3a0ee12a..2ff19122 100644
--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
@@ -136,9 +136,11 @@ public enum DonkeyPrompts {
understanding: HarnessRequestUnderstanding?,
environmentSummary: String?,
skillCatalog: String? = nil,
- retryNote: String? = nil
+ retryNote: String? = nil,
+ openWindows: [MacWindowTargetCandidate] = []
) -> String {
let elementsBlock = harnessStepElementsBlock(task.worldModel.elements)
+ let windowsBlock = harnessStepWindowsBlock(openWindows)
let factsBlock = task.worldModel.facts.isEmpty
? ""
@@ -194,7 +196,7 @@ public enum DonkeyPrompts {
GOAL: \(goalText)
\(understandingBlock)
\(historyBlock)
- \(factsBlock)\(environmentBlock)\(guidanceBlock)\(skillCatalogBlock)
+ \(factsBlock)\(environmentBlock)\(guidanceBlock)\(skillCatalogBlock)\(windowsBlock)
\(elementsBlock)
AVAILABLE TOOLS:
@@ -209,7 +211,20 @@ public enum DonkeyPrompts {
- Only operate the GUI when the task genuinely needs it (canvas/Electron/proprietary UI, or no
system-tool equivalent). When you do: SEE before you act — prefer ax.observe (fast,
structured) for native apps; use vision.capture when Accessibility is missing or insufficient
- — then act on a specific element by passing its id from the list above in "input".
+ — then act on a specific element by passing its id from the list above in "input". The see/act
+ tools focus the target app for you, so do NOT `open -a`/activate it first as a prerequisite —
+ go straight to ax.observe. Re-issuing a focus/open step instead of advancing is a loop that
+ burns the run.
+ - The action you need may not be a visible button. Figure it out like a person would, using the
+ general actions: RIGHT-CLICK an item (ax.click/vision.click button=right) to open its full
+ context menu — that is where Delete / Remove / Rename / "…from Library" usually live; or
+ select/open the item first and use its focused "⋯" / "More" / gear OVERFLOW menu; mouse.scroll
+ to bring offscreen items or controls into view; use the menu bar; or select an item and press
+ the matching key. After any of these, SEE again and read the
+ WHOLE menu before clicking — a context menu, popup, or confirmation dialog is just more
+ elements to observe, and the right entry is often a small labeled row near the bottom of a long
+ menu. Don't conclude something is impossible until you've tried these; only report it
+ unsupported if a skill says so or the paths are exhausted.
- Operating a specific app — even by script (playing music, saving a note, sending mail)? If it
appears in INSTALLED APP SKILLS above, consult that skill FIRST (app_skill) and run its
validated scripts (skill_run) before hand-writing osascript: the skill is the authority and
@@ -257,6 +272,24 @@ public enum DonkeyPrompts {
"""
}
+ /// Renders the other windows currently on screen — across every app and display — so the planner
+ /// knows what *else* exists in the world and can switch to or target a window that isn't in front.
+ /// A request often lives in a window the user isn't looking at; the planner needs it to exist here
+ /// before it can navigate to it. Bounds are global screen points (the same space tools act in).
+ public static func harnessStepWindowsBlock(_ windows: [MacWindowTargetCandidate]) -> String {
+ let onScreen = windows.filter { $0.isOnScreen && $0.bounds.width > 1 && $0.bounds.height > 1 }
+ guard !onScreen.isEmpty else { return "" }
+ let lines = onScreen.prefix(14).map { window -> String in
+ let app = window.appName ?? "?"
+ let title = (window.title?.isEmpty == false) ? " — \"\(window.title!)\"" : ""
+ let front = window.isFrontmost ? " [frontmost]" : ""
+ let bounds = window.bounds
+ return " - \(app)\(title)\(front) at \(Int(bounds.x)),\(Int(bounds.y)) \(Int(bounds.width))x\(Int(bounds.height))"
+ }
+ return "\nOPEN WINDOWS (every window on screen, any app or display — switch to or target one that isn't in front; widen vision.capture scope to screen or desktop to see a window off the active display):\n"
+ + lines.joined(separator: "\n") + "\n"
+ }
+
/// Renders observed elements in reading order with the geometry and state the observation already
/// captured — position (from `ax.frame.*` screen points or `vision.bbox.*` capture pixels), value,
/// and click eligibility — so the model can reason spatially ("the field under the Subject label")
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
index 09fe1cae..ad6888ad 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
@@ -29,6 +29,18 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
/// e.g. playing music or saving a note by script. nil when no skills are installed.
private let skillCatalog: String?
private let uptimeMS: @Sendable () -> Double
+ /// Optional turn-trace sink. Every planning call — the first sample, each retry, and the failure
+ /// shapes (empty reply, content filter, transport error) — is recorded here with its clipped prompt,
+ /// clipped reply, finish reason, attempt index, and span, so the whole decision path is traceable in
+ /// the thread. nil means tracing is off and the hot path is untouched.
+ private let trace: (any HarnessTurnTracing)?
+ /// Live snapshot of every window on screen (all apps/displays), rendered into the prompt each step
+ /// so the planner knows what else exists in the world and can target a window that isn't in front.
+ private let openWindows: @Sendable () -> [MacWindowTargetCandidate]
+ /// Best-effort compressed screenshot data URL attached to every step's request as an image so a
+ /// multimodal planner always SEES the screen, not just read AX/vision text. Returns nil only when
+ /// capture fails — the step then proceeds text-only, never breaking on a missing image.
+ private let captureScreenshot: @Sendable () async -> String?
/// Uptime (ms) at which the planner first chose an *action* tool (something that changes app
/// state, i.e. not a read-only observation). The route turns this into the "time to first action"
@@ -64,6 +76,9 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
understanding: HarnessRequestUnderstanding? = nil,
environmentSummary: String? = nil,
skillCatalog: String? = nil,
+ trace: (any HarnessTurnTracing)? = nil,
+ openWindows: @escaping @Sendable () -> [MacWindowTargetCandidate] = { [] },
+ captureScreenshot: @escaping @Sendable () async -> String? = { nil },
uptimeMS: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime * 1_000 }
) {
self.backend = backend
@@ -73,6 +88,9 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
self.understanding = understanding
self.environmentSummary = environmentSummary
self.skillCatalog = skillCatalog
+ self.trace = trace
+ self.openWindows = openWindows
+ self.captureScreenshot = captureScreenshot
self.uptimeMS = uptimeMS
self.readOnlyToolNames = Set(descriptors.filter { $0.safetyClass == .readOnly }.map(\.name))
self.requiredInputKeys = Dictionary(
@@ -316,19 +334,64 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
private static let maxOutputTokensCap = 8_000
private func decide(task: HarnessTaskState, retryNote: String?, attempt: Int) async throws -> Decision {
- let request = responseRequest(task: task, retryNote: retryNote, attempt: attempt)
+ let prompt = DonkeyPrompts.harnessStep(
+ task: task,
+ descriptors: descriptors,
+ appName: appName,
+ appGuidance: appGuidance,
+ understanding: understanding,
+ environmentSummary: environmentSummary,
+ skillCatalog: skillCatalog,
+ retryNote: retryNote,
+ openWindows: openWindows()
+ )
+ let imageDataURL = await captureScreenshot()
+ let request = responseRequest(prompt: prompt, attempt: attempt, imageDataURL: imageDataURL)
let backend = self.backend
- let response = try await AIDeadline.enforce(seconds: Self.stepTimeoutSeconds) {
- try await backend.createResponse(request)
+ let startedAt = RunTraceTimestamp.now()
+ let response: RemoteInferenceJSONValue
+ do {
+ response = try await AIDeadline.enforce(seconds: Self.stepTimeoutSeconds) {
+ try await backend.createResponse(request)
+ }
+ } catch {
+ recordPlannerCall(
+ prompt: prompt,
+ response: String(String(describing: error).prefix(500)),
+ finishReason: nil,
+ attempt: attempt,
+ status: .failed,
+ startedAt: startedAt,
+ endedAt: .now()
+ )
+ throw error
}
+ let endedAt = RunTraceTimestamp.now()
guard let text = RemoteInferenceResponseHelpers.outputText(from: response), !text.isEmpty else {
let raw = (try? JSONEncoder().encode(response)).flatMap { String(data: $0, encoding: .utf8) } ?? "<unencodable>"
let finishReason = RemoteInferenceResponseHelpers.providerFinishReason(from: response)
if let finishReason, Self.contentFilterFinishReasons.contains(finishReason) {
+ recordPlannerCall(
+ prompt: prompt, response: String(raw.prefix(500)), finishReason: finishReason,
+ attempt: attempt, status: .filtered, startedAt: startedAt, endedAt: endedAt
+ )
throw PlanningError.blockedByContentFilter(finishReason: finishReason, raw: String(raw.prefix(500)))
}
+ recordPlannerCall(
+ prompt: prompt, response: String(raw.prefix(2_000)), finishReason: finishReason,
+ attempt: attempt, status: .empty, startedAt: startedAt, endedAt: endedAt
+ )
throw PlanningError.missingOutputText(finishReason: finishReason, raw: String(raw.prefix(2_000)))
}
+ recordPlannerCall(
+ prompt: prompt,
+ response: text,
+ finishReason: RemoteInferenceResponseHelpers.providerFinishReason(from: response),
+ attempt: attempt,
+ status: .ok,
+ startedAt: startedAt,
+ endedAt: endedAt
+ )
let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)
let wire = try JSONDecoder().decode(DecisionWire.self, from: Data(json.utf8))
return Decision(
@@ -340,27 +403,50 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
)
}
- private func responseRequest(task: HarnessTaskState, retryNote: String?, attempt: Int) -> RemoteInferenceResponseCreateRequest {
+ /// Record one planning call into the turn trace. `attempt` is the 0-based loop index; the trace
+ /// shows it 1-based so the first sample reads as attempt 1.
+ private func recordPlannerCall(
+ prompt: String,
+ response: String,
+ finishReason: String?,
+ attempt: Int,
+ status: TraceModelCallStatus,
+ startedAt: RunTraceTimestamp,
+ endedAt: RunTraceTimestamp
+ ) {
+ trace?.recordModelCall(TraceModelCall(
+ kind: .plannerStep,
+ prompt: prompt,
+ response: response,
+ finishReason: finishReason,
+ attempt: attempt + 1,
+ status: status,
+ startedAt: startedAt,
+ endedAt: endedAt
+ ))
+ }
+
+ private func responseRequest(prompt: String, attempt: Int, imageDataURL: String? = nil) -> RemoteInferenceResponseCreateRequest {
let maxOutputTokens = min(Self.baseMaxOutputTokens * (attempt + 1), Self.maxOutputTokensCap)
+ // Text part always; the compressed screenshot is appended as an image part when available so a
+ // multimodal model sees the screen. Both server adapters accept `input_image` + `image_url`.
+ var content: [RemoteInferenceJSONValue] = [
+ .object([
+ "type": .string("input_text"),
+ "text": .string(prompt)
+ ])
+ ]
+ if let imageDataURL, !imageDataURL.isEmpty {
+ content.append(.object([
+ "type": .string("input_image"),
+ "image_url": .string(imageDataURL)
+ ]))
+ }
return RemoteInferenceResponseCreateRequest(
input: .array([
.object([
"role": .string("user"),
- "content": .array([
- .object([
- "type": .string("input_text"),
- "text": .string(DonkeyPrompts.harnessStep(
- task: task,
- descriptors: descriptors,
- appName: appName,
- appGuidance: appGuidance,
- understanding: understanding,
- environmentSummary: environmentSummary,
- skillCatalog: skillCatalog,
- retryNote: retryNote
- ))
- ])
- ])
+ "content": .array(content)
])
]),
store: false,
diff --git a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift
index 9d8b6558..74a07f51 100644
--- a/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift
+++ b/apps/Donkey/Sources/DonkeyAI/VisionComputerUseTools.swift
@@ -47,8 +47,17 @@ public final class VisionComputerUseToolProvider {
let minConfidence: Double
let reuseChangedFractionThreshold: Double
let capture: VisionActionDriver.ScreenshotCapture
+ /// Full-display capture, used by `vision.capture scope=screen` to see things drawn OUTSIDE the
+ /// target window — modal confirmation sheets, system dialogs, right-click menus.
+ let displayCapture: DisplayCapture
+ /// Whole-desktop capture across all displays, used by `vision.capture scope=desktop` — the widest
+ /// fallback for when the target isn't on the active display (another monitor, a background window).
+ let desktopCapture: DesktopCapture
let uptimeMS: @Sendable () -> Double
+ public typealias DisplayCapture = @MainActor (CGDirectDisplayID) async throws -> CapturedDisplayScreenshot
+ public typealias DesktopCapture = @MainActor () async throws -> CapturedDisplayScreenshot
+
/// Metrics from the most recent `screen.captureAndAnalyze`, so the loop can roll up parse time
/// and cache-hit telemetry without re-parsing the tool result.
public private(set) var lastCaptureMetrics: CaptureMetrics?
@@ -63,6 +72,8 @@ public final class VisionComputerUseToolProvider {
minConfidence: Double = 0.25,
reuseChangedFractionThreshold: Double = VisionComputerUseToolProvider.reuseChangedFractionThreshold,
capture: @escaping VisionActionDriver.ScreenshotCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().capture(target: $0) },
+ displayCapture: @escaping DisplayCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().captureDisplay(displayID: $0) },
+ desktopCapture: @escaping DesktopCapture = { try await ScreenCaptureKitWindowScreenshotCapturer().captureDesktop() },
uptimeMS: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime * 1_000 }
) {
self.appName = appName
@@ -74,6 +85,8 @@ public final class VisionComputerUseToolProvider {
self.minConfidence = minConfidence
self.reuseChangedFractionThreshold = reuseChangedFractionThreshold
self.capture = capture
+ self.displayCapture = displayCapture
+ self.desktopCapture = desktopCapture
self.uptimeMS = uptimeMS
}
@@ -82,7 +95,9 @@ public final class VisionComputerUseToolProvider {
HarnessToolDescriptor(
name: ToolName.captureAndAnalyze,
pluginID: "core.computer-use.vision",
- summary: "Screenshot the frontmost window and detect its UI elements with vision. Use when Accessibility is missing or insufficient (canvas/Electron content).",
+ 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"],
outputSchema: ["elements": "Detected element IDs, labels, roles, and click eligibility."],
requiredPermissions: [.screenCapture],
safetyClass: .readOnly,
@@ -153,6 +168,11 @@ public final class VisionComputerUseToolProvider {
guard let target = AccessibilityObserver.resolveTarget(appName: appName, bundleIdentifier: bundleIdentifier) else {
return result(context, status: .failed, summary: "No window for \(appName).", reason: "noWindowForApp")
}
+ switch trimmed(context.call.input["scope"])?.lowercased() {
+ case "screen": return await captureWideAndAnalyze(context, target: target, scope: "screen")
+ case "desktop": return await captureWideAndAnalyze(context, target: target, scope: "desktop")
+ default: break
+ }
let shot: CapturedWindowScreenshot
do {
shot = try await capture(target)
@@ -257,6 +277,101 @@ public final class VisionComputerUseToolProvider {
)
}
+ /// Capture wider than the target window and analyze it. `scope=screen` grabs the whole display the
+ /// window sits on (modal sheets, system prompts, right-click menus drawn outside the window);
+ /// `scope=desktop` grabs the entire desktop across all displays (a target on another monitor or a
+ /// background app). The capture's screen-space frame is stamped onto each element as its mapping
+ /// `region`, so a click maps the element's box through that rect exactly as a window capture maps
+ /// through the window rect. No cache: these surfaces are transient, so each wide capture parses fresh.
+ private func captureWideAndAnalyze(
+ _ context: HarnessToolExecutionContext,
+ target: MacWindowTargetCandidate,
+ scope: String
+ ) async -> HarnessToolResult {
+ let shot: CapturedDisplayScreenshot
+ do {
+ switch scope {
+ case "desktop": shot = try await desktopCapture()
+ default: shot = try await displayCapture(Self.displayID(forWindowBounds: target.bounds))
+ }
+ } catch {
+ let label = scope == "desktop" ? "Full-desktop" : "Full-screen"
+ return result(context, status: .failed, summary: "\(label) capture failed.", reason: "screenCaptureFailed")
+ }
+ let asWindow = CapturedWindowScreenshot(
+ pngData: shot.pngData,
+ imageWidth: shot.imageWidth,
+ imageHeight: shot.imageHeight,
+ captureMethod: .boundsCrop,
+ coordinateSpace: "display.points"
+ )
+ let compressed = ScreenshotCompression.compressedForModel(asWindow)
+ let imageWidth = max(1, Int(compressed.pixelSize.width.rounded()))
+ let imageHeight = max(1, Int(compressed.pixelSize.height.rounded()))
+ let started = uptimeMS()
+ let frame: DebugUIInspectionFrame
+ do {
+ frame = try await analyzer.inspect(
+ DebugUIInspectionRequest(
+ imageDataURL: compressed.base64DataURL,
+ pixelSize: compressed.pixelSize,
+ minConfidence: minConfidence
+ )
+ )
+ } catch {
+ return result(context, status: .failed, summary: "Vision parse failed.", reason: "visionParseFailed")
+ }
+ let parseMS = uptimeMS() - started
+ let region = WindowTargetBounds(
+ x: Double(shot.displayBounds.minX),
+ y: Double(shot.displayBounds.minY),
+ width: Double(shot.displayBounds.width),
+ height: Double(shot.displayBounds.height)
+ )
+ let worldElements = frame.elements
+ .filter { $0.bbox.hasPositiveArea }
+ .map { Self.worldElement(from: $0, imageWidth: imageWidth, imageHeight: imageHeight, region: region) }
+ lastCaptureMetrics = CaptureMetrics(usedCache: false, parseMS: parseMS, elementCount: worldElements.count)
+
+ let where_ = scope == "desktop" ? "the whole desktop" : "the full screen"
+ return HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: .succeeded,
+ summary: "Captured \(worldElements.count) element(s) across \(where_).",
+ observations: HarnessObservationDelta(
+ focusedApp: appName,
+ elements: worldElements,
+ facts: [
+ "vision.capture.scope": scope,
+ "vision.capture.usedCache": "false",
+ "vision.capture.parseMS": String(format: "%.0f", parseMS),
+ "vision.capture.elementCount": String(worldElements.count),
+ "lastAcceptedTool": context.call.name
+ ]
+ ),
+ metadata: [
+ "scope": scope,
+ "usedCache": "false",
+ "parseMS": String(format: "%.0f", parseMS),
+ "elementCount": String(worldElements.count)
+ ]
+ )
+ }
+
+ /// The display whose frame contains the target window's center (the one a modal will appear on),
+ /// falling back to the main display. Window bounds and `CGDisplayBounds` share the same top-left
+ /// global coordinate space, so the center point can be tested directly.
+ nonisolated static func displayID(forWindowBounds bounds: WindowTargetBounds) -> CGDirectDisplayID {
+ let center = CGPoint(x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2)
+ var ids = [CGDirectDisplayID](repeating: 0, count: 8)
+ var count: UInt32 = 0
+ if CGGetDisplaysWithPoint(center, 8, &ids, &count) == .success, count > 0, ids[0] != 0 {
+ return ids[0]
+ }
+ return CGMainDisplayID()
+ }
+
// MARK: - Guarded input
private func click(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {
@@ -284,7 +399,11 @@ public final class VisionComputerUseToolProvider {
let plan = VisionActionPlanner.PlannedAction(
action: "click", x: normalized.x, y: normalized.y, text: nil, reason: nil, screenPoint: nil
)
- guard let point = VisionActionPlanner.screenPoint(action: plan, window: target.bounds) else {
+ // A screen-scope element carries the display rect it was detected in; map through that. A
+ // window-scope element has no region, so map through the window's CURRENT bounds (re-resolved
+ // above) to stay correct if the window moved between the capture and this click.
+ let mappingRegion = geometry.region ?? target.bounds
+ guard let point = VisionActionPlanner.screenPoint(action: plan, window: mappingRegion) else {
return result(context, status: .failed, summary: "Could not map element \(elementID) to a screen point.", reason: "unmappablePoint")
}
let button: MacPointerInput.Button = context.call.input["button"] == "right" ? .right : .left
@@ -295,7 +414,7 @@ public final class VisionComputerUseToolProvider {
callID: context.call.id,
toolName: context.call.name,
status: .succeeded,
- summary: "\(clickWord) \(element.label.isEmpty ? elementID : element.label).",
+ summary: "\(clickWord) \(element.label.isEmpty ? elementID : element.label) at screen (\(Int(point.x)),\(Int(point.y))).",
observations: HarnessObservationDelta(facts: ["lastAcceptedTool": context.call.name]),
metadata: [
"elementID": elementID,
@@ -373,10 +492,38 @@ public final class VisionComputerUseToolProvider {
)
}
+ /// Screen-scope variant: same mapping metadata plus the display rect the image covered, so a later
+ /// `vision.click` maps the element's box through that display rect instead of the window's bounds.
+ nonisolated static func worldElement(
+ from element: DebugUIElement,
+ imageWidth: Int,
+ imageHeight: Int,
+ region: WindowTargetBounds
+ ) -> HarnessWorldElement {
+ let base = worldElement(from: element, imageWidth: imageWidth, imageHeight: imageHeight)
+ var metadata = base.metadata
+ metadata["vision.region.x"] = String(region.x)
+ metadata["vision.region.y"] = String(region.y)
+ metadata["vision.region.width"] = String(region.width)
+ metadata["vision.region.height"] = String(region.height)
+ metadata["vision.scope"] = "screen"
+ return HarnessWorldElement(
+ id: base.id,
+ label: base.label,
+ role: base.role,
+ isActionEligible: base.isActionEligible,
+ actions: base.actions,
+ metadata: metadata
+ )
+ }
+
struct ElementGeometry: Sendable {
var bbox: DebugUIBoundingBox
var imageWidth: Int
var imageHeight: Int
+ /// The screen-space rect the parse image covered, for a `scope=screen` capture. nil for a
+ /// window capture, where the click maps through the window's re-resolved bounds instead.
+ var region: WindowTargetBounds?
}
nonisolated static func geometry(from metadata: [String: String]) -> ElementGeometry? {
@@ -388,10 +535,18 @@ public final class VisionComputerUseToolProvider {
let imageHeight = metadata["vision.image.height"].flatMap(Int.init) else {
return nil
}
+ var region: WindowTargetBounds?
+ if let rx = metadata["vision.region.x"].flatMap(Double.init),
+ let ry = metadata["vision.region.y"].flatMap(Double.init),
+ let rw = metadata["vision.region.width"].flatMap(Double.init),
+ let rh = metadata["vision.region.height"].flatMap(Double.init) {
+ region = WindowTargetBounds(x: rx, y: ry, width: rw, height: rh)
+ }
return ElementGeometry(
bbox: DebugUIBoundingBox(x: x, y: y, width: width, height: height),
imageWidth: imageWidth,
- imageHeight: imageHeight
+ imageHeight: imageHeight,
+ region: region
)
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
index c05f0f2d..2c41b7c8 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/MacAccessibilitySnapshotCaptureService.swift
@@ -407,6 +407,22 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilit
for target: MacWindowTargetCandidate,
in application: AXUIElement
) -> AXUIElement? {
+ let windows = elementArrayAttribute(
+ kAXWindowsAttribute as CFString,
+ from: application,
+ limit: 100
+ )
+
+ // A modal popup — a separate dialog window or a modal panel — blocks its parent window, so
+ // while one is open it is the surface the planner needs to see and act on (its buttons and
+ // input fields). This is app-agnostic: confirmation prompts, save/print dialogs, and login
+ // sheets are routine RPA surfaces, and a plain window-by-target lookup would miss them
+ // because they don't match the resolved main window. (Sheets attach as children of their
+ // parent window and already appear under it; this catches the separate-window case.)
+ if let modal = windows.first(where: { isModalPopup($0) }) {
+ return modal
+ }
+
if let focusedWindow = elementAttribute(
kAXFocusedWindowAttribute as CFString,
from: application
@@ -414,11 +430,6 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilit
return focusedWindow
}
- let windows = elementArrayAttribute(
- kAXWindowsAttribute as CFString,
- from: application,
- limit: 100
- )
if let match = windows.first(where: { matches($0, target: target) }) {
return match
}
@@ -426,6 +437,16 @@ final class ApplicationServicesMacAccessibilitySnapshotCapturer: MacAccessibilit
return windows.first
}
+ /// A window that traps interaction until dismissed: a dialog/system-dialog subrole, or any
+ /// window flagged `AXModal`. Used so the observation surfaces popups over the main window.
+ private func isModalPopup(_ element: AXUIElement) -> Bool {
+ let subrole = stringAttribute(kAXSubroleAttribute as CFString, from: element)
+ if subrole == (kAXDialogSubrole as String) || subrole == (kAXSystemDialogSubrole as String) {
+ return true
+ }
+ return boolAttribute(kAXModalAttribute as CFString, from: element) == true
+ }
+
private func readRawNode(
_ element: AXUIElement,
depth: Int,
diff --git a/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift b/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift
index ea7f85b4..4593022d 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/WindowScreenshotCaptureService.swift
@@ -374,6 +374,133 @@ public final class ScreenCaptureKitWindowScreenshotCapturer: WindowScreenshotCap
}
}
+/// A screenshot of an entire display, used when the thing to interact with lives OUTSIDE the target
+/// window — a modal confirmation sheet, a system dialog, or a right-click menu. `displayBounds` is the
+/// display's frame in global, top-left-origin screen points, so a detected element's normalized box can
+/// be mapped to a screen point exactly like a window capture (just against the display rect instead of
+/// the window rect).
+public struct CapturedDisplayScreenshot: Sendable {
+ public var pngData: Data
+ public var imageWidth: Int
+ public var imageHeight: Int
+ public var displayBounds: CGRect
+
+ public init(pngData: Data, imageWidth: Int, imageHeight: Int, displayBounds: CGRect) {
+ self.pngData = pngData
+ self.imageWidth = imageWidth
+ self.imageHeight = imageHeight
+ self.displayBounds = displayBounds
+ }
+}
+
+public extension ScreenCaptureKitWindowScreenshotCapturer {
+ /// Capture an entire display through ScreenCaptureKit (same backend as the window path, so it
+ /// honors the same screen-recording permission). `displayID` picks the screen the modal is on —
+ /// normally the one the target window sits on.
+ func captureDisplay(displayID: CGDirectDisplayID) async throws -> CapturedDisplayScreenshot {
+ guard permissionChecker.hasScreenRecordingAccess() else {
+ throw WindowScreenshotCaptureError.screenRecordingPermissionDenied
+ }
+ let content = try await SCShareableContent.current
+ guard let display = content.displays.first(where: { $0.displayID == displayID })
+ ?? content.displays.first else {
+ throw WindowScreenshotCaptureError.captureFailed(windowID: 0, reason: "no SCDisplay for \(displayID)")
+ }
+ let filter = SCContentFilter(display: display, excludingWindows: [])
+ let contentInfo = SCShareableContent.info(for: filter)
+ let scale = CGFloat(contentInfo.pointPixelScale)
+ let configuration = SCStreamConfiguration()
+ configuration.width = max(1, Int(ceil(contentInfo.contentRect.width * scale)))
+ configuration.height = max(1, Int(ceil(contentInfo.contentRect.height * scale)))
+ configuration.showsCursor = false
+ configuration.capturesAudio = false
+
+ let image = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: configuration)
+ let pngData = try Self.pngData(for: image, windowID: 0)
+ return CapturedDisplayScreenshot(
+ pngData: pngData,
+ imageWidth: image.width,
+ imageHeight: image.height,
+ displayBounds: CGDisplayBounds(displayID)
+ )
+ }
+
+ /// Capture the ENTIRE desktop across all displays as one image — the widest fallback, for when the
+ /// thing to act on isn't on the active display at all (another monitor, a background app's window).
+ /// Each display is captured and composited into a single canvas laid out in global, top-left-origin
+ /// screen points, so `displayBounds` (the union of every display's frame) maps detected elements to
+ /// screen points exactly like a window or single-display capture.
+ func captureDesktop() async throws -> CapturedDisplayScreenshot {
+ guard permissionChecker.hasScreenRecordingAccess() else {
+ throw WindowScreenshotCaptureError.screenRecordingPermissionDenied
+ }
+ let content = try await SCShareableContent.current
+ let displays = content.displays
+ guard !displays.isEmpty else {
+ throw WindowScreenshotCaptureError.captureFailed(windowID: 0, reason: "no displays")
+ }
+
+ // Union of every display's frame, in global top-left-origin points (the world coordinate space).
+ var desktop = CGRect.null
+ for display in displays { desktop = desktop.union(CGDisplayBounds(display.displayID)) }
+ guard desktop.width >= 1, desktop.height >= 1 else {
+ throw WindowScreenshotCaptureError.captureFailed(windowID: 0, reason: "empty desktop rect")
+ }
+ let canvasWidth = Int(desktop.width.rounded())
+ let canvasHeight = Int(desktop.height.rounded())
+ guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB),
+ let canvas = CGContext(
+ data: nil,
+ width: canvasWidth,
+ height: canvasHeight,
+ bitsPerComponent: 8,
+ bytesPerRow: 0,
+ space: colorSpace,
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
+ ) else {
+ throw WindowScreenshotCaptureError.captureFailed(windowID: 0, reason: "desktop canvas allocation failed")
+ }
+ canvas.setFillColor(CGColor(gray: 0, alpha: 1))
+ canvas.fill(CGRect(x: 0, y: 0, width: canvasWidth, height: canvasHeight))
+
+ for display in displays {
+ let bounds = CGDisplayBounds(display.displayID)
+ let filter = SCContentFilter(display: display, excludingWindows: [])
+ let info = SCShareableContent.info(for: filter)
+ let scale = CGFloat(info.pointPixelScale)
+ let configuration = SCStreamConfiguration()
+ configuration.width = max(1, Int(ceil(info.contentRect.width * scale)))
+ configuration.height = max(1, Int(ceil(info.contentRect.height * scale)))
+ configuration.showsCursor = false
+ configuration.capturesAudio = false
+ let image = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: configuration)
+ // CGContext is bottom-left origin; place each display so the composite reads top-left like a
+ // normal image. A display whose top sits `topInset` points below the desktop top is drawn so
+ // its top lands at canvasHeight - topInset.
+ let leftInset = bounds.minX - desktop.minX
+ let topInset = bounds.minY - desktop.minY
+ let drawRect = CGRect(
+ x: leftInset,
+ y: CGFloat(canvasHeight) - topInset - bounds.height,
+ width: bounds.width,
+ height: bounds.height
+ )
+ canvas.draw(image, in: drawRect)
+ }
+
+ guard let composite = canvas.makeImage() else {
+ throw WindowScreenshotCaptureError.captureFailed(windowID: 0, reason: "desktop composite failed")
+ }
+ let pngData = try Self.pngData(for: composite, windowID: 0)
+ return CapturedDisplayScreenshot(
+ pngData: pngData,
+ imageWidth: composite.width,
+ imageHeight: composite.height,
+ displayBounds: desktop
+ )
+ }
+}
+
private extension WindowTargetBounds {
func intersects(_ other: WindowTargetBounds) -> Bool {
let maxX = x + width
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift
index 875f2105..8e9151fe 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift
@@ -1,4 +1,5 @@
import DonkeyAI
+import DonkeyContracts
import DonkeyHarness
import Foundation
import Testing
@@ -43,4 +44,48 @@ struct HarnessStepPromptTests {
)
#expect(!prompt.contains("authoritative playbooks for these apps/domains"))
}
+
+ private func window(app: String, title: String, frontmost: Bool) -> MacWindowTargetCandidate {
+ MacWindowTargetCandidate(
+ windowID: 1, processID: 2, appName: app, bundleIdentifier: "com.example.\(app)",
+ title: title, bounds: WindowTargetBounds(x: 0, y: 0, width: 1440, height: 900),
+ isVisible: true, isOnScreen: true, isFrontmost: frontmost, isFocused: frontmost,
+ isIPhoneMirroring: false,
+ safetyAssessment: WindowTargetSafetyAssessment(status: .allowed, summary: "")
+ )
+ }
+
+ /// The other windows on screen must reach the prompt so a request that lives in a window the user
+ /// isn't looking at exists in the world before the planner can navigate to it.
+ @Test
+ func includesOpenWindowsBlock() {
+ let prompt = DonkeyPrompts.harnessStep(
+ task: task(goal: "open my github tab"),
+ descriptors: [],
+ appName: "Notes",
+ appGuidance: nil,
+ understanding: nil,
+ environmentSummary: nil,
+ openWindows: [window(app: "Safari", title: "GitHub", frontmost: true)]
+ )
+ #expect(prompt.contains("OPEN WINDOWS"))
+ #expect(prompt.contains("Safari"))
+ #expect(prompt.contains("\"GitHub\""))
+ #expect(prompt.contains("[frontmost]"))
+ }
+
+ /// With no other windows the block is omitted (no dangling header).
+ @Test
+ func omitsOpenWindowsWhenNone() {
+ let prompt = DonkeyPrompts.harnessStep(
+ task: task(goal: "what time is it"),
+ descriptors: [],
+ appName: "iTerm2",
+ appGuidance: nil,
+ understanding: nil,
+ environmentSummary: nil,
+ openWindows: []
+ )
+ #expect(!prompt.contains("OPEN WINDOWS"))
+ }
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerUseToolsTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerUseToolsTests.swift
index 8eb95c3b..0eb5338e 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerUseToolsTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/VisionComputerUseToolsTests.swift
@@ -48,6 +48,47 @@ struct VisionComputerUseToolsTests {
}
}
+ @Test
+ func screenScopeElementMapsThroughDisplayRectNotWindow() {
+ // A modal/dialog detected in a full-screen (scope=screen) capture carries the DISPLAY rect it
+ // was found in, so its click maps through that rect — even on a second display offset from the
+ // origin. Center of a 1920x1080 parse image, against a display at x-offset 1920, lands dead
+ // center of that display: (1920 + 960, 0 + 540).
+ let display = WindowTargetBounds(x: 1920, y: 0, width: 1920, height: 1080)
+ let detected = element(id: "delete-btn", bbox: DebugUIBoundingBox(x: 910, y: 490, width: 100, height: 100))
+ let world = VisionComputerUseToolProvider.worldElement(
+ from: detected, imageWidth: 1920, imageHeight: 1080, region: display
+ )
+
+ #expect(world.metadata["vision.scope"] == "screen")
+ let geometry = VisionComputerUseToolProvider.geometry(from: world.metadata)
+ #expect(geometry?.region == display)
+
+ if let geo = geometry, let region = geo.region {
+ let normalized = VisionComputerUseToolProvider.normalizedCenter(
+ bbox: geo.bbox, imageWidth: geo.imageWidth, imageHeight: geo.imageHeight
+ )
+ let plan = VisionActionPlanner.PlannedAction(
+ action: "click", x: normalized.x, y: normalized.y, text: nil, reason: nil, screenPoint: nil
+ )
+ let point = VisionActionPlanner.screenPoint(action: plan, window: region)
+ #expect(abs((point?.x ?? 0) - 2880) < 0.5)
+ #expect(abs((point?.y ?? 0) - 540) < 0.5)
+ } else {
+ Issue.record("expected screen-scope geometry with a region")
+ }
+ }
+
+ @Test
+ func windowScopeElementHasNoRegion() {
+ // A normal window capture carries no region, so the click falls back to the window's current
+ // bounds (re-resolved at click time, so it stays correct if the window moved).
+ let detected = element(id: "e1", bbox: DebugUIBoundingBox(x: 10, y: 10, width: 20, height: 20))
+ let world = VisionComputerUseToolProvider.worldElement(from: detected, imageWidth: 100, imageHeight: 100)
+ #expect(world.metadata["vision.scope"] == nil)
+ #expect(VisionComputerUseToolProvider.geometry(from: world.metadata)?.region == nil)
+ }
+
@Test
func zeroAreaElementIsNotActionEligible() {
let detected = element(id: "e2", bbox: DebugUIBoundingBox(x: 0, y: 0, width: 0, height: 0))
diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.md
index a6073d0c..183b1cd5 100644
--- a/docs/guides/agent-harness.md
+++ b/docs/guides/agent-harness.md
@@ -62,12 +62,18 @@ Every task carries its own durable state:
State is task-local. Pausing, clarifying, gating, interrupting, or cancelling
one task never touches another.
-Storage is split three ways so decisions stay inspectable:
-
-- **Threads** store conversation events and active task ids.
+Storage keeps decisions inspectable:
+
+- **Threads** store the conversation *and* the turn trace, in the same thread
+ file. The trace records every model call (clipped prompt and reply, finish
+ reason, attempt, outcome, and duration), which sensing modality each step used
+ (Accessibility vs. AI vision), and the per-step split of decision time vs.
+ tool time. Timestamps are wall-clock plus monotonic, so a slow turn is pinned
+ to a specific call instead of a coarse end-to-end number.
- **Task snapshots** store execution state.
-- **Compaction snapshots** record exactly what context was sent to the model
- for each decision.
+
+One turn-trace manager is the single sink every model call and the step loop
+report to — the substrate a later self-correcting pass would learn from.
## Turn Understanding
@@ -181,15 +187,26 @@ Seeing and acting are plain tools the planner picks per step — not a fixed
pipeline. The harness re-plans after every observation: look, see the result,
pick the next tool.
-**To see**, the planner picks one of two paths. Accessibility tree reads are
-fast, structured, and preferred for native apps. Screenshot + vision works on
-any pixels (canvas, Electron) and is the fallback when Accessibility isn't
-enough. Both return elements into the world model. Screenshots never go to
-hosted model providers: the planner reads AX and vision annotations rendered
-as text — each element with its geometry, value, and click eligibility, in
-reading order. A non-LLM monitor watches the frontmost window's screenshot
-fingerprint and re-parses on large changes, keeping the vision cache warm so
-captures are usually free at decision time.
+**To see**, the planner draws on two paths: Accessibility reads (fast,
+structured, preferred for native apps) and screenshot + vision (any pixels —
+canvas, Electron). Both return elements into the world model, which the planner
+reads as text: each element with its geometry, value, and click eligibility, in
+reading order. With a multimodal model the compressed screenshot goes too
+(`ScreenshotCompression.compressedForModel` — ~896px JPEG), so the planner can
+point at pixels AX and the vision parse miss. A non-LLM monitor re-parses on
+large screen changes, keeping the vision cache warm so captures are usually free
+at decision time.
+
+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
+sheet or right-click menu), `scope=desktop` (all displays, when the target is on
+another monitor); detected elements carry the rect they were found in, so a
+click maps through it the same way at any scope. When a modal popup is open the
+Accessibility read surfaces *that* window — its buttons and fields are what the
+planner needs. And the world model lists every open window (app, title, bounds),
+so a request living in a background window exists before the planner navigates
+to it.
**To act**, the planner can click an element, type or press keys (including
modifier chords), scroll, drag one observed element onto another, wait for the
diff --git a/docs/guides/donkey-vision.md b/docs/guides/donkey-vision.md
index 3066dc61..6d4bdba2 100644
--- a/docs/guides/donkey-vision.md
+++ b/docs/guides/donkey-vision.md
@@ -117,7 +117,12 @@ cadence, scope, and filters, not which evidence source runs.
1. **Model boxes are never pixel-perfect.** Do not add global coordinate
offsets to compensate for AI localization.
-2. **Scoped captures only.** Never send full-desktop screenshots to hosted AI.
+2. **Smallest scope that works, escalate when needed.** Screenshots may go to
+ hosted models (the harness sends compressed captures to multimodal models).
+ Start with the target window; widen to a display for cross-window surfaces
+ like modals; fall back to the whole desktop only when the thing to act on
+ isn't visible at a tighter scope. Always compress before sending, and prefer
+ the tightest scope that still shows what the model needs.
3. **No provider switch.** Provider selection is not the UI or config model
for Donkey Vision.
4. **AI evidence stays marked.** Keep AI boxes visually distinct and tagged so