Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Capture requested macOS window screenshots (R5.6) (#945)

Tomáš Doubek248b671ddd16
diff --git a/crates/engine/src/tools/apple_runtime.rs b/crates/engine/src/tools/apple_runtime.rs
index 5c915f51..ad4341d1 100644
--- a/crates/engine/src/tools/apple_runtime.rs
+++ b/crates/engine/src/tools/apple_runtime.rs
@@ -75,7 +75,10 @@ pub struct ObserveUiParams {
/// A specific window to restrict to (on Windows, its window handle).
#[serde(default)]
pub window_id: Option<u64>,
- /// Include a screenshot (PNG, base64) alongside the tree.
+ /// Include a screenshot (PNG, base64) alongside the tree. macOS 14+: captures one on-screen
+ /// window belonging to pid, restricted by window_id when supplied, at up to 2048 pixels
+ /// per side. Without window_id, captures the first matching window. Needs existing Screen
+ /// Recording permission; failures are explicit limitations and never open permission dialogs.
#[serde(default)]
pub screenshot: bool,
/// Include the accessibility tree.
@@ -468,13 +471,28 @@ mod macos {
} else {
format!("Skipped the accessibility tree for pid {pid}, as requested.")
};
- let b =
+ let screenshot_limitation = if p.screenshot && result.get("screenshot").is_none() {
+ let error = result.get("screenshot_error");
+ Some(Limitation::new(
+ error.and_then(|e| e.get("code")).and_then(Value::as_str).unwrap_or("screenshot_unavailable"),
+ error
+ .and_then(|e| e.get("message"))
+ .and_then(Value::as_str)
+ .unwrap_or("The requested screenshot was not captured; check the helper error and retry."),
+ ))
+ } else {
+ None
+ };
+ let mut b =
EvidenceBuilder::new("runtime_ui_read", Subject { kind: "ui".into(), sha256: None, name: Some(format!("pid {pid}")) }, env(ctx, "accessibility"))
- .params(json!({"pid": pid, "max_nodes": p.max_nodes, "screenshot": p.screenshot, "accessibility": p.accessibility}))
+ .params(json!({"pid": pid, "window_id": p.window_id, "max_nodes": p.max_nodes, "screenshot": p.screenshot, "accessibility": p.accessibility}))
.result(result)
.summary(summary)
.confidence(Confidence::Observed)
.authority(Authority::OurRun);
+ if let Some(limitation) = screenshot_limitation {
+ b = b.limitation(limitation).coverage(Coverage { status: craft_anything_evidence::CoverageStatus::Partial, ..Coverage::default() });
+ }
Ok(ToolOutput::evidence(b.build()?))
}
@@ -647,10 +665,37 @@ mod tests {
assert_eq!(output["result"]["nodes"], json!([]), "{output}");
assert_eq!(output["result"]["truncated"], false, "{output}");
assert_eq!(output["params"]["accessibility"], false, "{output}");
+ assert!(output["result"].get("screenshot").is_none(), "{output}");
+ assert!(output["result"].get("screenshot_error").is_none(), "{output}");
assert!(output["summary"].as_str().unwrap().contains("Skipped the accessibility tree"), "{output}");
}
}
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn macos_reports_a_requested_screenshot_that_cannot_be_captured() {
+ let e = Engine::new(crate::testing::session());
+ // This process has no windows. A deliberately impossible window id ensures the helper
+ // can never capture anything, even on a machine with Screen Recording permission.
+ let output = e
+ .call("runtime_ui_read", json!({"pid": std::process::id(), "window_id": u64::MAX, "accessibility": false, "screenshot": true}), granted())
+ .unwrap()
+ .to_json();
+ assert_eq!(output["result"]["nodes"], json!([]), "{output}");
+ assert!(output["result"].get("screenshot").is_none(), "{output}");
+ let error = &output["result"]["screenshot_error"];
+ assert!(
+ matches!(
+ error["code"].as_str(),
+ Some("screen_recording_denied" | "screenshot_window_not_found" | "screenshot_unsupported" | "screenshot_capture_failed")
+ ),
+ "{output}"
+ );
+ assert!(output["limitations"].as_array().unwrap().iter().any(|l| l["code"] == error["code"] && l["message"] == error["message"]), "{output}");
+ assert_eq!(output["coverage"]["status"], "partial", "{output}");
+ assert_eq!(output["params"]["window_id"], u64::MAX, "{output}");
+ }
+
#[cfg(target_os = "macos")]
#[test]
fn calls_validate_before_dispatch() {
diff --git a/crates/engine/src/tools/apple_runtime/native_ui_helper.swift b/crates/engine/src/tools/apple_runtime/native_ui_helper.swift
index a86a4fc5..74c66f47 100644
--- a/crates/engine/src/tools/apple_runtime/native_ui_helper.swift
+++ b/crates/engine/src/tools/apple_runtime/native_ui_helper.swift
@@ -12,6 +12,65 @@
import Foundation
import ApplicationServices
+import ScreenCaptureKit
+import ImageIO
+import AppKit
+
+func screenshotFailure(_ code: String, _ message: String) -> [String: Any] {
+ return ["screenshot_error": ["code": code, "message": message]]
+}
+
+// Never capture a display or fall back to a different process's window. Enumeration needs
+// existing Screen Recording permission; preflight avoids opening a permission dialog.
+@MainActor
+func captureScreenshot(pid: Int32, windowID: UInt64?) async -> [String: Any] {
+ guard #available(macOS 14.0, *) else {
+ return screenshotFailure("screenshot_unsupported", "Screenshots need macOS 14 or later.")
+ }
+ // A command-line helper has no AppKit application yet. ScreenCaptureKit needs its
+ // WindowServer connection initialized, or CoreGraphics can abort in CGS_REQUIRE_INIT.
+ _ = NSApplication.shared
+ guard CGPreflightScreenCaptureAccess() else {
+ return screenshotFailure("screen_recording_denied", "Screenshot unavailable: grant Screen Recording permission to the invoking app in System Settings, then retry.")
+ }
+ do {
+ let content = try await SCShareableContent.excludingDesktopWindows(true, onScreenWindowsOnly: true)
+ let candidates = content.windows.filter {
+ $0.owningApplication?.processID == pid && $0.windowLayer == 0 &&
+ $0.frame.width > 0 && $0.frame.height > 0 &&
+ (windowID == nil || UInt64($0.windowID) == windowID)
+ }
+ guard let window = candidates.first else {
+ return screenshotFailure("screenshot_window_not_found", "No capturable on-screen window matches this pid and window_id. Open the target window and retry.")
+ }
+ let width = window.frame.width
+ let height = window.frame.height
+ guard width.isFinite && height.isFinite else {
+ return screenshotFailure("screenshot_invalid_size", "The target window has invalid dimensions.")
+ }
+ // Bound pixels before capture and encoded bytes before base64/JSON allocation.
+ let scale = min(1.0, 2048.0 / max(width, height))
+ let config = SCStreamConfiguration()
+ config.width = max(1, Int((width * scale).rounded(.down)))
+ config.height = max(1, Int((height * scale).rounded(.down)))
+ config.showsCursor = false
+ let image = try await SCScreenshotManager.captureImage(
+ contentFilter: SCContentFilter(desktopIndependentWindow: window), configuration: config)
+ let png = NSMutableData()
+ guard let destination = CGImageDestinationCreateWithData(png, "public.png" as CFString, 1, nil) else {
+ return screenshotFailure("screenshot_encoding_failed", "Could not create a PNG encoder for the screenshot.")
+ }
+ CGImageDestinationAddImage(destination, image, nil)
+ guard CGImageDestinationFinalize(destination), png.length <= 6 * 1024 * 1024 else {
+ return screenshotFailure("screenshot_encoding_failed", "Screenshot PNG encoding failed or exceeded the 6 MiB limit.")
+ }
+ return ["screenshot": ["mime_type": "image/png", "base64": (png as Data).base64EncodedString(),
+ "window_id": window.windowID, "width": image.width, "height": image.height,
+ "scaled": scale < 1.0]]
+ } catch {
+ return screenshotFailure("screenshot_capture_failed", "The window screenshot could not be captured. Check Screen Recording permission and that the target window is still open, then retry.")
+ }
+}
struct Request: Decodable {
var command: String
@@ -105,7 +164,11 @@ if readAccessibility && !AXIsProcessTrusted() {
switch req.command {
case "observe":
let nodes = readAccessibility ? snapshot(pid: pid, maxNodes: req.max_nodes ?? 5000) : []
- emit(["nodes": nodes, "truncated": readAccessibility && nodes.count >= (req.max_nodes ?? 5000)])
+ var result: [String: Any] = ["nodes": nodes, "truncated": readAccessibility && nodes.count >= (req.max_nodes ?? 5000)]
+ if req.screenshot ?? false {
+ result.merge(await captureScreenshot(pid: pid, windowID: req.window_id)) { _, new in new }
+ }
+ emit(result)
case "walkthrough":
let app = AXUIElementCreateApplication(pid)
var steps: [[String: Any]] = []
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 78881f82..87c08109 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -485,8 +485,13 @@ Owner: open · Status: todo
Golden rule 3: the result is evidence. Each fix needs a Mac to test on.
- [x] macOS: a denied Accessibility permission is reported as success with an empty tree (#240)
— claimed: mavericzz, branch bugfix/r5.6-accessibility-denied; PR #887
-- [ ] macOS: `runtime_ui_read` ignores `screenshot` (#248): the Swift helper declares it but
- never captures an image
+- [x] macOS: `runtime_ui_read` captures a requested screenshot (#248): one on-screen window
+ belonging to the pid, restricted by `window_id` when supplied; PNG/base64 up to 2048 px
+ per side. Missing Screen Recording permission, a missing window or a capture failure produces
+ an explicit screenshot limitation and partial evidence. Denied Accessibility permission with
+ the tree enabled (the default) returns a tool error before capture; `accessibility: false`
+ skips the tree. Requires macOS 14+ and existing Screen Recording permission; opens no dialog
+ — claimed: Codex, branch bugfix/r5.6-macos-screenshot
- [x] macOS: `runtime_ui_read` honours `accessibility: false` (#307): the Swift helper skips
the tree and its permission check, returns no nodes without truncation, and the evidence
records the flag and says the tree was skipped. Walkthroughs still require Accessibility
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 3ea593e8..64ddba7b 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -12,7 +12,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| Disabled chat backends | Naming a backend that is off refuses chat and either side of compare with a settings error and guidance, before API or coding-agent setup | Isolated hub regressions for disabled API and agent backends, both compare positions, and enabled/automatic controls. Invalid tunnel settings detect API setup before the guard. No live provider or agent was used |
| Runner-owned app windows | Runtime capture tries the launched process and its descendants; the captured window owner's PID is also used for the UI tree. Unrelated processes with matching names are excluded. Process discovery has a deadline, output cap and candidate limit | Hermetic regressions cover runner/child/grandchild ownership, unrelated windows, direct launches, cycles, malformed rows, caps and errors. A macOS process snapshot finds an owned child without opening a window. Windows and real Go GUI capture have not been run |
| New-project toolchains | New Python, Go, .NET, Maven, Gradle and Make projects use the same build catalogue as existing projects (`engine/src/toolchains.toml`). Shared launch recipes let screenshots, self-tests and Play start Python `main.py`, `app.py` or `__main__.py`, Go with a root `main.go`, and one root `.csproj`. Python uses a project-local virtual environment when present, resolves its executable to an absolute path even for relative project folders, and forces fresh syntax compilation; .NET passes app options after `--`. Manifest markers take priority over standalone Python files. Runtime window-capture requests normalize relative project and runner paths to absolute paths. Existing packaged programs, Rust, Electron and Godot keep launch priority. Multiple `.csproj` matches or a capped scan do not choose a project. Other layouts still need a packaged program or another launch recipe | Catalogue and launch regressions cover argv boundaries, ambiguous entrypoints, scan limits and Windows/local interpreter selection, including relative project folders and unchanged argument boundaries. Capture-request tests cover relative placements and PATH results, local interpreters and optional UI-tree output without opening a window. An owned interpreter stand-in runs the full new-project build/screenshot path, rejects failed builds, and verifies a failed screenshot cannot reuse an old PNG. An opt-in real Python 3.15.2 fixture on macOS passes build/screenshot checks, ignores invalid virtualenv code, and rejects a syntax error even when its mtime matches the cached version. Without `compileall -f` that same syntax-error probe incorrectly exits zero. Real Go/.NET/Maven/Gradle runs, Windows and GUI apps have not been verified for this change |
-| macOS optional UI tree | `runtime_ui_read` with `accessibility: false` skips the tree and its permission check, returns empty nodes without truncation, and records the flag and skipped read in its evidence (#307). Walkthroughs still require Accessibility. Screenshot capture remains open (#248) | Engine regression on macOS compiles and runs the real Swift helper with zero and one node limits, without reading another app's UI. No granted-permission tree read or walkthrough was run for this change |
+| macOS optional UI tree and screenshots | `runtime_ui_read` with `accessibility: false` skips the tree and its permission check, returns empty nodes without truncation, and records the skipped read (#307). Walkthroughs still require Accessibility. With `screenshot: true`, macOS 14+ returns one owned-by-pid window as PNG/base64, restricted by `window_id` when supplied; without it, the first matching on-screen window. Images are limited to 2048 px per side and 6 MiB PNG. Missing Screen Recording permission, a missing window or a capture failure is an explicit screenshot limitation with partial coverage (#248). Denied Accessibility permission returns a tool error before capture when the tree is enabled (the default); set `accessibility: false` to skip the tree. Permission dialogs are never opened | Engine regressions compile/run the real Swift helper: skipped trees at node limits 0/1, screenshot-off control, and impossible-window screenshot errors propagated to evidence. Live helper probe on macOS 27.2 captured only an owned AppKit fixture: valid 320 × 192 PNG (14,400 bytes), matching window id; screenshot-off returned no image/error. No granted-permission tree read, walkthrough, macOS 14 run or MCP transport run |
| DNS question boundaries | A question is retained only when its name, type and class are complete. A missing class byte marks the DNS message incomplete; preceding complete questions remain available, and incomplete questions do not enter the query inventory | Four packet regressions cover both truncation lengths, multiple questions, complete class values and the capture summary. No live capture was used |
| Reject impossible IPv4 header and total lengths | IPv4 decoding rejects impossible header lengths and reports incomplete base headers or options. | Synthetic byte fixtures in `pcap_ipv4_lengths` integration regressions. Cover 10–19 captured header bytes, total lengths below IHL, missing options, complete options, truncated transport headers with readable ports, and a cut UDP payload with both ports and its captured length preserved. |
| Validate the version in IPv6 frames | IPv6 decoding checks the packet version before reporting IPv6 facts, including captures declaring raw IPv6; explicit raw IPv4 likewise uses IPv4 validation. | Synthetic byte fixtures in `pcap_ipv6_version` integration regressions. Cover incorrect versions behind the IPv6 EtherType, mismatched explicit raw IPv4 and IPv6 link types, matching explicit and generic raw packets, and valid IPv6 traffic-class bits. |
diff --git a/docs/pitfalls.md b/docs/pitfalls.md
index 3d2c41d0..a6cd5d0d 100644
--- a/docs/pitfalls.md
+++ b/docs/pitfalls.md
@@ -193,6 +193,12 @@ PATH lookup can return a relative path too. Resolve workspace paths against the
current directory, look up only bare program names, and make the result absolute without
dereferencing the virtualenv symlink. Test the generated capture request without opening a GUI.
+**A screenshot helper aborted inside CoreGraphics.** The first macOS screenshot probe used
+ScreenCaptureKit from a command-line Swift helper without initializing AppKit's WindowServer
+connection. An owned-window capture aborted in `CGS_REQUIRE_INIT`, while no-window regressions
+passed. Initialize `NSApplication.shared` on the main actor before capture, and verify an actual
+owned-window PNG as well as missing-window errors.
+
**A model catalogue queried in the wrong project.** OpenCode V2's raw `api get /api/model` does
not reliably select the invoking CLI's directory. Use the `model.list` operation with an explicit
`location[directory]` parameter, and test that the returned Location matches it. Over SSH,