Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cua-driver-rs)(experimental): picture-in-picture agent preview (macOS native; Win/Linux stubs) (#1730)
Francesco Bonacci7594195a22c7
diff --git a/docs/content/docs/cua-driver/guide/getting-started/meta.json b/docs/content/docs/cua-driver/guide/getting-started/meta.jsonindex 413e0e7783..2865dc2fed 100644--- a/docs/content/docs/cua-driver/guide/getting-started/meta.json+++ b/docs/content/docs/cua-driver/guide/getting-started/meta.json@@ -3,5 +3,5 @@"description": "Get up and running with Cua Driver","icon": "Rocket","defaultOpen": true,- "pages": ["introduction", "installation", "quickstart", "windows-ssh", "linux", "autostart", "integrations", "swift-integration", "process-model", "comparison", "faq"]+ "pages": ["introduction", "installation", "quickstart", "windows-ssh", "linux", "autostart", "pip-preview", "integrations", "swift-integration", "process-model", "comparison", "faq"]}diff --git a/docs/content/docs/cua-driver/guide/getting-started/pip-preview.mdx b/docs/content/docs/cua-driver/guide/getting-started/pip-preview.mdxnew file mode 100644index 0000000000..4074e7afdc--- /dev/null+++ b/docs/content/docs/cua-driver/guide/getting-started/pip-preview.mdx@@ -0,0 +1,94 @@+---+title: PiP Preview (Experimental)+description: Always-on-top picture-in-picture window showing the agent's per-action screenshots and a one-line action label.+---++import { Callout } from 'fumadocs-ui/components/callout';++<Callout type="warn">+**Experimental — opt-in, default OFF.** macOS only today; Windows and Linux ship as compile-clean stubs that print a "not yet implemented" notice when `--experimental-pip` is on argv. The flag, geometry, and frame schema may change before the feature is promoted out of `experimental`. Don't build production tooling against it yet.+</Callout>++`--experimental-pip` opens a small always-on-top window next to your work that shows what the cua-driver agent is doing in real time: the post-action screenshot of the target window, plus a one-line label describing the tool call that produced it (`click element_index=2`, `type_text "hello world"`, etc.).++It's intended as a live "agent's-eye view" — a passive observation surface, not a debugger. The window updates on every action tool call; it doesn't continuously capture the desktop.++## Enabling it++Two ways. The persistent path uses the same `~/.cua-driver/config.json`+file that the `set_config` MCP tool writes to, so PiP survives across+daemon restarts without re-running `claude mcp add` with the flag in+the args list.++### A. Persistent — edit `~/.cua-driver/config.json` (recommended)++```json+{+ "experimental_pip": true,+ "experimental_pip_geometry": "320x200+24+24"+}+```++Both keys are optional; `experimental_pip_geometry` defaults to+`320x200` in the top-right corner. Restart your MCP client (or kill+the running `cua-driver` daemon) for the new config to take effect.++### B. One-off — CLI flag++```bash+# MCP server (stdio)+cua-driver mcp --experimental-pip++# HTTP / Unix-socket serve daemon+cua-driver serve --experimental-pip++# Override geometry+cua-driver serve --experimental-pip --experimental-pip-geometry 640x400+cua-driver serve --experimental-pip --experimental-pip-geometry 480x300+24+24+```++The geometry string is the standard X11 `WxH+X+Y` form. `+X+Y` is the+top-left origin of the window in screen points (AppKit's bottom-left+convention is hidden inside the backend). **CLI flags override+`config.json`** — they're not additive.++On startup you'll see:++```+⚗️ PiP preview enabled (experimental — macOS only today; see https://github.com/trycua/cua/issues for follow-up)+```++## What gets pushed++PiP receives a frame for the same set of tool calls the recording pipeline writes a `turn-NNNNN/screenshot.png` for — every non-read-only, non-meta call: `click`, `double_click`, `right_click`, `type_text`, `press_key`, `hotkey`, `scroll`, `drag`, `set_value`, `launch_app`, plus the get/refresh AX tools that take a fresh screenshot anyway.++The PNG bytes themselves come from the same `SCREENSHOT_FN` callback the recorder uses, so the live view always matches what a replay would show for that turn.++## Window properties (macOS)++- **Always-on-top:** `NSFloatingWindowLevel` — above your normal apps, below menus / accessibility overlays.+- **Never key:** `setBecomesKeyOnlyIfNeeded(true)` plus a transient / no-cycle collection behavior — the window never steals keyboard focus from your frontmost app.+- **Visible across all spaces:** `CanJoinAllSpaces | FullScreenAuxiliary | Stationary` — survives space switches and full-screen apps.+- **Closeable:** the red traffic-light button dismisses the window and decouples it from the session. Re-enabling means restarting the daemon with the flag.++## Platform support++| Platform | Status | Notes |+|---|---|---|+| macOS | Working | NSWindow + NSImageView, frame updates via `dispatch_async` to the main queue |+| Windows | Stub | `--experimental-pip` is accepted; backend logs "not yet implemented" and the daemon continues without a window |+| Linux | Stub | Same as Windows |++Track Win + Linux follow-up work via the [trycua/cua issue tracker](https://github.com/trycua/cua/issues).++## Non-goals (today)++- **Continuous capture.** PiP follows tool calls, not a frame rate. If you need a video, use `start_recording`.+- **Click-to-drag repositioning.** Window position is static for the session; use `--experimental-pip-geometry` if you need to move it.+- **Audio / recording-to-disk from PiP.** The recording feature already handles those; PiP is a live view only.++## Troubleshooting++- **Window never appears.** Make sure the cursor overlay is enabled (the AppKit event loop is shared) — if you passed `--no-overlay`, the main thread is parked and AppKit doesn't run. Workaround: drop `--no-overlay`.+- **Window appears but no frames.** Confirm a real tool call is landing — bare reads (`get_window_state`, `list_windows`) skip the push path. Try `cua-driver call launch_app '{"bundle_id":"com.apple.calculator"}'` against a running daemon.+- **Label is truncated.** Increase the width via `--experimental-pip-geometry 720x400`.diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lockindex e092bbaa41..b2069f67ca 100644--- a/libs/cua-driver/rust/Cargo.lock+++ b/libs/cua-driver/rust/Cargo.lock@@ -286,6 +286,7 @@ dependencies = ["flate2","image","libc",+ "pip-preview","platform-linux","platform-macos","platform-windows",@@ -1190,6 +1191,15 @@ version = "0.2.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"+[[package]]+name = "pip-preview"+version = "0.2.18"+dependencies = [+ "anyhow",+ "serde_json",+ "tracing",+]+[[package]]name = "pkg-config"version = "0.3.33"@@ -1207,6 +1217,7 @@ dependencies = ["cursor-overlay","image","libc",+ "pip-preview","serde","serde_json","thiserror",@@ -1236,6 +1247,7 @@ dependencies = ["objc2-app-kit","objc2-foundation","objc2-quartz-core",+ "pip-preview","screencapturekit","serde","serde_json",@@ -1257,6 +1269,7 @@ dependencies = ["cua-driver-core","cursor-overlay","image",+ "pip-preview","serde","serde_json","thiserror",diff --git a/libs/cua-driver/rust/Cargo.toml b/libs/cua-driver/rust/Cargo.tomlindex 6714c31fe3..26f50aec04 100644--- a/libs/cua-driver/rust/Cargo.toml+++ b/libs/cua-driver/rust/Cargo.toml@@ -9,6 +9,7 @@ members = ["crates/platform-linux","crates/cursor-overlay","crates/focus-monitor-win",+ "crates/pip-preview",][workspace.package]diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rsindex e0b7789b6f..1818092c82 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs@@ -14,6 +14,7 @@ pub mod cdp;pub mod element_cache;pub mod image_utils;pub mod page;+pub mod pip_hook;pub mod protocol;pub mod cursor_sampler;pub mod recording;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/pip_hook.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/pip_hook.rsnew file mode 100644index 0000000000..d2c426169f--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/pip_hook.rs@@ -0,0 +1,49 @@+//! PiP frame-push hook — registered once by `main.rs` when the+//! `--experimental-pip` flag is on argv.+//!+//! The trait + factory live in the `pip-preview` crate so the platform+//! backends can implement them without depending on `cua-driver-core`.+//! What lives here is just the per-process callback that the tool+//! dispatcher uses to push frames after each successful tool call —+//! a thin shim so `tool.rs` doesn't need to know about `pip-preview`+//! directly and we keep the dependency graph one-directional.+//!+//! The PNG bytes pushed through here come from the existing+//! `SCREENSHOT_FN` callback (the same source `screenshot.png` uses in+//! the recording pipeline), so PiP shows exactly what the recorder+//! captures.++use std::sync::OnceLock;++/// Synthesized per-call frame payload. Kept structurally identical+/// to `pip_preview::PipFrame` — duplicated here to keep `cua-driver-core`+/// from importing `pip-preview` (the dependency would be circular once+/// platform backends pull both crates in).+pub struct PipHookFrame {+ pub png_bytes: Vec<u8>,+ pub action_label: String,+ pub timestamp_ms: u64,+}++type PipPushFnBox = Box<dyn Fn(PipHookFrame) + Send + Sync>;+static PIP_PUSH_FN: OnceLock<PipPushFnBox> = OnceLock::new();++/// Register the platform-side push callback. `main.rs` calls this+/// once after starting the PiP backend.+pub fn set_pip_push_fn(f: impl Fn(PipHookFrame) + Send + Sync + 'static) {+ let _ = PIP_PUSH_FN.set(Box::new(f));+}++/// True when a PiP backend is wired up. Tool dispatcher uses this to+/// skip the screenshot-bytes path when nothing would consume the+/// frame (avoiding wasted capture work in the common --pip-off case).+pub fn pip_enabled() -> bool {+ PIP_PUSH_FN.get().is_some()+}++/// Push a frame to the PiP window. No-op when no backend is registered.+pub fn push_pip_frame(frame: PipHookFrame) {+ if let Some(f) = PIP_PUSH_FN.get() {+ f(frame);+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rsindex 423ad3ba5b..43ed3ca976 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs@@ -35,6 +35,14 @@ pub fn set_screenshot_fn(f: impl Fn(Option<u64>, Option<i64>) -> Option<Vec<u8>>let _ = SCREENSHOT_FN.set(Box::new(f));}+/// Invoke the registered screenshot callback. Returns `None` when no+/// callback was registered or when the platform capture failed. Used+/// by the PiP push hook (and by anything else that wants to share the+/// per-turn screenshot pipeline without duplicating the platform glue).+pub fn screenshot_for(window_id: Option<u64>, pid: Option<i64>) -> Option<Vec<u8>> {+ SCREENSHOT_FN.get().and_then(|f| f(window_id, pid))+}+// ── Platform click-marker callback ───────────────────────────────────────────//// Takes (png_bytes, cx, cy) and returns modified PNG bytes with a red crosshairdiff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rsindex 1da27d6835..7fcef7fc5d 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs@@ -7,13 +7,15 @@ use async_trait::async_trait;use serde_json::Value;use crate::{+ pip_hook,protocol::{Content, ToolResult},- recording::{now_ms, RecordingSession},+ recording::{now_ms, screenshot_for, RecordingSession},recording_tools::{GetRecordingStateTool, ReplayTrajectoryTool, StartRecordingTool,StopRecordingTool,init_replay_registry,},+ tool_args::ArgsExt,};/// Metadata for a single tool.@@ -163,6 +165,25 @@ impl ToolRegistry {self.recording.record(name, &args, result_text, start_ms);}+ // Experimental PiP push — only when --experimental-pip is on argv+ // (otherwise `pip_enabled()` is false and we skip the screenshot+ // entirely to avoid wasted capture work). We push for the same set+ // of action tools the recording pipeline cares about (non-read-only,+ // not the recording-control meta-tools) so the live view matches+ // what the recorder would have captured for the turn.+ if pip_hook::pip_enabled() && should_record {+ let window_id = args.opt_u64("window_id");+ let pid = args.opt_i64("pid");+ if let Some(png_bytes) = screenshot_for(window_id, pid) {+ let label = synthesize_action_label(name, &args);+ pip_hook::push_pip_frame(pip_hook::PipHookFrame {+ png_bytes,+ action_label: label,+ timestamp_ms: now_ms(),+ });+ }+ }+result}}@@ -172,3 +193,50 @@ impl Default for ToolRegistry {Self::new()}}++/// Build a short, human-friendly label for the PiP overlay from the+/// tool name + raw args. Kept under ~60 chars so the macOS NSTextField+/// has room without truncation at default geometry.+fn synthesize_action_label(tool_name: &str, args: &Value) -> String {+ let arg = |k: &str| -> Option<String> {+ args.get(k).map(|v| match v {+ Value::String(s) => s.clone(),+ other => other.to_string(),+ })+ };+ let summary = match tool_name {+ "click" | "double_click" | "right_click" => {+ if let Some(idx) = args.opt_u64("element_index") {+ format!("element_index={idx}")+ } else if let (Some(x), Some(y)) = (args.opt_f64("x"), args.opt_f64("y")) {+ format!("({x:.0}, {y:.0})")+ } else {+ "".into()+ }+ }+ "type_text" => {+ let text = arg("text").unwrap_or_default();+ let trimmed: String = text.chars().take(40).collect();+ if text.chars().count() > 40 {+ format!("\"{trimmed}…\"")+ } else {+ format!("\"{trimmed}\"")+ }+ }+ "press_key" | "hotkey" => arg("key").or_else(|| arg("keys")).unwrap_or_default(),+ "scroll" => format!(+ "dx={} dy={}",+ arg("dx").unwrap_or_else(|| "0".into()),+ arg("dy").unwrap_or_else(|| "0".into())+ ),+ "drag" => "drag".into(),+ "set_value" => arg("value").unwrap_or_default(),+ "launch_app" => arg("bundle_id").or_else(|| arg("name")).unwrap_or_default(),+ _ => String::new(),+ };+ if summary.is_empty() {+ tool_name.to_owned()+ } else {+ format!("{tool_name}: {summary}")+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver/Cargo.tomlindex 67b77dc233..affa006490 100644--- a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml+++ b/libs/cua-driver/rust/crates/cua-driver/Cargo.toml@@ -18,6 +18,7 @@ tracing = { workspace = true }tracing-subscriber = { workspace = true }cua-driver-core = { path = "../cua-driver-core" }cursor-overlay = { path = "../cursor-overlay" }+pip-preview = { path = "../pip-preview" }async-trait = "0.1"base64 = { workspace = true }uuid = { workspace = true }diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rsindex ccc4528799..88c3f338c2 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs@@ -110,6 +110,10 @@ const VALUE_FLAGS: &[&str] = &["--cursor-icon", "--cursor-id", "--cursor-palette","--glide-ms", "--dwell-ms", "--idle-hide-ms","--screenshot-out-file", "--client", "--socket", "--pid-file", "--type",+ // Experimental PiP preview — value flag for the optional geometry+ // override (--experimental-pip itself is a bare flag and doesn't+ // need to be listed here).+ "--experimental-pip-geometry",];/// Parse the first non-flag positional argument from argv to determine which@@ -152,6 +156,14 @@ pub fn parse_command() -> Command {println!();println!("doctor options:");println!(" --json Emit the probe report as JSON for scripting.");+ println!();+ println!("experimental options (default: off):");+ println!(" --experimental-pip Show a small always-on-top window with the latest");+ println!(" post-action screenshot + a 1-line label. macOS only");+ println!(" today; Win/Linux print a not-yet-implemented notice.");+ println!(" --experimental-pip-geometry WxH[+X+Y] Override window size (and optional top-left");+ println!(" origin). Defaults to 480x360 in the top-right");+ println!(" corner of the main display.");std::process::exit(0);}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rsindex 88437a7aae..28a177f002 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs@@ -72,6 +72,73 @@ fn emit_entry_telemetry(command: &cli::Command) {}}+/// Wire up the experimental picture-in-picture preview window.+///+/// Called from every long-running entry point (Serve and Mcp on all+/// platforms; the `Call` arm intentionally skips PiP since the+/// per-call binaries don't keep an AppKit/event loop alive long+/// enough to be useful).+///+/// No-op when `--experimental-pip` is not on argv. On Windows / Linux+/// the factory returns "not yet implemented" — we log and continue+/// without a window so the rest of the daemon keeps working.+fn maybe_init_pip() {+ let cfg = match pip_preview::default_config_path() {+ Some(p) => pip_preview::PipConfig::from_args_and_file(&p),+ None => pip_preview::PipConfig::from_args(),+ };+ if !cfg.enabled {+ return;+ }++ // Register the platform factory. The set is idempotent so multiple+ // entry points calling this in the same process is safe.+ #[cfg(target_os = "macos")]+ pip_preview::set_pip_backend_factory(+ Box::new(platform_macos::pip::MacosPipBackendFactory),+ );+ #[cfg(target_os = "windows")]+ pip_preview::set_pip_backend_factory(+ Box::new(platform_windows::pip::WindowsPipBackendFactory),+ );+ #[cfg(target_os = "linux")]+ pip_preview::set_pip_backend_factory(+ Box::new(platform_linux::pip::LinuxPipBackendFactory),+ );++ match pip_preview::start_pip(&cfg) {+ Ok(backend) => {+ // Bridge: when the tool dispatcher in cua-driver-core wants+ // to push a frame, forward to the live backend handle.+ // We move the Box into a static Mutex<Option<...>> so the+ // closure can re-borrow on every call without taking+ // ownership of the trait object.+ use std::sync::Mutex as StdMutex;+ static BACKEND: std::sync::OnceLock<StdMutex<Option<Box<dyn pip_preview::PipBackend>>>> =+ std::sync::OnceLock::new();+ let _ = BACKEND.set(StdMutex::new(Some(backend)));+ cua_driver_core::pip_hook::set_pip_push_fn(|frame| {+ if let Some(slot) = BACKEND.get() {+ if let Some(b) = slot.lock().unwrap().as_ref() {+ b.push_frame(pip_preview::PipFrame {+ png_bytes: frame.png_bytes,+ action_label: frame.action_label,+ timestamp_ms: frame.timestamp_ms,+ });+ }+ }+ });+ eprintln!(+ "⚗️ PiP preview enabled (experimental — macOS only today; \+ see https://github.com/trycua/cua/issues for follow-up)"+ );+ }+ Err(e) => {+ eprintln!("⚗️ PiP preview requested but unavailable: {e}");+ }+ }+}+// ── macOS entry-point ─────────────────────────────────────────────────────#[cfg(target_os = "macos")]@@ -181,10 +248,35 @@ fn main() {cua_driver_core::video::set_video_backend_factory(Box::new(platform_macos::video_sckit::SckitVideoBackendFactory),);+ let pip_cfg = match pip_preview::default_config_path() {+ Some(p) => pip_preview::PipConfig::from_args_and_file(&p),+ None => pip_preview::PipConfig::from_args(),+ };+ maybe_init_pip();let reg = Arc::new(platform_macos::register_tools());reg.init_self_weak();let sp = socket.unwrap_or_else(serve::default_socket_path);let pid_path = serve::default_pid_file_path();+ // PiP needs the AppKit main run loop to process the+ // dispatch_async_f calls that push frames into NSImageView.+ // When --experimental-pip is on, move the serve loop onto+ // a background thread and park the main thread in+ // NSApplication.run() so the dispatched blocks actually+ // execute. Without this, frames queue forever and the+ // window stays blank. The non-PiP path keeps the original+ // run-on-main semantics so we don't change behaviour for+ // existing users.+ if pip_cfg.enabled {+ std::thread::Builder::new()+ .name("cua-serve".into())+ .spawn(move || {+ serve::run_serve_cmd(reg, &sp, Some(&pid_path));+ std::process::exit(0);+ })+ .expect("spawn serve thread");+ platform_macos::pip::run_appkit_main_loop();+ return;+ }serve::run_serve_cmd(reg, &sp, Some(&pid_path));return;}@@ -314,6 +406,7 @@ fn main() {cua_driver_core::video::set_video_backend_factory(Box::new(platform_macos::video_sckit::SckitVideoBackendFactory),);+ maybe_init_pip();std::thread::Builder::new().name("cua-mcp".into())@@ -405,6 +498,7 @@ fn main() -> anyhow::Result<()> {let cursor_cfg = cursor_overlay::CursorConfig::from_args();let reg = Arc::new(build_registry(cursor_cfg));reg.init_self_weak();+ maybe_init_pip();let sp = socket.unwrap_or_else(serve::default_socket_path);let pid_path = serve::default_pid_file_path();// run_serve_cmd builds its own runtime; must run on a fresh thread.@@ -523,6 +617,7 @@ async fn async_main() -> anyhow::Result<()> {let registry = Arc::new(build_registry(cursor_cfg));registry.init_self_weak();+ maybe_init_pip();cua_driver_core::server::run(registry).await?;Ok(())}diff --git a/libs/cua-driver/rust/crates/pip-preview/Cargo.toml b/libs/cua-driver/rust/crates/pip-preview/Cargo.tomlnew file mode 100644index 0000000000..5d504210d7--- /dev/null+++ b/libs/cua-driver/rust/crates/pip-preview/Cargo.toml@@ -0,0 +1,9 @@+[package]+name = "pip-preview"+version.workspace = true+edition.workspace = true++[dependencies]+anyhow = { workspace = true }+tracing = { workspace = true }+serde_json = { workspace = true }diff --git a/libs/cua-driver/rust/crates/pip-preview/src/lib.rs b/libs/cua-driver/rust/crates/pip-preview/src/lib.rsnew file mode 100644index 0000000000..e54c9698b5--- /dev/null+++ b/libs/cua-driver/rust/crates/pip-preview/src/lib.rs@@ -0,0 +1,284 @@+//! pip-preview — shared types + trait for the experimental+//! picture-in-picture agent preview window.+//!+//! The PiP window is an opt-in, always-on-top floating window that+//! shows what the cua-driver agent just did: a post-action screenshot+//! of the target window plus a one-line label summarising the tool+//! call. It mirrors the architecture used by `cursor-overlay` (shared+//! config/types here, platform-specific renderer in each `platform-*`+//! crate) and the registration pattern used by `cua_driver_core::video`+//! (a `OnceLock` factory set once at startup by `main.rs`).+//!+//! macOS is the first working implementation (NSWindow + NSImageView).+//! Windows + Linux ship as compile-clean stubs whose `start()` returns+//! a clear "not yet implemented" error so the rest of the daemon+//! continues without a PiP window.++use std::sync::OnceLock;++/// Canonical `~/.cua-driver/config.json` path matching what the per-platform+/// `set_config` tools write to. Returns `None` when `$HOME` is unset+/// (sandboxed CI).+pub fn default_config_path() -> Option<std::path::PathBuf> {+ std::env::var("HOME")+ .ok()+ .map(|h| std::path::PathBuf::from(h).join(".cua-driver").join("config.json"))+}++/// Merge a single `key`/`value` into `~/.cua-driver/config.json`,+/// preserving any other keys that are already there. Used by the+/// per-platform `set_config` tools to persist `experimental_pip` /+/// `experimental_pip_geometry` so the next daemon restart picks them up.+pub fn write_config_key(key: &str, value: serde_json::Value) -> Result<(), String> {+ let path = default_config_path().ok_or_else(|| "$HOME is not set".to_string())?;+ let mut json: serde_json::Value = path+ .exists()+ .then(|| std::fs::read_to_string(&path).ok())+ .flatten()+ .and_then(|t| serde_json::from_str(&t).ok())+ .unwrap_or_else(|| serde_json::json!({}));+ json[key] = value;+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;+ }+ let body = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;+ std::fs::write(&path, body).map_err(|e| e.to_string())?;+ Ok(())+}++/// Read `experimental_pip` + `experimental_pip_geometry` from the+/// config file, falling back to defaults when missing or malformed.+/// Surfaced by the per-platform `get_config` tools alongside the+/// in-memory `DriverConfig` fields.+pub fn read_pip_keys_from_file() -> (bool, Option<String>) {+ let path = match default_config_path() {+ Some(p) => p,+ None => return (false, None),+ };+ let text = match std::fs::read_to_string(&path) {+ Ok(t) => t,+ Err(_) => return (false, None),+ };+ let json: serde_json::Value = match serde_json::from_str(&text) {+ Ok(v) => v,+ Err(_) => return (false, None),+ };+ let enabled = json.get("experimental_pip").and_then(|v| v.as_bool()).unwrap_or(false);+ let geometry = json.get("experimental_pip_geometry")+ .and_then(|v| v.as_str())+ .map(|s| s.to_owned());+ (enabled, geometry)+}++/// Geometry of the PiP window, in screen points (top-left origin).+///+/// Parsed from `--experimental-pip-geometry WxH+X+Y`. `x` / `y` are+/// optional; when `None` the platform backend picks a sensible+/// "top-right corner with a small inset" default so a user enabling+/// the feature without any geometry flags still sees a window.+#[derive(Debug, Clone, Copy)]+pub struct PipGeometry {+ pub width: u32,+ pub height: u32,+ pub x: Option<i32>,+ pub y: Option<i32>,+}++impl Default for PipGeometry {+ fn default() -> Self {+ Self {+ width: 320,+ height: 200,+ x: None,+ y: None,+ }+ }+}++impl PipGeometry {+ /// Parse `WxH` or `WxH+X+Y` (matching the common X11 geometry form).+ /// Returns `None` on any parse failure so the caller can fall back+ /// to defaults without panicking.+ pub fn parse(s: &str) -> Option<Self> {+ // Split off the optional `+X+Y` tail first so the leading+ // `WxH` parses cleanly even when no position is provided.+ let (size, pos): (&str, Option<(i32, i32)>) = match s.find('+') {+ Some(i) => {+ let tail = &s[i + 1..];+ let mut parts = tail.split('+');+ let x = parts.next()?.parse().ok()?;+ let y = parts.next()?.parse().ok()?;+ (&s[..i], Some((x, y)))+ }+ None => (s, None),+ };+ let mut wh = size.split('x');+ let w: u32 = wh.next()?.parse().ok()?;+ let h: u32 = wh.next()?.parse().ok()?;+ Some(Self {+ width: w,+ height: h,+ x: pos.map(|p| p.0),+ y: pos.map(|p| p.1),+ })+ }+}++/// Configuration for the PiP window. Built by `main.rs` from CLI+/// flags and handed to `PipBackendFactory::start`.+#[derive(Debug, Clone)]+pub struct PipConfig {+ /// `--experimental-pip` is on argv. The factory is only consulted+ /// when this is true; the field is kept here so backends that+ /// share a `start()` path can early-return.+ pub enabled: bool,+ pub geometry: PipGeometry,+ /// Window title — kept here so the "experimental" label stays in+ /// one place. Defaults to "cua-driver — agent view (experimental)".+ pub title: String,+}++impl Default for PipConfig {+ fn default() -> Self {+ Self {+ enabled: false,+ geometry: PipGeometry::default(),+ title: "cua-driver — agent view (experimental)".to_owned(),+ }+ }+}++impl PipConfig {+ /// Parse the PiP-related CLI flags out of `std::env::args()`.+ /// Recognised flags (all opt-in):+ /// ```text+ /// --experimental-pip+ /// --pip (short alias)+ /// --experimental-pip-geometry WxH | WxH+X+Y+ /// ```+ /// Unknown flags are ignored so this never conflicts with the+ /// other arg-parser passes (CursorConfig, the subcommand router).+ pub fn from_args() -> Self {+ let args: Vec<String> = std::env::args().collect();+ Self::parse(&args[1..])+ }++ pub fn parse(args: &[String]) -> Self {+ let mut cfg = PipConfig::default();+ let mut i = 0usize;+ while i < args.len() {+ match args[i].as_str() {+ "--experimental-pip" | "--pip" => cfg.enabled = true,+ "--experimental-pip-geometry" => {+ if let Some(geom) = args.get(i + 1).and_then(|s| PipGeometry::parse(s)) {+ cfg.geometry = geom;+ i += 1;+ }+ }+ _ => {}+ }+ i += 1;+ }+ cfg+ }++ /// Resolve the config from (in order of precedence, low → high):+ ///+ /// defaults → `~/.cua-driver/config.json` keys+ /// (`experimental_pip` bool, `experimental_pip_geometry` string)+ /// → CLI flags+ ///+ /// Lets users persist `--experimental-pip` across daemon restarts by+ /// editing `~/.cua-driver/config.json` once, instead of re-running+ /// `claude mcp add` with the flag baked into the args list.+ /// Malformed or missing file falls back to the next layer silently.+ pub fn from_args_and_file(config_path: &std::path::Path) -> Self {+ let mut cfg = PipConfig::default();+ if let Ok(text) = std::fs::read_to_string(config_path) {+ if let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) {+ if let Some(b) = json.get("experimental_pip").and_then(|v| v.as_bool()) {+ cfg.enabled = b;+ }+ if let Some(s) = json.get("experimental_pip_geometry").and_then(|v| v.as_str()) {+ if let Some(g) = PipGeometry::parse(s) {+ cfg.geometry = g;+ }+ }+ }+ }+ // CLI args override anything in the file.+ let args: Vec<String> = std::env::args().collect();+ let cli = PipConfig::parse(&args[1..]);+ if cli.enabled {+ cfg.enabled = true;+ }+ // CLI geometry only overrides when explicitly passed — detect by+ // diffing against PipGeometry::default() (the parse() entry point+ // returns the default when no flag is present).+ if cli.geometry.width != PipGeometry::default().width+ || cli.geometry.height != PipGeometry::default().height+ || cli.geometry.x.is_some()+ || cli.geometry.y.is_some()+ {+ cfg.geometry = cli.geometry;+ }+ cfg+ }+}++/// A single frame pushed into the PiP window after a tool call lands.+///+/// `png_bytes` are the raw PNG bytes produced by the platform+/// screenshot callback — the same path that powers `screenshot.png`+/// in the recording pipeline, so PiP shows exactly what the recorder+/// sees.+#[derive(Debug, Clone)]+pub struct PipFrame {+ pub png_bytes: Vec<u8>,+ /// One-line summary shown overlayed on the frame, e.g.+ /// `click element_index=2` or `type_text "hello world"`.+ pub action_label: String,+ /// Wall-clock timestamp (ms since Unix epoch) — used by backends+ /// that want to show "last update Xs ago" in the title bar.+ pub timestamp_ms: u64,+}++/// A live PiP window. Owned by `main.rs` for the lifetime of the+/// process; `shutdown()` consumes it and closes the window.+pub trait PipBackend: Send + Sync {+ /// Push a new frame to the window. Non-blocking; the backend is+ /// responsible for dispatching the actual draw to whatever thread+ /// its UI toolkit requires (the macOS impl dispatches to the main+ /// queue via `dispatch_async`).+ fn push_frame(&self, frame: PipFrame);++ /// Close the window and release native resources. Called from+ /// `main.rs` on shutdown.+ fn shutdown(self: Box<Self>);+}++/// Spawns a fresh PiP window. Registered once at startup via+/// `set_pip_backend_factory`.+pub trait PipBackendFactory: Send + Sync {+ fn start(&self, cfg: &PipConfig) -> anyhow::Result<Box<dyn PipBackend>>;+}++static PIP_FACTORY: OnceLock<Box<dyn PipBackendFactory>> = OnceLock::new();++/// Register the platform's PiP backend factory. Idempotent — subsequent+/// calls are silently ignored, matching the other startup-callback+/// setters in `cua_driver_core`.+pub fn set_pip_backend_factory(factory: Box<dyn PipBackendFactory>) {+ let _ = PIP_FACTORY.set(factory);+}++/// Start a PiP window using the registered backend. Returns an error+/// when no backend has been registered for this platform — `main.rs`+/// treats that as "PiP unavailable on this OS" and continues without+/// the window.+pub fn start_pip(cfg: &PipConfig) -> anyhow::Result<Box<dyn PipBackend>> {+ let factory = PIP_FACTORY+ .get()+ .ok_or_else(|| anyhow::anyhow!("no PiP backend registered for this platform"))?;+ factory.start(cfg)+}diff --git a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml b/libs/cua-driver/rust/crates/platform-linux/Cargo.tomlindex bbe6c6ef0f..4189eca8c6 100644--- a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml+++ b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml@@ -13,6 +13,7 @@ tracing = { workspace = true }async-trait = "0.1"cua-driver-core = { path = "../cua-driver-core" }cursor-overlay = { path = "../cursor-overlay" }+pip-preview = { path = "../pip-preview" }# tiny-skia for cursor rendering (shared cross-platform)tiny-skia = { version = "0.11", default-features = false, features = ["std"] }diff --git a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs b/libs/cua-driver/rust/crates/platform-linux/src/lib.rsindex f8350614af..525e251e54 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs@@ -14,6 +14,7 @@ use cua_driver_core::tool::ToolRegistry;pub mod tools;pub mod overlay;+pub mod pip;#[cfg(target_os = "linux")]pub mod x11;diff --git a/libs/cua-driver/rust/crates/platform-linux/src/pip/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/pip/mod.rsnew file mode 100644index 0000000000..805c0eb4e6--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/pip/mod.rs@@ -0,0 +1,23 @@+//! Linux picture-in-picture preview stub.+//!+//! The Linux implementation is a follow-up to the experimental macOS+//! drop. Plan: GTK4 always-on-top utility window under X11/XWayland,+//! with a Wayland-native fallback via `wlr-layer-shell` where+//! supported. Tracking issue linked in the docs.+//!+//! Until that lands, `start()` returns a clear error so `main.rs`+//! can log "PiP unavailable on this platform" and continue without+//! the window.++use pip_preview::{PipBackend, PipBackendFactory, PipConfig};++pub struct LinuxPipBackendFactory;++impl PipBackendFactory for LinuxPipBackendFactory {+ fn start(&self, _cfg: &PipConfig) -> anyhow::Result<Box<dyn PipBackend>> {+ Err(anyhow::anyhow!(+ "PiP preview is not yet implemented on Linux — track \+ trycua/cua follow-up issue for status"+ ))+ }+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rsindex 08c78b16de..d99cf700dd 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs@@ -1631,12 +1631,15 @@ impl Tool for GetConfigTool {}async fn invoke(&self, _args: Value) -> ToolResult {let cfg = self.state.config.read().unwrap();+ let (pip_enabled, pip_geometry) = pip_preview::read_pip_keys_from_file();ToolResult::text("cua-driver-rs configuration").with_structured(json!({"version": env!("CARGO_PKG_VERSION"),"platform": "linux","capture_mode": cfg.capture_mode,- "max_image_dimension": cfg.max_image_dimension+ "max_image_dimension": cfg.max_image_dimension,+ "experimental_pip": pip_enabled,+ "experimental_pip_geometry": pip_geometry}))}}@@ -1653,10 +1656,16 @@ impl Tool for SetConfigTool {fn def(&self) -> &ToolDef {SCFG_DEF.get_or_init(|| ToolDef {name: "set_config".into(),- description: "Update cua-driver-rs configuration. Changes take effect immediately.".into(),+ description: "Update cua-driver-rs configuration. capture_mode / \+ max_image_dimension take effect immediately. The experimental_pip \+ keys persist to ~/.cua-driver/config.json and apply on next \+ daemon restart (the PiP backend is initialised once at startup; \+ Linux ships only the trait stub today — see issue #1729).".into(),input_schema: json!({"type":"object","properties":{"capture_mode":{"type":"string","enum":["som","vision","ax"],"description":"Default capture mode for get_window_state."},- "max_image_dimension":{"type":"integer","description":"Max dimension for screenshot resizing (0 = no limit)."}+ "max_image_dimension":{"type":"integer","description":"Max dimension for screenshot resizing (0 = no limit)."},+ "experimental_pip":{"type":"boolean","description":"Enable the experimental PiP preview window (applies next restart; Linux backend stubbed)."},+ "experimental_pip_geometry":{"type":"string","description":"PiP window size + optional position in `WxH` or `WxH+X+Y` form."}},"additionalProperties":false}),read_only: false, destructive: false, idempotent: true, open_world: false,})@@ -1673,15 +1682,35 @@ impl Tool for SetConfigTool {cfg.max_image_dimension = dim as u32;parts.push(format!("max_image_dimension={dim}"));}+ if let Some(enabled) = args.get("experimental_pip").and_then(|v| v.as_bool()) {+ if let Err(e) = pip_preview::write_config_key("experimental_pip", Value::Bool(enabled)) {+ return ToolResult::error(format!("failed to persist experimental_pip: {e}"));+ }+ parts.push(format!("experimental_pip={enabled} (next restart)"));+ }+ if let Some(geom) = args.opt_str("experimental_pip_geometry") {+ if pip_preview::PipGeometry::parse(&geom).is_none() {+ return ToolResult::error(format!(+ "experimental_pip_geometry `{geom}` is not a valid WxH or WxH+X+Y string"+ ));+ }+ if let Err(e) = pip_preview::write_config_key("experimental_pip_geometry", Value::String(geom.clone())) {+ return ToolResult::error(format!("failed to persist experimental_pip_geometry: {e}"));+ }+ parts.push(format!("experimental_pip_geometry={geom} (next restart)"));+ }let msg = if parts.is_empty() {"Config unchanged (no known parameters).".to_owned()} else {format!("Config updated: {}", parts.join(", "))};+ let (pip_enabled, pip_geometry) = pip_preview::read_pip_keys_from_file();ToolResult::text(msg).with_structured(json!({"capture_mode": cfg.capture_mode,- "max_image_dimension": cfg.max_image_dimension+ "max_image_dimension": cfg.max_image_dimension,+ "experimental_pip": pip_enabled,+ "experimental_pip_geometry": pip_geometry}))}}diff --git a/libs/cua-driver/rust/crates/platform-macos/Cargo.toml b/libs/cua-driver/rust/crates/platform-macos/Cargo.tomlindex 0f46e869c1..944ba230c9 100644--- a/libs/cua-driver/rust/crates/platform-macos/Cargo.toml+++ b/libs/cua-driver/rust/crates/platform-macos/Cargo.toml@@ -16,6 +16,7 @@ async-trait = "0.1"uuid = { workspace = true }cua-driver-core = { path = "../cua-driver-core" }cursor-overlay = { path = "../cursor-overlay" }+pip-preview = { path = "../pip-preview" }[target.'cfg(target_os = "macos")'.dependencies]# macOS system bindings@@ -37,6 +38,11 @@ objc2-app-kit = { version = "0.2", features = ["NSApplication", "NSWindow", "NSScreen", "NSColor","NSEvent", "NSRunningApplication", "NSWorkspace","NSView", "NSGraphicsContext", "NSResponder",+ # Picture-in-picture preview window (experimental) — NSImageView /+ # NSImage for the post-action screenshot, NSTextField for the+ # one-line action label, NSPanel/NSImageCell are reachable via+ # transitive deps.+ "NSImage", "NSImageView", "NSTextField", "NSControl", "NSCell","block2", "libc",] }diff --git a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs b/libs/cua-driver/rust/crates/platform-macos/src/lib.rsindex b1ee523510..bee67dc831 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs@@ -34,6 +34,8 @@ pub mod tools;pub mod recording_hooks;#[cfg(target_os = "macos")]pub mod video_sckit;+#[cfg(target_os = "macos")]+pub mod pip;use cua_driver_core::tool::ToolRegistry;diff --git a/libs/cua-driver/rust/crates/platform-macos/src/pip/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/pip/mod.rsnew file mode 100644index 0000000000..3184f84acd--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-macos/src/pip/mod.rs@@ -0,0 +1,425 @@+//! macOS picture-in-picture preview window.+//!+//! Floating NSWindow with an NSImageView showing the most recent+//! post-action screenshot and an NSTextField with a one-line label+//! describing the action that produced it.+//!+//! ## Threading model+//!+//! Mirrors `cursor/overlay.rs`:+//!+//! - The MCP/tokio server runs on a background thread.+//! - AppKit MUST run on the main thread, which `cua-driver/src/main.rs`+//! parks in `NSApplication.run()` for the cursor overlay.+//! - `push_frame()` is called from arbitrary tokio tasks. It packages+//! the frame into a heap-allocated `Box` and posts the actual UI+//! update onto the main queue via `dispatch_async_f`. The block+//! then constructs an `NSImage` from the PNG bytes and calls+//! `[imageView setImage:]` + `[label setStringValue:]`.+//!+//! ## Window properties+//!+//! - `NSWindowCollectionBehaviorCanJoinAllSpaces | FullScreenAuxiliary |+//! Stationary | Transient | IgnoresCycle`+//! - `level = .floating` (kCGFloatingWindowLevel, between normal apps+//! and dock; high enough to stay visible, low enough not to obscure+//! menus or accessibility overlays).+//! - `setIgnoresMouseEvents(false)` — user can click the red close+//! button. Backend cleanup happens on `shutdown()`; closing the+//! window manually decouples it from the session as the spec+//! requires.+//! - No activation: `setHidesOnDeactivate(false)` and+//! `setBecomesKeyOnlyIfNeeded(true)` so the window never steals+//! keyboard focus from the user's frontmost app.+//!+//! ## Init lifecycle+//!+//! Because the cursor overlay already owns the main thread when+//! enabled, `MacosPipBackend::start` cannot block on it. Instead it+//! posts the window-creation block onto the main queue and returns+//! immediately. The first frame may arrive before the window exists;+//! that's fine — the push path reads the window pointer from a+//! `Mutex<Option<usize>>` and silently no-ops until init finishes.++use std::ffi::c_void;+use std::sync::Mutex;++use pip_preview::{PipBackend, PipBackendFactory, PipConfig, PipFrame};++// ── CGColor objc2 encoding shim ────────────────────────────────────────────+//+// `[NSColor CGColor]` returns a `CGColorRef` whose Objective-C type encoding+// is `^{CGColor=}`. objc2's strict msg_send! enforcement rejects bare+// `*mut c_void` (`^v`) for both sides of that call. Declare a phantom+// struct with the matching encoding so we can typed-cast through it+// without pulling in a wider CGColor binding crate.++#[repr(C)]+struct CGColor {+ _opaque: [u8; 0],+}++// RefEncode supplies an automatic Encode impl for `*mut CGColor` /+// `*const CGColor` via objc2's blanket — that's the route msg_send! needs+// for both setting layer.backgroundColor and reading [NSColor CGColor].+// `ENCODING_REF` is the encoding for one level of indirection, so the+// pointer wrap goes here (objc encoding `^{CGColor=}`).+unsafe impl objc2::RefEncode for CGColor {+ const ENCODING_REF: objc2::Encoding =+ objc2::Encoding::Pointer(&objc2::Encoding::Struct("CGColor", &[]));+}++// ── Native AppKit pointer cell ─────────────────────────────────────────────+//+// Window, image view, and label pointers are stashed as `usize` so+// `Send` works (raw `*mut AnyObject` is `!Send`). The actual deref ++// `msg_send!` happens only on the main queue inside the dispatched+// block, so there is no thread-safety hazard from the Send promise.++struct NativeHandles {+ window: usize,+ image_view: usize,+ label: usize,+}++static HANDLES: Mutex<Option<NativeHandles>> = Mutex::new(None);++// ── libdispatch glue — same shape as cursor::overlay ──────────────────────++#[link(name = "dispatch", kind = "dylib")]+extern "C" {+ static _dispatch_main_q: u8;+ fn dispatch_async_f(+ queue: *const c_void,+ context: *mut c_void,+ work: unsafe extern "C" fn(*mut c_void),+ );+}++fn dispatch_to_main<T: Send + 'static>(payload: T, cb: unsafe extern "C" fn(*mut c_void)) {+ let boxed = Box::new(payload);+ unsafe {+ let main_queue = &raw const _dispatch_main_q as *const c_void;+ dispatch_async_f(main_queue, Box::into_raw(boxed) as *mut c_void, cb);+ }+}++// ── Backend impl ──────────────────────────────────────────────────────────++pub struct MacosPipBackend;++impl PipBackend for MacosPipBackend {+ fn push_frame(&self, frame: PipFrame) {+ // No window yet? Drop the frame silently — start() dispatches+ // the create block onto the main queue and the very first+ // tool call can race that block.+ if HANDLES.lock().unwrap().is_none() {+ return;+ }+ dispatch_to_main(frame, push_frame_cb);+ }++ fn shutdown(self: Box<Self>) {+ dispatch_to_main((), shutdown_cb);+ }+}++unsafe extern "C" fn push_frame_cb(ctx: *mut c_void) {+ use objc2::runtime::AnyObject;+ use objc2::{class, msg_send};++ let frame: PipFrame = *Box::from_raw(ctx as *mut PipFrame);++ let (image_view_ptr, label_ptr) = {+ let guard = HANDLES.lock().unwrap();+ match guard.as_ref() {+ Some(h) => (h.image_view, h.label),+ None => return,+ }+ };++ // Construct NSData from the PNG bytes, then NSImage from NSData.+ // `dataWithBytes:length:` copies into a fresh NSData so the input+ // `Vec<u8>` can be freed at the end of this block.+ let png_ptr = frame.png_bytes.as_ptr() as *const c_void;+ let png_len = frame.png_bytes.len();+ let ns_data: *mut AnyObject = msg_send![+ class!(NSData),+ dataWithBytes: png_ptr+ length: png_len+ ];+ if ns_data.is_null() {+ return;+ }+ let img: *mut AnyObject = {+ let alloc: *mut AnyObject = msg_send![class!(NSImage), alloc];+ msg_send![alloc, initWithData: ns_data]+ };+ if !img.is_null() {+ let image_view = image_view_ptr as *mut AnyObject;+ let _: () = msg_send![image_view, setImage: img];+ }++ // Update the label. NSString::stringWithUTF8String requires NUL+ // termination; copy into a CString so we hand a clean buffer.+ if let Ok(cstr) = std::ffi::CString::new(frame.action_label) {+ let ns_str: *mut AnyObject = msg_send![+ class!(NSString),+ stringWithUTF8String: cstr.as_ptr() as *const u8+ ];+ if !ns_str.is_null() {+ let label = label_ptr as *mut AnyObject;+ let _: () = msg_send![label, setStringValue: ns_str];+ }+ }+}++unsafe extern "C" fn shutdown_cb(_ctx: *mut c_void) {+ use objc2::runtime::AnyObject;+ use objc2::msg_send;++ let handles = HANDLES.lock().unwrap().take();+ if let Some(h) = handles {+ let win = h.window as *mut AnyObject;+ if !win.is_null() {+ let _: () = msg_send![win, orderOut: std::ptr::null_mut::<AnyObject>()];+ let _: () = msg_send![win, close];+ }+ }+}++// ── AppKit main loop helper for Serve mode ───────────────────────────────++/// Park the main thread in `NSApplication.run()`. Used by `cua-driver+/// serve --experimental-pip` so the dispatch_async_f → main queue+/// path PiP frames go through can be drained. Mirrors the cursor+/// overlay's `run_appkit` startup (Accessory activation policy →+/// finishLaunching → run) without installing the overlay's+/// CALayer-backed window itself.+///+/// Never returns — the background `serve::run_serve_cmd` thread calls+/// `std::process::exit` when it finishes, which tears down NSApp at+/// the same time.+pub fn run_appkit_main_loop() {+ use objc2::runtime::AnyObject;+ use objc2::{class, msg_send};++ let _mtm = objc2_foundation::MainThreadMarker::new()+ .expect("run_appkit_main_loop must be called from the main thread");+ unsafe {+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];+ // Accessory policy: no Dock icon, no menu bar. Keeps the+ // daemon out of the user's application switcher, same as+ // the cursor overlay's NSApp setup.+ let _: bool = msg_send![app, setActivationPolicy: 1i64];+ let _: () = msg_send![app, finishLaunching];+ let _: () = msg_send![app, run];+ }+}++// ── Factory ──────────────────────────────────────────────────────────────++pub struct MacosPipBackendFactory;++impl PipBackendFactory for MacosPipBackendFactory {+ fn start(&self, cfg: &PipConfig) -> anyhow::Result<Box<dyn PipBackend>> {+ // Window construction must happen on the main thread. We hand+ // off via dispatch_async_f and return immediately — the first+ // few frames may be dropped while init races, which is fine+ // for a live-preview UX.+ let cfg_clone = cfg.clone();+ dispatch_to_main(cfg_clone, init_cb);+ Ok(Box::new(MacosPipBackend))+ }+}++unsafe extern "C" fn init_cb(ctx: *mut c_void) {+ use objc2::runtime::AnyObject;+ use objc2::{class, msg_send};+ use objc2_foundation::{NSPoint, NSRect, NSSize};++ let cfg: PipConfig = *Box::from_raw(ctx as *mut PipConfig);++ // Idempotency guard — `start()` should only be called once per+ // process, but cheap to defend against duplicate calls.+ if HANDLES.lock().unwrap().is_some() {+ return;+ }++ // ── Resolve geometry ──+ // AppKit windows use a bottom-left origin in screen coordinates.+ // The CLI flag uses a top-left X11-style origin (since that's the+ // mental model agents have for screenshots). Flip Y here so a+ // `+0+0` flag puts the window in the top-left corner.+ let screen: *mut AnyObject = msg_send![class!(NSScreen), mainScreen];+ if screen.is_null() {+ // Headless environment (CI) — skip silently. The daemon keeps+ // running without a PiP window.+ return;+ }+ let screen_frame: NSRect = msg_send![screen, frame];++ let w = cfg.geometry.width as f64;+ let h = cfg.geometry.height as f64;+ // Default placement: top-right corner with a 24pt inset, mirroring+ // the macOS conventions for floating utility windows.+ let inset = 24.0_f64;+ let (top_left_x, top_left_y) = match (cfg.geometry.x, cfg.geometry.y) {+ (Some(x), Some(y)) => (x as f64, y as f64),+ _ => (screen_frame.size.width - w - inset, inset),+ };+ // Convert top-left → bottom-left for AppKit.+ let bottom_y = screen_frame.size.height - top_left_y - h;+ let rect = NSRect::new(NSPoint::new(top_left_x, bottom_y), NSSize::new(w, h));++ // ── NSWindow ──+ // Borderless so the image owns the whole rectangle. No close button+ // / title bar — the window is owned by the daemon session lifecycle.+ // The rounded-corner look comes from a CALayer-backed content view+ // with cornerRadius + masksToBounds; the window itself stays+ // transparent outside the rounded rect.+ // NSWindowStyleMaskBorderless = 0+ let style_mask: u64 = 0;+ let backing_store_buffered: u64 = 2;+ let win: *mut AnyObject = {+ let alloc: *mut AnyObject = msg_send![class!(NSWindow), alloc];+ msg_send![+ alloc,+ initWithContentRect: rect+ styleMask: style_mask+ backing: backing_store_buffered+ defer: false+ ]+ };+ if win.is_null() {+ return;+ }++ // Transparent backing so the corners outside the CALayer-clipped+ // content view show whatever's underneath — gives the floating-pill+ // look. The shadow comes from AppKit's default `hasShadow: true`.+ let clear: *mut AnyObject = msg_send![class!(NSColor), clearColor];+ let _: () = msg_send![win, setBackgroundColor: clear];+ let _: () = msg_send![win, setOpaque: false];+ let _: () = msg_send![win, setHasShadow: true];+ // Draggable from anywhere since there's no title bar.+ let _: () = msg_send![win, setMovableByWindowBackground: true];++ // Floating window level (NSFloatingWindowLevel = 3).+ let _: () = msg_send![win, setLevel: 3i64];++ // Collection behavior: visible across all spaces, no Mission+ // Control affordance, never the main / key window.+ // 1<<0 CanJoinAllSpaces | 1<<4 Stationary | 1<<8 FullScreenAuxiliary+ // 1<<6 Transient | 1<<7 IgnoresCycle+ let behavior: u64 = (1 << 0) | (1 << 4) | (1 << 8) | (1 << 6) | (1 << 7);+ let _: () = msg_send![win, setCollectionBehavior: behavior];++ let _: () = msg_send![win, setReleasedWhenClosed: false];+ let _: () = msg_send![win, setHidesOnDeactivate: false];++ // ── Content view: rounded-corner black backing ──+ // wantsLayer + masksToBounds clips the image view to the rounded+ // rect. The backing CALayer color shows wherever the (proportionally+ // scaled) image leaves gaps above/below or left/right.+ let content_view: *mut AnyObject = msg_send![win, contentView];+ let _: () = msg_send![content_view, setWantsLayer: true];+ let content_layer: *mut AnyObject = msg_send![content_view, layer];+ let _: () = msg_send![content_layer, setCornerRadius: 12.0_f64];+ let _: () = msg_send![content_layer, setMasksToBounds: true];+ let black: *mut AnyObject = msg_send![+ class!(NSColor),+ colorWithCalibratedRed: 0.0_f64+ green: 0.0_f64+ blue: 0.0_f64+ alpha: 1.0_f64+ ];+ let black_cg: *mut CGColor = msg_send![black, CGColor];+ let _: () = msg_send![content_layer, setBackgroundColor: black_cg];++ // ── NSImageView: fills the entire content view ──+ let image_rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h));+ let image_view: *mut AnyObject = {+ let alloc: *mut AnyObject = msg_send![class!(NSImageView), alloc];+ msg_send![alloc, initWithFrame: image_rect]+ };+ // NSImageScaleProportionallyUpOrDown = 3 (preserve aspect ratio).+ // AppKit types this as NSUInteger — passing signed i64 triggers+ // an objc2 type-encoding panic on macOS 26+.+ let _: () = msg_send![image_view, setImageScaling: 3u64];++ // ── Label overlay: pill at bottom-center ──+ // Container NSView with semi-transparent black backing + rounded+ // corners (half its height for a fully rounded pill). NSTextField+ // sits inside, centered, white text on the dark backing.+ let pill_height = 22.0_f64;+ let pill_inset_x = 16.0_f64;+ let pill_inset_bottom = 10.0_f64;+ let pill_w = (w - pill_inset_x * 2.0).max(60.0);+ let pill_rect = NSRect::new(+ NSPoint::new(pill_inset_x, pill_inset_bottom),+ NSSize::new(pill_w, pill_height),+ );+ let pill: *mut AnyObject = {+ let alloc: *mut AnyObject = msg_send![class!(NSView), alloc];+ msg_send![alloc, initWithFrame: pill_rect]+ };+ let _: () = msg_send![pill, setWantsLayer: true];+ let pill_layer: *mut AnyObject = msg_send![pill, layer];+ let _: () = msg_send![pill_layer, setCornerRadius: pill_height / 2.0];+ let _: () = msg_send![pill_layer, setMasksToBounds: true];+ let pill_bg: *mut AnyObject = msg_send![+ class!(NSColor),+ colorWithCalibratedRed: 0.0_f64+ green: 0.0_f64+ blue: 0.0_f64+ alpha: 0.62_f64+ ];+ let pill_bg_cg: *mut CGColor = msg_send![pill_bg, CGColor];+ let _: () = msg_send![pill_layer, setBackgroundColor: pill_bg_cg];++ // NSTextField inside the pill — horizontal padding via frame inset.+ let label_rect = NSRect::new(+ NSPoint::new(10.0, 0.0),+ NSSize::new(pill_w - 20.0, pill_height),+ );+ let label: *mut AnyObject = {+ let alloc: *mut AnyObject = msg_send![class!(NSTextField), alloc];+ msg_send![alloc, initWithFrame: label_rect]+ };+ let _: () = msg_send![label, setBezeled: false];+ let _: () = msg_send![label, setDrawsBackground: false];+ let _: () = msg_send![label, setEditable: false];+ let _: () = msg_send![label, setSelectable: false];+ // NSTextAlignment.center = 2 (NSInteger).+ let _: () = msg_send![label, setAlignment: 2i64];+ let white: *mut AnyObject = msg_send![class!(NSColor), whiteColor];+ let _: () = msg_send![label, setTextColor: white];+ let font: *mut AnyObject = msg_send![class!(NSFont), systemFontOfSize: 11.0_f64];+ let _: () = msg_send![label, setFont: font];+ // Initial placeholder text — overwritten on the first frame.+ if let Ok(cstr) = std::ffi::CString::new("waiting for first action…") {+ let ns_str: *mut AnyObject = msg_send![+ class!(NSString),+ stringWithUTF8String: cstr.as_ptr() as *const u8+ ];+ if !ns_str.is_null() {+ let _: () = msg_send![label, setStringValue: ns_str];+ }+ }++ let _: () = msg_send![content_view, addSubview: image_view];+ let _: () = msg_send![pill, addSubview: label];+ let _: () = msg_send![content_view, addSubview: pill];++ // Show the window without making it key or activating the app.+ let _: () = msg_send![win, orderFrontRegardless];++ *HANDLES.lock().unwrap() = Some(NativeHandles {+ window: win as usize,+ image_view: image_view as usize,+ label: label as usize,+ });++ tracing::info!(target: "pip", "PiP window initialised ({}x{})", cfg.geometry.width, cfg.geometry.height);+}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_config.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_config.rsindex 890d7f30e3..56681ec8c7 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_config.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_config.rs@@ -37,6 +37,11 @@ impl Tool for GetConfigTool {.first().map(|s| s.config.enabled).unwrap_or(true);+ // PiP values aren't in DriverConfig — they're file-only since the+ // backend is initialised once at startup. Read fresh so the+ // response reflects whatever set_config (or a direct JSON edit)+ // last wrote.+ let (pip_enabled, pip_geometry) = pip_preview::read_pip_keys_from_file();ToolResult::text("cua-driver-rs configuration").with_structured(serde_json::json!({"version": env!("CARGO_PKG_VERSION"),@@ -46,6 +51,8 @@ impl Tool for GetConfigTool {"agent_cursor": {"enabled": cursor_enabled,},+ "experimental_pip": pip_enabled,+ "experimental_pip_geometry": pip_geometry,}))}}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rsindex 2a8484baef..532e4478b8 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs@@ -18,7 +18,11 @@ static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();fn def() -> &'static ToolDef {DEF.get_or_init(|| ToolDef {name: "set_config".into(),- description: "Update cua-driver-rs configuration. Changes take effect immediately.".into(),+ description: "Update cua-driver-rs configuration. Changes to capture_mode \+ and max_image_dimension take effect immediately. The experimental_pip \+ keys are persisted to ~/.cua-driver/config.json and take effect on \+ the next daemon restart (the PiP backend is initialised once at \+ startup).".into(),input_schema: serde_json::json!({"type": "object","properties": {@@ -30,6 +34,16 @@ fn def() -> &'static ToolDef {"max_image_dimension": {"type": "integer","description": "Max dimension for screenshot resizing (0 = no limit)."+ },+ "experimental_pip": {+ "type": "boolean",+ "description": "Enable the experimental picture-in-picture preview window. \+ Applies on next daemon restart."+ },+ "experimental_pip_geometry": {+ "type": "string",+ "description": "PiP window size + optional position in `WxH` or `WxH+X+Y` \+ form (e.g. `320x200+24+24`). Applies on next daemon restart."}},"additionalProperties": false@@ -64,9 +78,32 @@ impl Tool for SetConfigTool {return ToolResult::error(format!("max_image_dimension {dim} exceeds u32::MAX"));}}+ // PiP keys persist to the same config.json but take effect only on+ // next daemon restart — the backend is initialised once at startup.+ let mut pip_note = String::new();+ if let Some(enabled) = args.get("experimental_pip").and_then(|v| v.as_bool()) {+ if let Err(e) = pip_preview::write_config_key("experimental_pip", Value::Bool(enabled)) {+ return ToolResult::error(format!("failed to persist experimental_pip: {e}"));+ }+ pip_note = format!(" — restart cua-driver for experimental_pip={enabled} to take effect");+ }+ if let Some(geom) = args.opt_str("experimental_pip_geometry") {+ // Validate before persisting so the user gets an immediate error.+ if pip_preview::PipGeometry::parse(&geom).is_none() {+ return ToolResult::error(format!(+ "experimental_pip_geometry `{geom}` is not a valid WxH or WxH+X+Y string"+ ));+ }+ if let Err(e) = pip_preview::write_config_key("experimental_pip_geometry", Value::String(geom.clone())) {+ return ToolResult::error(format!("failed to persist experimental_pip_geometry: {e}"));+ }+ if pip_note.is_empty() {+ pip_note = format!(" — restart cua-driver for experimental_pip_geometry={geom} to take effect");+ }+ }ToolResult::text(format!(- "Config updated: capture_mode={}, max_image_dimension={}",- cfg.capture_mode, cfg.max_image_dimension+ "Config updated: capture_mode={}, max_image_dimension={}{}",+ cfg.capture_mode, cfg.max_image_dimension, pip_note))}}diff --git a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml b/libs/cua-driver/rust/crates/platform-windows/Cargo.tomlindex 1b3bfefbe2..04f4fa34f3 100644--- a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml+++ b/libs/cua-driver/rust/crates/platform-windows/Cargo.toml@@ -13,6 +13,7 @@ tracing = { workspace = true }async-trait = "0.1"cua-driver-core = { path = "../cua-driver-core" }cursor-overlay = { path = "../cursor-overlay" }+pip-preview = { path = "../pip-preview" }# tiny-skia for cross-platform cursor rendering (used in overlay.rs on all targets)tiny-skia = { version = "0.11", default-features = false, features = ["std"] }diff --git a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs b/libs/cua-driver/rust/crates/platform-windows/src/lib.rsindex 74130c6778..d840ffbb45 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs@@ -15,6 +15,7 @@ pub mod tools;pub mod overlay;pub mod diagnostics;pub mod recording_hooks;+pub mod pip;#[cfg(target_os = "windows")]pub mod win32;diff --git a/libs/cua-driver/rust/crates/platform-windows/src/pip/mod.rs b/libs/cua-driver/rust/crates/platform-windows/src/pip/mod.rsnew file mode 100644index 0000000000..6f8666fced--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/pip/mod.rs@@ -0,0 +1,24 @@+//! Windows picture-in-picture preview stub.+//!+//! The Win32 implementation is a follow-up to the experimental macOS+//! drop. The plan is a layered, no-activate `WS_EX_NOACTIVATE |+//! WS_EX_TOPMOST` HWND with a child `STATIC` showing the bitmap of+//! the latest screenshot, fed via `SetWindowPos` for the never-key+//! behavior the spec requires. Tracking issue is linked in the docs.+//!+//! Until that lands, `start()` returns a clear error so `main.rs`+//! can log "PiP unavailable on this platform" and continue without+//! the window.++use pip_preview::{PipBackend, PipBackendFactory, PipConfig};++pub struct WindowsPipBackendFactory;++impl PipBackendFactory for WindowsPipBackendFactory {+ fn start(&self, _cfg: &PipConfig) -> anyhow::Result<Box<dyn PipBackend>> {+ Err(anyhow::anyhow!(+ "PiP preview is not yet implemented on Windows — track \+ trycua/cua follow-up issue for status"+ ))+ }+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rsindex bcb9801568..05a388e04d 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs@@ -4331,6 +4331,7 @@ impl Tool for GetConfigTool {.first().map(|s| s.config.enabled).unwrap_or(true);+ let (pip_enabled, pip_geometry) = pip_preview::read_pip_keys_from_file();let payload = json!({"schema_version": 1,"version": env!("CARGO_PKG_VERSION"),@@ -4338,6 +4339,8 @@ impl Tool for GetConfigTool {"capture_mode": cfg.capture_mode,"max_image_dimension": cfg.max_image_dimension,"agent_cursor": { "enabled": cursor_enabled },+ "experimental_pip": pip_enabled,+ "experimental_pip_geometry": pip_geometry,});// Match Swift's text format 1:1: `"✅ <pretty JSON>"`.let pretty = serde_json::to_string_pretty(&payload).unwrap_or_else(|_| payload.to_string());@@ -4369,13 +4372,17 @@ impl Tool for SetConfigTool {— bulk write of named fields.\n\n\Known keys:\n\- `capture_mode` (string: `vision` | `ax` | `som`)\n\- - `max_image_dimension` (integer)\n\n\+ - `max_image_dimension` (integer)\n\+ - `experimental_pip` (boolean; persisted to config.json, applies on next daemon restart — Windows backend stubbed today, see issue #1729)\n\+ - `experimental_pip_geometry` (string `WxH` or `WxH+X+Y`; persisted; applies on next daemon restart)\n\n\Returns the full updated config in the same shape as `get_config`.".into(),input_schema: json!({"type":"object","properties":{"key":{"type":"string","description":"Dotted snake_case path to a leaf config field (Swift-compatible shape). Pair with `value`."},"value":{"description":"New value for `key`. JSON type depends on the key."},"capture_mode":{"type":"string","enum":["som","vision","ax"],"description":"Legacy per-field shape."},- "max_image_dimension":{"type":"integer","description":"Legacy per-field shape."}+ "max_image_dimension":{"type":"integer","description":"Legacy per-field shape."},+ "experimental_pip":{"type":"boolean","description":"Legacy per-field shape. Enables PiP preview (applies next restart)."},+ "experimental_pip_geometry":{"type":"string","description":"Legacy per-field shape. PiP window size + optional position."}},"additionalProperties":false}),read_only: false, destructive: false, idempotent: true, open_world: false,})@@ -4397,8 +4404,31 @@ impl Tool for SetConfigTool {Some(n) => { cfg.max_image_dimension = n as u32; applied = true; }None => return ToolResult::error(format!("`max_image_dimension` must be an integer, got {val}.")),},+ "experimental_pip" => match val.as_bool() {+ Some(b) => {+ if let Err(e) = pip_preview::write_config_key("experimental_pip", Value::Bool(b)) {+ return ToolResult::error(format!("failed to persist experimental_pip: {e}"));+ }+ applied = true;+ }+ None => return ToolResult::error(format!("`experimental_pip` must be a boolean, got {val}.")),+ },+ "experimental_pip_geometry" => match val.as_str() {+ Some(s) => {+ if pip_preview::PipGeometry::parse(s).is_none() {+ return ToolResult::error(format!(+ "experimental_pip_geometry `{s}` is not a valid WxH or WxH+X+Y string"+ ));+ }+ if let Err(e) = pip_preview::write_config_key("experimental_pip_geometry", Value::String(s.to_owned())) {+ return ToolResult::error(format!("failed to persist experimental_pip_geometry: {e}"));+ }+ applied = true;+ }+ None => return ToolResult::error(format!("`experimental_pip_geometry` must be a string, got {val}.")),+ },other => return ToolResult::error(format!(- "Unknown config key `{other}`. Known: capture_mode, max_image_dimension."+ "Unknown config key `{other}`. Known: capture_mode, max_image_dimension, experimental_pip, experimental_pip_geometry.")),}}@@ -4409,6 +4439,23 @@ impl Tool for SetConfigTool {if let Some(dim) = args.get("max_image_dimension").and_then(|v| v.as_u64()) {cfg.max_image_dimension = dim as u32; applied = true;}+ if let Some(enabled) = args.get("experimental_pip").and_then(|v| v.as_bool()) {+ if let Err(e) = pip_preview::write_config_key("experimental_pip", Value::Bool(enabled)) {+ return ToolResult::error(format!("failed to persist experimental_pip: {e}"));+ }+ applied = true;+ }+ if let Some(geom) = args.get("experimental_pip_geometry").and_then(|v| v.as_str()) {+ if pip_preview::PipGeometry::parse(geom).is_none() {+ return ToolResult::error(format!(+ "experimental_pip_geometry `{geom}` is not a valid WxH or WxH+X+Y string"+ ));+ }+ if let Err(e) = pip_preview::write_config_key("experimental_pip_geometry", Value::String(geom.to_owned())) {+ return ToolResult::error(format!("failed to persist experimental_pip_geometry: {e}"));+ }+ applied = true;+ }if !applied {return ToolResult::error("Missing required string field `key` (or a known legacy per-field).");}@@ -4418,6 +4465,7 @@ impl Tool for SetConfigTool {.first().map(|s| s.config.enabled).unwrap_or(true);+ let (pip_enabled, pip_geometry) = pip_preview::read_pip_keys_from_file();let payload = json!({"schema_version": 1,"version": env!("CARGO_PKG_VERSION"),@@ -4425,6 +4473,8 @@ impl Tool for SetConfigTool {"capture_mode": cfg.capture_mode,"max_image_dimension": cfg.max_image_dimension,"agent_cursor": { "enabled": cursor_enabled },+ "experimental_pip": pip_enabled,+ "experimental_pip_geometry": pip_geometry,});let pretty = serde_json::to_string_pretty(&payload).unwrap_or_else(|_| payload.to_string());ToolResult::text(format!("✅ {pretty}")).with_structured(payload)