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): daemon session identity — own + clean up session-scoped recording & config (#1776)
Francesco Bonacci748e74a84ef0
diff --git a/docs/content/docs/cua-driver/guide/getting-started/process-model.mdx b/docs/content/docs/cua-driver/guide/getting-started/process-model.mdxindex daed11b70d..7bf024bf4f 100644--- a/docs/content/docs/cua-driver/guide/getting-started/process-model.mdx+++ b/docs/content/docs/cua-driver/guide/getting-started/process-model.mdx@@ -98,12 +98,24 @@ cua-driver status# pid: 12345```+### Session identity and shared daemon state++The daemon drives **one** physical machine, and every `cua-driver mcp` client shares its `ToolState`. Some of that state is "set once, affects later calls" — the trajectory recorder is a singleton, and `set_config` mutates a process-global config — so two concurrent MCP sessions would otherwise clobber each other.++To scope that state, each `cua-driver mcp` proxy mints a **session identity** once at startup and stamps it on every request it forwards to the daemon. The daemon uses it to OWN and CLEAN UP session-scoped state:++- **Recording ownership.** `start_recording` stamps the live recording with the calling session. On disconnect the proxy sends a best-effort `session_end` signal; the daemon stops only the recording that session owns — so if a later client started its own recording (clobbering the singleton), the earlier client's disconnect can't stop it. A manual `stop_recording`, the CLI, and the daemon idle-TTL backstop all stop unconditionally.+- **Per-session config.** `set_config` from a proxy-backed session writes an in-memory override keyed by the session, not the shared/persisted global — see [set_config](/cua-driver/reference/mcp-tools#set_config). The override is dropped on `session_end`. Only the anonymous CLI / one-shot path writes the persisted default.++This solves state **ownership and cleanup**, not safe concurrent screen/input control — the daemon still drives one machine, so two sessions clicking at once still contend for the same desktop. Backward-compatible: a one-shot `cua-driver call` (or an older proxy that predates the session field) carries no session identity and behaves exactly as before — anonymous/global, writing the persisted config and owning no session-scoped state.+### mcp-client lifecycle (proxy mode)The `cua-driver mcp` process in proxy mode is a thin stdio→UDS pump:- Lives for the duration of the stdio session — exits cleanly when the MCP client (parent) closes stdin or the host process is killed.- Does **not** terminate the daemon on exit. The daemon stays running, ready for the next mcp client.+- On a clean stdin EOF it sends one best-effort `session_end` so the daemon drops this session's owned state (recording + config overrides). A SIGKILL skips this; the daemon idle-TTL backstop still bounds a leaked recording.- Holds no AX caches or per-pid state of its own — everything lives on the daemon side. Restarting just the mcp client preserves whatever element-index caches the daemon has built up.### mcp-client lifecycle (in-process mode)diff --git a/docs/content/docs/cua-driver/reference/mcp-tools.mdx b/docs/content/docs/cua-driver/reference/mcp-tools.mdxindex 0becf40005..f73097f8a3 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools.mdx@@ -452,7 +452,7 @@ Start trajectory recording. Every subsequent action-tool invocation (click, righTurn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.-**Video is on by default** — the main display is captured to `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of the session. Pass `record_video: false` to opt out.+**Video is off by default.** Pass `record_video: true` to also capture the main display to `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of the session. On the daemon-proxy path (the default macOS `cua-driver mcp` flow), recording is stopped automatically when the MCP client disconnects (the proxy sends a `session_end` signal carrying its session identity, and the daemon stops only the recording that session owns), so a forgotten session no longer keeps writing to disk; a daemon-side idle timeout (~5 min of no tool activity) is a backstop in case the client is killed before it can clean up.**macOS uses native ScreenCaptureKit** (in-process SCStream + SCRecordingOutput) so video inherits Cua Driver's own Screen Recording grant — no extra TCC prompt, no ffmpeg subprocess. Requires macOS 15.0+.@@ -460,10 +460,12 @@ Turn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarState persists for the life of the daemon / MCP session; a restart resets to disabled with no on-disk state. Call `stop_recording` to disable + finalize the mp4.+The result's `structuredContent` includes an `owner` field — the session that owns the live recording (the proxy-minted session identity), or `null` when started anonymously. Ownership is what lets the daemon-proxy disconnect auto-stop (a `session_end` signal) stop only the recording this session started, even when a later client clobbered the singleton recorder with its own `start_recording`. (This `owner` field supersedes the earlier `generation` token.)+**Arguments:**- `output_dir` (string, required): Absolute or ~-rooted directory where turn folders and (when enabled) the video file are written.-- `record_video` (boolean, optional): Capture the main display to <output_dir>/recording.mp4. Default: true. Set to false to record only the per-turn screenshots + JSON. On macOS this uses native ScreenCaptureKit (no extra TCC prompt, macOS 15.0+); on Windows + Linux it requires ffmpeg on PATH.+- `record_video` (boolean, optional): Capture the main display to <output_dir>/recording.mp4. Default: false. Set to true to also capture the main display to recording.mp4 (otherwise only the per-turn screenshots + JSON are recorded). On macOS this uses native ScreenCaptureKit (no extra TCC prompt, macOS 15.0+); on Windows + Linux it requires ffmpeg on PATH.```json{"output_dir":"~/cua-trajectories/demo1"}@@ -473,7 +475,11 @@ State persists for the life of the daemon / MCP session; a restart resets to disStop trajectory recording. Disables further per-turn capture and, when video was enabled, gracefully terminates the ffmpeg subprocess so the mp4's moov atom is finalized (the file is playable). Calling stop on an already-stopped session is a no-op. The response carries `last_video_path` pointing at the finalized mp4 (when video was on).-**Arguments:** none.+A manual `stop_recording` is **unconditional** — it stops whatever recording is active regardless of which session started it. Ownership-scoped teardown (so one MCP client disconnecting can't stop a recording a later client started) is handled by the daemon's `session_end` lifecycle signal, not by this tool — so `stop_recording` takes no arguments.++**Arguments:**++_None._### replay_trajectory@@ -500,6 +506,8 @@ Caveats: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).+**Per-session isolation (daemon-proxy path).** The daemon is one shared process: every `cua-driver mcp` client shares its state. To stop concurrent MCP sessions from clobbering each other (and the on-disk default), `set_config` from a proxy-backed MCP session writes an **in-memory, session-scoped override** — it does NOT touch the global `DriverConfig` or persist to `~/.cua-driver/config.json`. `get_config` and the capture tools then resolve effective values as call-arg > session override > global default, and the override is dropped automatically when the client disconnects. Only the anonymous path — the `cua-driver config set` CLI and one-shot `cua-driver call` — writes the persisted global default that survives a daemon restart. (`capture_mode` / `max_image_dimension` session-scoping is macOS-only today; Windows/Linux still write the shared config — tracked as a follow-up.)+**Arguments:**- `capture_mode` (string, optional): Default capture mode for get_window_state.diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lockindex c0bf75cbd4..2203a84428 100644--- a/libs/cua-driver/rust/Cargo.lock+++ b/libs/cua-driver/rust/Cargo.lock@@ -275,7 +275,7 @@ dependencies = [[[package]]name = "cua-driver"-version = "0.3.5"+version = "0.3.6"dependencies = ["anyhow","async-trait",@@ -305,7 +305,7 @@ dependencies = [[[package]]name = "cua-driver-core"-version = "0.3.5"+version = "0.3.6"dependencies = ["anyhow","async-trait",@@ -320,7 +320,7 @@ dependencies = [[[package]]name = "cua-driver-uia"-version = "0.3.5"+version = "0.3.6"dependencies = ["anyhow","cua-driver-core",@@ -335,7 +335,7 @@ dependencies = [[[package]]name = "cursor-overlay"-version = "0.3.5"+version = "0.3.6"dependencies = ["anyhow","image",@@ -488,7 +488,7 @@ checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"[[package]]name = "focus-monitor-win"-version = "0.3.5"+version = "0.3.6"dependencies = ["windows 0.58.0",]@@ -1192,7 +1192,7 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"[[package]]name = "pip-preview"-version = "0.3.5"+version = "0.3.6"dependencies = ["anyhow","serde_json",@@ -1207,7 +1207,7 @@ checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"[[package]]name = "platform-linux"-version = "0.3.5"+version = "0.3.6"dependencies = ["anyhow","async-trait",@@ -1228,7 +1228,7 @@ dependencies = [[[package]]name = "platform-macos"-version = "0.3.5"+version = "0.3.6"dependencies = ["anyhow","async-trait",@@ -1260,7 +1260,7 @@ dependencies = [[[package]]name = "platform-windows"-version = "0.3.5"+version = "0.3.6"dependencies = ["anyhow","async-trait",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 1818092c82..6fbc141414 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@@ -23,6 +23,7 @@ pub mod recording_render;pub mod recording_tools;pub mod recording_zoom;pub mod server;+pub mod session;pub mod text_sanitize;pub mod tool;pub mod tool_args;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 43ed3ca976..6d4d6e2684 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@@ -93,6 +93,18 @@ pub struct RecordingSession {struct RecordingInner {enabled: bool,+ /// Session that owns the live recording, stamped on every successful+ /// `start()` from the daemon-injected `_session_id`. The daemon-global+ /// recorder is a singleton, so when session A starts a recording and+ /// session B later starts another (clobbering A's), A's disconnect must+ /// NOT stop B's recording. The proxy-exit `session_end` hook passes its+ /// own session id to `stop_owner()`, which no-ops when the live owner has+ /// moved on. `None` means the recording was started anonymously (CLI+ /// one-shot / legacy `configure()` shim) and is owned by nobody — only an+ /// unconditional `stop_owner(None)` can tear it down. Supersedes the+ /// #1775 generation token: a session id is a stable owner identity rather+ /// than a monotonic counter, and it doubles as the config-override key.+ owner: Option<String>,output_dir: Option<PathBuf>,next_turn: u32,session_start_ms: u64,@@ -130,6 +142,13 @@ pub struct RecordingState {/// Path to the most recently finalized video file, if any. Populated/// after a stop; cleared on next start.pub last_video_path: Option<String>,+ /// Session id that owns the current (or most recent) recording, stamped on+ /// `start()` from the daemon-injected `_session_id`. `None` for an+ /// anonymously-started recording (CLI one-shot / legacy shim). Surfaced so+ /// callers can see who owns the live recording; the proxy-exit teardown+ /// drives ownership via `session_end` (it already knows its own id) rather+ /// than reading this back.+ pub owner: Option<String>,}impl RecordingSession {@@ -137,6 +156,7 @@ impl RecordingSession {Self {inner: Mutex::new(RecordingInner {enabled: false,+ owner: None,output_dir: None,next_turn: 1,session_start_ms: 0,@@ -153,13 +173,21 @@ impl RecordingSession {/// Enable recording at `output_dir`, optionally with video capture./// Counterpart to `stop()`. Returns the resulting state.///- /// `record_video=true` (the default for callers that don't opt out)- /// spawns ffmpeg writing `<output_dir>/recording.mp4` for the lifetime- /// of the session. If ffmpeg isn't on PATH the start still succeeds —+ /// `record_video=true` spawns ffmpeg writing `<output_dir>/recording.mp4`+ /// for the lifetime of the session. NOTE: the MCP `start_recording` tool+ /// now defaults `record_video` to *false* (opt-in) — see+ /// `recording_tools.rs` — so video only records when explicitly requested.+ /// The legacy CLI `recording start` path via `configure()` still forces+ /// video on. If ffmpeg isn't on PATH the start still succeeds —/// the per-turn capture (action.json + screenshot.png) is independent/// of video — but the structured state carries the ffmpeg error so/// the caller can surface it.- pub fn start(&self, output_dir: &str, record_video: bool) -> anyhow::Result<()> {+ ///+ /// `owner` stamps the session that owns this recording (the daemon-injected+ /// `_session_id`). `None` marks an anonymous start (CLI one-shot / legacy+ /// `configure()` shim) owned by nobody. See `stop_owner()` for how this+ /// gates teardown.+ pub fn start(&self, output_dir: &str, record_video: bool, owner: Option<&str>) -> anyhow::Result<()> {let mut inner = self.inner.lock().unwrap();// If a previous session is still open, gracefully tear it down// first so the caller doesn't accidentally leak an ffmpeg process.@@ -225,6 +253,12 @@ impl RecordingSession {&session_payload,);+ // Stamp the owning session on every successful start (reached only on+ // the success path — start() returns early via `?` on `create_dir_all`+ // failure above). `owner` clobbers any previous owner, which is correct:+ // the daemon-global recorder is a singleton, so the latest start() owns+ // it. The previous owner's disconnect then no-ops in stop_owner().+ inner.owner = owner.map(str::to_owned);inner.enabled = true;inner.output_dir = Some(dir);inner.next_turn = 1;@@ -240,11 +274,34 @@ impl RecordingSession {/// session is a no-op. If a video subprocess is running, it's/// gracefully terminated and the finalized metadata is folded into/// `session.json`.- pub fn stop(&self) -> anyhow::Result<()> {+ ///+ /// `requester` is the ownership guard for session-driven teardown+ /// (`session_end` / proxy-exit). Semantics:+ /// - `None` — unconditional stop. Manual `stop_recording`, the legacy+ /// `configure()` shim, the CLI one-shot path, and the idle-TTL backstop+ /// all pass `None` to preserve today's manual-stop behavior.+ /// - `Some(sid)` where `sid` owns the live recording — stop + clear owner.+ /// - `Some(sid)` where `sid` does NOT own it (a disconnecting session+ /// whose recording was already clobbered by a newer `start()`, or which+ /// never started a recording) — silent no-op, leaving the current+ /// owner's recording running.+ /// The guard lives inside the lock so it is race-free against a concurrent+ /// `start()`. Supersedes the #1775 generation-token `stop()`.+ pub fn stop_owner(&self, requester: Option<&str>) -> anyhow::Result<()> {let mut inner = self.inner.lock().unwrap();if !inner.enabled {return Ok(());}+ if let Some(req) = requester {+ // A targeted stop only acts when the requester owns the live+ // recording. An anonymously-owned recording (owner == None) is+ // never torn down by a session-scoped stop — only an unconditional+ // `stop_owner(None)` reaches it.+ if inner.owner.as_deref() != Some(req) {+ return Ok(());+ }+ }+ inner.owner = None;let dir = inner.output_dir.clone();let video_meta = inner.video.take().and_then(|rec| rec.stop().ok());let cursor_samples = inner.cursor.take().map(|c| c.stop()).unwrap_or(0);@@ -285,15 +342,17 @@ impl RecordingSession {/// Legacy toggle API kept as a thin shim over `start()`/`stop()` so/// existing callers (CLI subcommand, tests) keep compiling during the- /// rename window. Defaults `record_video` to true to match the new- /// surface.+ /// rename window. Forces `record_video` on for this legacy CLI path — the+ /// MCP `start_recording` tool now defaults video OFF (see+ /// `recording_tools.rs`), but the CLI `recording start` keeps video on.pub fn configure(&self, enabled: bool, output_dir: Option<&str>) -> anyhow::Result<()> {if !enabled {- return self.stop();+ return self.stop_owner(None);}let dir = output_dir.ok_or_else(|| anyhow::anyhow!("output_dir is required when enabling recording"))?;- self.start(dir, true)+ // Legacy CLI path: anonymous owner (no MCP session id available here).+ self.start(dir, true, None)}/// Return a snapshot of the current state (non-blocking).@@ -307,6 +366,7 @@ impl RecordingSession {video_active: inner.video.is_some(),last_video_path: inner.last_video.as_ref().map(|m| m.path.to_string_lossy().into_owned()),+ owner: inner.owner.clone(),}}@@ -333,10 +393,17 @@ impl RecordingSession {(out.join(format!("turn-{idx:05}")), inner.session_start_ms)};+ // Strip the daemon-injected `_session_id` (and any other reserved+ // `_`-prefixed internal keys) before recording so the UUID never lands+ // in action.json's `arguments`. The injection point is the daemon+ // `call` branch (serve.rs); recording is the single chokepoint where+ // those internal keys must not leak into the persisted trajectory.+ let args = strip_internal_keys(args);+if let Err(e) = write_turn(&turn_dir,tool_name,- args,+ args.as_ref(),result_text,start_ms,session_start_ms,@@ -353,6 +420,24 @@ impl Default for RecordingSession {// ── helpers ───────────────────────────────────────────────────────────────────+/// Drop reserved internal keys (any `_`-prefixed key, e.g. the daemon-injected+/// `_session_id`) from a tool-call args object so they never persist into a+/// recorded `action.json`. Returns the value unchanged when it isn't an object+/// or carries no internal keys (cheap clone-free fast path).+fn strip_internal_keys(args: &Value) -> std::borrow::Cow<'_, Value> {+ match args.as_object() {+ Some(map) if map.keys().any(|k| k.starts_with('_')) => {+ let cleaned: serde_json::Map<String, Value> = map+ .iter()+ .filter(|(k, _)| !k.starts_with('_'))+ .map(|(k, v)| (k.clone(), v.clone()))+ .collect();+ std::borrow::Cow::Owned(Value::Object(cleaned))+ }+ _ => std::borrow::Cow::Borrowed(args),+ }+}+fn write_turn(turn_dir: &Path,tool_name: &str,diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rsindex 2875339704..7493ea2582 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs@@ -68,9 +68,10 @@ impl Tool for StartRecordingTool {red dot drawn at the click point.\n\n\Turn folders are named `turn-00001/`, `turn-00002/`, etc. Turn \numbering restarts at 1 each time recording is (re-)started.\n\n\- **Video is on by default** — the main display is captured to \- `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of \- the session. Pass `record_video: false` to opt out.\n\n\+ **Video is off by default.** Pass `record_video: true` to also \+ capture the main display to `<output_dir>/recording.mp4` (H.264 / \+ 30 fps) for the lifetime of the session. The recording is torn \+ down automatically when the MCP client disconnects.\n\n\**macOS uses native ScreenCaptureKit** (in-process SCStream + \SCRecordingOutput) so video inherits Cua Driver's own Screen \Recording grant — no extra TCC prompt, no ffmpeg subprocess. \@@ -96,8 +97,9 @@ impl Tool for StartRecordingTool {"record_video": {"type": "boolean","description": "Capture the main display to <output_dir>/recording.mp4. \- Default: true. Set to false to record only the per-turn \- screenshots + JSON. On macOS this uses native \+ Default: false. Set to true to also capture the main \+ display to recording.mp4 (otherwise only the per-turn \+ screenshots + JSON are recorded). On macOS this uses native \ScreenCaptureKit (no extra TCC prompt, macOS 15.0+); on \Windows + Linux it requires ffmpeg on PATH."}@@ -117,9 +119,13 @@ impl Tool for StartRecordingTool {if output_dir.as_deref().map(str::is_empty).unwrap_or(true) {return ToolResult::error("`output_dir` is required.");}- let record_video = args.bool_or("record_video", true);+ let record_video = args.bool_or("record_video", false);+ // Daemon-injected ownership key (absent for one-shot CLI / anonymous+ // sessions). Stamps the recording so a session-scoped teardown+ // (session_end) only stops the recording its own session started.+ let owner = args.opt_str("_session_id");- match self.session.start(output_dir.as_deref().unwrap(), record_video) {+ match self.session.start(output_dir.as_deref().unwrap(), record_video, owner.as_deref()) {Ok(()) => {let state = self.session.current_state();// When the caller asked for video and it failed (e.g. macOS@@ -164,7 +170,12 @@ impl Tool for StopRecordingTool {and, when video was enabled, gracefully terminates the ffmpeg subprocess \so the mp4's moov atom is finalized (the file is playable). Calling \stop on an already-stopped session is a no-op. The response carries \- `last_video_path` pointing at the finalized mp4 (when video was on).".into(),+ `last_video_path` pointing at the finalized mp4 (when video was on).\n\n\+ A manual `stop_recording` is **unconditional** — it stops whatever \+ recording is active regardless of which session started it. \+ Ownership-scoped teardown (so one MCP client disconnecting can't stop a \+ recording a later client started) is handled by the daemon's \+ `session_end` lifecycle signal, not by this tool.".into(),input_schema: json!({"type": "object","properties": {},@@ -178,7 +189,10 @@ impl Tool for StopRecordingTool {}async fn invoke(&self, _args: Value) -> ToolResult {- match self.session.stop() {+ // Manual stop is unconditional — `None` requester tears down whatever+ // recording is active. Session-scoped teardown is driven by the+ // daemon's `session_end` arm (serve.rs), which calls `stop_owner(sid)`.+ match self.session.stop_owner(None) {Ok(()) => {let state = self.session.current_state();let video_note = state.last_video_path.as_deref()@@ -440,6 +454,11 @@ fn recording_state_json(state: &RecordingState) -> Value {"last_error": state.last_error,"video_active": state.video_active,"last_video_path": state.last_video_path,+ // Session that owns the live recording (the daemon-injected+ // `_session_id`), or null when started anonymously. Informational; the+ // proxy-exit teardown drives ownership via the daemon `session_end`+ // signal rather than reading this back.+ "owner": state.owner,})}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rsnew file mode 100644index 0000000000..f66b7d8c10--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs@@ -0,0 +1,47 @@+//! Session lifecycle hooks.+//!+//! The cua-driver daemon (`serve.rs`) drives ONE shared `ToolRegistry`; every+//! `cua-driver mcp` proxy process connects to it and shares its state. A+//! proxy-minted `session_id` (carried in the daemon request envelope) lets the+//! daemon OWN and CLEAN UP per-session state.+//!+//! Recording ownership lives on the core `RecordingSession` directly. But some+//! session-scoped state is platform-specific (e.g. macOS per-session config+//! overrides in `platform-macos::tools::SessionConfigRegistry`) and the daemon+//! only holds an `Arc<ToolRegistry>` — it can't reach into a platform crate's+//! `ToolState`. This module bridges that gap with a small process-global list+//! of cleanup callbacks: each platform registers a `Fn(&str)` once at startup,+//! and the daemon's `session_end` arm fans the disconnecting `session_id` out+//! to all of them.+//!+//! This mirrors the existing screenshot/AX-snapshot callback pattern in+//! `recording.rs` — a registry-free, platform-pluggable hook set with no+//! reverse coupling from core into the platform crates.++use std::sync::{Mutex, OnceLock};++type SessionEndHook = Box<dyn Fn(&str) + Send + Sync>;++static SESSION_END_HOOKS: OnceLock<Mutex<Vec<SessionEndHook>>> = OnceLock::new();++fn hooks() -> &'static Mutex<Vec<SessionEndHook>> {+ SESSION_END_HOOKS.get_or_init(|| Mutex::new(Vec::new()))+}++/// Register a callback invoked with the disconnecting `session_id` whenever a+/// session ends (graceful proxy EOF → daemon `session_end`). Each platform+/// registers its session-scoped cleanup here once at startup. Idempotency and+/// "unknown session id" tolerance are the hook's responsibility — `session_end`+/// fires once per proxy exit, but a hook should treat a clear of an unseen id+/// as a no-op.+pub fn register_session_end_hook(hook: impl Fn(&str) + Send + Sync + 'static) {+ hooks().lock().unwrap().push(Box::new(hook));+}++/// Fan a session-end out to every registered cleanup hook. Called by the daemon+/// `session_end` arm. No-op when no hooks are registered.+pub fn fire_session_end(session_id: &str) {+ for hook in hooks().lock().unwrap().iter() {+ hook(session_id);+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rsindex b6a67b5a3e..3585984569 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs@@ -963,6 +963,8 @@ pub fn run_call(method: "call".into(),name: Some(tool.to_owned()),args: Some(args_for_daemon),+ // CLI one-shot is its own ephemeral, anonymous/global session.+ session_id: None,};match crate::serve::send_request(&socket_path, &req) {Ok(resp) => {@@ -1202,6 +1204,9 @@ pub fn run_recording_cmd(subcommand: &str, args: &[String], socket: Option<&str>args: Some(serde_json::json!({"output_dir": output_dir})),+ // CLI `recording start` is anonymous — the recording is owned by+ // nobody, so only an unconditional stop (CLI / manual) reaps it.+ session_id: None,};match crate::serve::send_request(&socket_path, &req) {Ok(resp) if resp.ok => {@@ -1211,6 +1216,7 @@ pub fn run_recording_cmd(subcommand: &str, args: &[String], socket: Option<&str>method: "call".into(),name: Some("get_recording_state".into()),args: Some(serde_json::json!({})),+ session_id: None,};if let Ok(sr) = crate::serve::send_request(&socket_path, &state_req) {if let Some(result) = sr.result {@@ -1235,6 +1241,7 @@ pub fn run_recording_cmd(subcommand: &str, args: &[String], socket: Option<&str>method: "call".into(),name: Some("stop_recording".into()),args: Some(serde_json::json!({})),+ session_id: None,};match crate::serve::send_request(&socket_path, &req) {Ok(resp) if resp.ok => println!("Recording stopped."),@@ -1251,6 +1258,7 @@ pub fn run_recording_cmd(subcommand: &str, args: &[String], socket: Option<&str>method: "call".into(),name: Some("get_recording_state".into()),args: Some(serde_json::json!({})),+ session_id: None,};match crate::serve::send_request(&socket_path, &req) {Ok(resp) if resp.ok => {@@ -1491,6 +1499,7 @@ fn run_permissions_status(json: bool) {method: "call".into(),name: Some("check_permissions".into()),args: Some(serde_json::json!({ "prompt": false })),+ session_id: None,};crate::serve::send_request(&socket, &req).ok()@@ -1617,6 +1626,7 @@ fn run_permissions_grant() {method: "call".into(),name: Some("check_permissions".into()),args: Some(serde_json::json!({ "prompt": false })),+ session_id: None,};let poll_deadline =std::time::Instant::now() + std::time::Duration::from_secs(180);@@ -2311,6 +2321,8 @@ pub fn run_config_cmd(method: "call".into(),name: Some("get_config".into()),args: Some(serde_json::json!({})),+ // CLI `config get` reads the persisted global (anonymous).+ session_id: None,};if let Ok(resp) = crate::serve::send_request(&socket_path, &req) {if resp.ok {@@ -2389,6 +2401,9 @@ pub fn run_config_cmd(method: "call".into(),name: Some("set_config".into()),args: Some(args.clone()),+ // CLI `config set` is anonymous → writes the persisted+ // global default (the only writer of the on-disk config).+ session_id: None,};if let Ok(resp) = crate::serve::send_request(&socket_path, &req) {if resp.ok {@@ -2398,6 +2413,7 @@ pub fn run_config_cmd(method: "call".into(),name: Some("get_config".into()),args: Some(serde_json::json!({})),+ session_id: None,};if let Ok(r2) = crate::serve::send_request(&socket_path, &req2) {if let Some(result) = r2.result {diff --git a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rsindex 5347d80f12..74be7c52de 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs@@ -52,11 +52,21 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {);}+ // Mint this MCP session's identity once at proxy startup. One proxy process+ // == one MCP session; the daemon outlives it. We stamp this id on every+ // forwarded request so the daemon can OWN and CLEAN UP this session's+ // state (recording, config overrides) and tear it down on disconnect via+ // a `session_end` signal. Dep-free `pid + start-nanos` is sufficient for+ // daemon-local uniqueness over this proxy's lifetime (no `uuid` crate dep+ // for one mint).+ let session_id = mint_session_id();+ debug!(session_id = %session_id, "proxy session minted");+// Cache the tool list once at startup. The daemon's registry is// static for the lifetime of the daemon, so polling on every// `tools/list` would waste a round-trip per call. Swift does the// same caching in `fetchProxyToolList`.- let cached_tools_list = fetch_tools_list_from_daemon(&socket_path)?;+ let cached_tools_list = fetch_tools_list_from_daemon(&socket_path, &session_id)?;let cached_tools_list = Arc::new(cached_tools_list);let stdin = tokio::io::stdin();@@ -69,7 +79,7 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {line.clear();let n = reader.read_line(&mut line).await?;if n == 0 {- break; // EOF+ break; // EOF — MCP client disconnected (stdin closed).}let trimmed = line.trim();if trimmed.is_empty() {@@ -88,7 +98,7 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {}Ok(req) => {let id = req.id.clone().unwrap_or(serde_json::Value::Null);- handle_proxy_request(req, id, &socket_path, &cached_tools_list).await+ handle_proxy_request(req, id, &socket_path, &cached_tools_list, &session_id).await}};@@ -104,15 +114,79 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {writer.flush().await?;}+ // Reached on a clean stdin EOF (the `n == 0` break above) — the normal+ // "MCP client disconnected" seam, which is what real clients do when they+ // close stdio. (An I/O error inside the loop instead propagates via `?`+ // and skips this block; that rare path is covered by the daemon-side+ // recording idle-TTL backstop in `serve.rs`, so the SCStream still can't+ // run forever.) Send a single best-effort `session_end` so the daemon drops+ // every piece of state THIS session owns — its recording (so the SCStream+ // doesn't keep capturing ~6 GB/h after we exit) and its config overrides.+ //+ // The daemon's `stop_owner(session_id)` no-ops if a later client clobbered+ // our recording (a newer `start_recording` re-stamped the owner), so our+ // disconnect can't stop a recording we no longer own. Best-effort: the+ // daemon may already be gone, and an OLD daemon returns "Unknown method"+ // (the `other =>` arm) — both are swallowed so teardown degrades to today's+ // no-cleanup without failing the exit.+ //+ // DEFERRED (follow-up): a generic per-session idle reaper for the proxy+ // SIGKILL/crash path that skips this EOF block. The daemon-global recording+ // idle-TTL backstop is an acceptable interim cover for the recording leak;+ // there is no merged config TTL yet, so a SIGKILLed session's config+ // overrides linger until the daemon restarts — a small, bounded in-memory+ // leak tracked for the reaper PR.+ let end_req = DaemonRequest {+ method: "session_end".into(),+ name: None,+ args: None,+ session_id: Some(session_id.clone()),+ };+ // `send_request` is sync + blocking; we're past the read loop and about to+ // exit, so a direct blocking call on this thread is fine (no reactor+ // starvation concern). It inherits send_request's connect/read timeouts,+ // bounding a wedged-daemon delay to ~10s — acceptable for a teardown.+ match crate::serve::send_request(&socket_path, &end_req) {+ Ok(r) if !r.ok => {+ // Old daemon (pre-session-identity) → "Unknown method"; degrade+ // gracefully to today's no-cleanup. Newer daemon always ACKs ok.+ debug!("proxy-exit session_end not honored (old daemon?): {:?}", r.error)+ }+ Err(e) => warn!("proxy-exit session_end transport error: {e}"),+ _ => debug!("proxy-exit session_end sent"),+ }+Ok(())}+/// Mint a session id unique among the live proxies sharing one daemon, for the+/// lifetime of this proxy process. `pid + process-start nanos` is dep-free and+/// sufficient: two proxies can't share a pid concurrently, and the nanos guard+/// disambiguates pid reuse across the daemon's lifetime. We deliberately avoid+/// the `uuid` crate — a single v4 mint isn't worth a new dependency.+fn mint_session_id() -> String {+ let pid = std::process::id();+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);+ format!("mcp-{pid}-{nanos}")+}+/// One-shot daemon `list` over the UDS, reshaped into a MCP/// `tools/list` result. The daemon now returns the full ToolDef/// (`name`, `description`, `input_schema`, annotation hints) per/// commit 3's `serve.rs` change.-fn fetch_tools_list_from_daemon(socket_path: &str) -> anyhow::Result<serde_json::Value> {- let req = DaemonRequest { method: "list".into(), name: None, args: None };+fn fetch_tools_list_from_daemon(+ socket_path: &str,+ session_id: &str,+) -> anyhow::Result<serde_json::Value> {+ let req = DaemonRequest {+ method: "list".into(),+ name: None,+ args: None,+ session_id: Some(session_id.to_owned()),+ };let resp = send_request(socket_path, &req)?;if !resp.ok {anyhow::bail!(@@ -184,6 +258,7 @@ async fn handle_proxy_request(id: serde_json::Value,socket_path: &str,cached_tools_list: &Arc<serde_json::Value>,+ session_id: &str,) -> Response {match req.method.as_str() {"initialize" => Response::ok(id, initialize_result()),@@ -192,7 +267,7 @@ async fn handle_proxy_request("tools/call" => match req.tool_call() {Err(e) => Response::error(id, -32602, format!("Invalid params: {e}")),- Ok(call) => forward_tool_call(id, call.name, call.args, socket_path).await,+ Ok(call) => forward_tool_call(id, call.name, call.args, socket_path, session_id).await,},other => {@@ -220,11 +295,13 @@ async fn forward_tool_call(name: String,args: serde_json::Value,socket_path: &str,+ session_id: &str,) -> Response {let req = DaemonRequest {method: "call".into(),name: Some(name.clone()),args: Some(args),+ session_id: Some(session_id.to_owned()),};// The daemon client is sync, so jump to a blocking thread to keepdiff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rsindex 30dbad8e83..9d50a55027 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs@@ -19,6 +19,77 @@use serde::{Deserialize, Serialize};+// ── Recording idle-TTL backstop (#1764) ─────────────────────────────────────────++/// Default TTL of zero `call` activity after which an active recording is+/// auto-stopped. Generous: a single agent turn can be slow. Overridable via the+/// `CUA_DRIVER_RS_RECORDING_IDLE_TTL_SECS` env var (used by the #1764 verify+/// harness to exercise the backstop quickly).+const RECORDING_IDLE_TTL_SECS_DEFAULT: u64 = 300;++/// Wall-clock seconds since the Unix epoch. Same idiom `recording.rs` uses for+/// `now_ms`.+fn now_unix_secs() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs()+}++/// Resolve the recording idle TTL, honoring the env override.+fn recording_idle_ttl_secs() -> u64 {+ std::env::var("CUA_DRIVER_RS_RECORDING_IDLE_TTL_SECS")+ .ok()+ .and_then(|v| v.parse::<u64>().ok())+ .filter(|v| *v > 0)+ .unwrap_or(RECORDING_IDLE_TTL_SECS_DEFAULT)+}++/// Spawn a detached daemon task that auto-stops a recording after the idle TTL.+///+/// Defense-in-depth for #1764: the primary teardown is the MCP proxy's+/// stop-on-exit hook (`proxy.rs`). This TTL covers the case the proxy can't run+/// its hook — proxy SIGKILL/crash, or a non-proxy client that dies holding a+/// connection. It MUST NOT stop a still-active session: it only reaps when BOTH+/// the recording is enabled AND there has been no `call` activity for the full+/// TTL. As long as a session keeps issuing tool calls, `last_activity` is bumped+/// every turn and the idle window never reaches the TTL. `stop()` is idempotent,+/// so racing with the proxy-exit hook or an explicit `stop_recording` is benign.+fn spawn_recording_idle_backstop(+ registry: std::sync::Arc<cua_driver_core::tool::ToolRegistry>,+ last_activity: std::sync::Arc<std::sync::atomic::AtomicU64>,+) {+ let ttl = recording_idle_ttl_secs();+ tokio::spawn(async move {+ // 30s tick granularity: reap latency is `ttl` rounded up to the next+ // tick, so a sub-30s TTL override (e.g. in tests) still fires no sooner+ // than ~30s. Fine for the 300s production default.+ let mut tick = tokio::time::interval(std::time::Duration::from_secs(30));+ loop {+ tick.tick().await;+ if registry.recording.current_state().enabled {+ let idle = now_unix_secs().saturating_sub(+ last_activity.load(std::sync::atomic::Ordering::Relaxed),+ );+ if idle >= ttl {+ tracing::warn!(+ "recording idle {idle}s ≥ {ttl}s TTL; auto-stopping \+ (proxy-exit hook likely missed)"+ );+ // Unconditional (`None`): the idle backstop is a last-resort+ // GLOBAL kill of whatever recording is active after global+ // inactivity — not an owner reclaiming a specific session.+ // It already targets the live recording by definition, so a+ // requester id would be redundant and could only make it+ // wrongly no-op. Session-scoped teardown is the proxy-exit+ // `session_end` path (#1764 / session-identity work).+ let _ = registry.recording.stop_owner(None);+ }+ }+ }+ });+}+// ── Paths ─────────────────────────────────────────────────────────────────────/// Returns the platform default socket/pipe path.@@ -85,6 +156,16 @@ pub struct DaemonRequest {pub name: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub args: Option<serde_json::Value>,+ /// MCP-session identity minted once per `cua-driver mcp` proxy process and+ /// stamped on every forwarded request. The daemon uses it to OWN and CLEAN+ /// UP session-scoped state (recording, config overrides). Absent (`None`)+ /// means an anonymous/"global" session — a one-shot `cua-driver call` or a+ /// legacy proxy that predates this field — which keeps today's behavior.+ /// `skip_serializing_if = Option::is_none` makes the absent case+ /// byte-identical on the wire, so old clients and daemons interoperate.+ /// serde defaults a missing field to `None` on deserialize.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub session_id: Option<String>,}#[derive(Debug, Serialize, Deserialize)]@@ -149,7 +230,7 @@ pub fn is_daemon_listening(socket_path: &str) -> bool {}#[cfg(not(target_os = "windows"))]{- let req = DaemonRequest { method: "list".into(), name: None, args: None };+ let req = DaemonRequest { method: "list".into(), name: None, args: None, session_id: None };send_request(socket_path, &req).ok().map(|r| r.ok)@@ -274,12 +355,25 @@ pub async fn run_serve(let (shutdown_tx, mut shutdown_rx) = tokio::sync::oneshot::channel::<()>();let shutdown_tx = std::sync::Arc::new(tokio::sync::Mutex::new(Some(shutdown_tx)));+ // Idle-TTL recording backstop (#1764). The recorder is a daemon-global+ // singleton; the primary teardown path is the MCP proxy's exit hook+ // (proxy.rs), which sends `stop_recording` when the client disconnects.+ // This TTL is defense-in-depth for the case the proxy can't run its hook+ // (SIGKILL/crash, or a non-proxy client that holds a connection and dies).+ // We track the last `call` activity timestamp; a background task auto-stops+ // the recording after `RECORDING_IDLE_TTL_SECS` of zero tool activity. It is+ // keyed on call activity (NOT connection liveness), so an actively-used+ // session — one issuing tool calls every turn — is never reaped.+ let last_activity = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(now_unix_secs()));+ spawn_recording_idle_backstop(registry.clone(), last_activity.clone());+loop {tokio::select! {result = listener.accept() => {let (stream, _) = result?;let reg = registry.clone();let shutdown_tx2 = shutdown_tx.clone();+ let last_activity = last_activity.clone();tokio::spawn(async move {let (reader, mut writer) = stream.into_split();@@ -357,6 +451,12 @@ pub async fn run_serve(}}"call" => {+ // Recording idle-TTL liveness: any serviced tool+ // call counts as activity (#1764).+ last_activity.store(+ now_unix_secs(),+ std::sync::atomic::Ordering::Relaxed,+ );let raw_name = req.name.as_deref().unwrap_or("").to_owned();// Deprecated alias: `type_text_chars` → `type_text`.// Mirrors Swift's `ToolRegistry.call` aliasing.@@ -364,9 +464,30 @@ pub async fn run_serve(eprintln!("[cua-driver-rs] deprecated tool name 'type_text_chars' — use 'type_text' instead.");"type_text".to_owned()} else { raw_name.clone() };- let args = req.args.unwrap_or(serde_json::Value::Object(+ let mut args = req.args.unwrap_or(serde_json::Value::Object(serde_json::Map::new()));+ // Inject the proxy-minted session identity into+ // the tool args under the reserved `_session_id`+ // key so session-aware tools can read it via+ // ArgsExt (the same path cursor_id uses). Only+ // when the client sent a session_id AND the args+ // is an object that doesn't already carry the+ // key (so an explicit client value wins, and a+ // non-object arg is left untouched). The daemon+ // never validates args against input_schema, so+ // this extra key is safe; recording strips all+ // `_`-prefixed keys before persisting a turn.+ if let Some(sid) = &req.session_id {+ if let Some(obj) = args.as_object_mut() {+ if !obj.contains_key("_session_id") {+ obj.insert(+ "_session_id".to_owned(),+ serde_json::Value::String(sid.clone()),+ );+ }+ }+ }if reg.get_def(&tool_name).is_none() {let resp = DaemonResponse::err(format!("Unknown tool: {tool_name}"), 64@@ -408,6 +529,26 @@ pub async fn run_serve((serde_json::to_string(&resp).unwrap() + "\n").as_bytes()).await;}+ "session_end" => {+ // Session lifecycle teardown: the proxy sends+ // this best-effort on stdin EOF (client+ // disconnect), carrying its own session_id. Drop+ // that session's owned state — stop its recording+ // (no-op if a later session clobbered it) and+ // clear its config overrides via the registered+ // platform cleanup hooks. Always ACK ok so the+ // proxy's best-effort teardown sees success.+ if let Some(sid) = req.session_id.as_deref() {+ let _ = reg.recording.stop_owner(Some(sid));+ cua_driver_core::session::fire_session_end(sid);+ }+ let resp = DaemonResponse::ok(+ serde_json::json!({"session_end": true})+ );+ let _ = writer.write_all(+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()+ ).await;+ }other => {let resp = DaemonResponse::err(format!("Unknown method: {other}"), 65@@ -651,6 +792,11 @@ pub async fn run_serve(let (shutdown_tx, mut shutdown_rx) = tokio::sync::oneshot::channel::<()>();let shutdown_tx = std::sync::Arc::new(tokio::sync::Mutex::new(Some(shutdown_tx)));+ // Idle-TTL recording backstop (#1764). See the unix branch above for the+ // full rationale; the leak (record_video via ffmpeg) is platform-independent.+ let last_activity = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(now_unix_secs()));+ spawn_recording_idle_backstop(registry.clone(), last_activity.clone());+loop {// Create a new pipe server instance to accept the next client.// Use create_with_security_attributes_raw so Medium-IL clients can@@ -677,6 +823,7 @@ pub async fn run_serve(let reg = registry.clone();let shutdown_tx2 = shutdown_tx.clone();+ let last_activity = last_activity.clone();tokio::spawn(async move {let (reader, mut writer) = tokio::io::split(server);@@ -739,12 +886,32 @@ pub async fn run_serve().await;}"call" => {+ // Recording idle-TTL liveness (#1764).+ last_activity.store(+ now_unix_secs(),+ std::sync::atomic::Ordering::Relaxed,+ );let raw_name = req.name.as_deref().unwrap_or("").to_owned();let tool_name = if raw_name == "type_text_chars" {eprintln!("[cua-driver-rs] deprecated tool name 'type_text_chars' — use 'type_text' instead.");"type_text".to_owned()} else { raw_name.clone() };- let args = req.args.unwrap_or(serde_json::Value::Object(serde_json::Map::new()));+ let mut args = req.args.unwrap_or(serde_json::Value::Object(serde_json::Map::new()));+ // Inject the proxy-minted session identity under+ // the reserved `_session_id` key (see the unix+ // branch above for the full rationale). Only when+ // a session_id was sent and the args object+ // doesn't already carry the key.+ if let Some(sid) = &req.session_id {+ if let Some(obj) = args.as_object_mut() {+ if !obj.contains_key("_session_id") {+ obj.insert(+ "_session_id".to_owned(),+ serde_json::Value::String(sid.clone()),+ );+ }+ }+ }if reg.get_def(&tool_name).is_none() {let resp = DaemonResponse::err(format!("Unknown tool: {tool_name}"), 64);let _ = writer.write_all(@@ -778,6 +945,21 @@ pub async fn run_serve((serde_json::to_string(&resp).unwrap() + "\n").as_bytes()).await;}+ "session_end" => {+ // Session lifecycle teardown (see the unix branch+ // above). Drop the disconnecting session's owned+ // recording + config overrides, then ACK ok.+ if let Some(sid) = req.session_id.as_deref() {+ let _ = reg.recording.stop_owner(Some(sid));+ cua_driver_core::session::fire_session_end(sid);+ }+ let resp = DaemonResponse::ok(+ serde_json::json!({"session_end": true})+ );+ let _ = writer.write_all(+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()+ ).await;+ }other => {let resp = DaemonResponse::err(format!("Unknown method: {other}"), 65);let _ = writer.write_all(@@ -881,7 +1063,7 @@ pub fn run_stop_cmd(socket_path: &str) {std::process::exit(1);}- let req = DaemonRequest { method: "shutdown".into(), name: None, args: None };+ let req = DaemonRequest { method: "shutdown".into(), name: None, args: None, session_id: None };match send_request(socket_path, &req) {Ok(_) => {// Poll until daemon stops responding (up to 2 seconds).diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rsindex 041dcc05d0..7da57f73ab 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs@@ -201,7 +201,15 @@ impl Tool for ClickTool {"debug_image_out requires window_id."),Some(wid) => {- let max_dim = self.state.config.read().unwrap().max_image_dimension;+ // Session-effective max dimension so debug_image_out+ // matches the resize the calling session sees in+ // get_window_state (precedence: session override > global).+ let max_dim = self.state.session_config+ .effective(+ args.opt_str("_session_id").as_deref(),+ &self.state.config.read().unwrap(),+ )+ .1;let dbg_path_c = dbg_path.clone();let dbg_result = tokio::task::spawn_blocking(move || {let png = crate::capture::screenshot_window_bytes(wid)?;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 56681ec8c7..7d79c8ad6d 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@@ -31,8 +31,16 @@ fn def() -> &'static ToolDef {impl Tool for GetConfigTool {fn def(&self) -> &ToolDef { def() }- async fn invoke(&self, _args: Value) -> ToolResult {- let cfg = self.state.config.read().unwrap();+ async fn invoke(&self, args: Value) -> ToolResult {+ use cua_driver_core::tool_args::ArgsExt;+ // Resolve effective values for the CALLING session: a named session+ // sees its own override layered over the global; the anonymous session+ // (absent `_session_id`) sees the raw global — today's behavior.+ let session_id = args.opt_str("_session_id");+ let (capture_mode, max_image_dimension) = {+ let cfg = self.state.config.read().unwrap();+ self.state.session_config.effective(session_id.as_deref(), &cfg)+ };let cursor_enabled = self.state.cursor_registry.all_states().first().map(|s| s.config.enabled)@@ -46,8 +54,8 @@ impl Tool for GetConfigTool {.with_structured(serde_json::json!({"version": env!("CARGO_PKG_VERSION"),"platform": "macos",- "capture_mode": cfg.capture_mode,- "max_image_dimension": cfg.max_image_dimension,+ "capture_mode": capture_mode,+ "max_image_dimension": max_image_dimension,"agent_cursor": {"enabled": cursor_enabled,},diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rsindex addcb5cf2e..c0b63fe4d8 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs@@ -71,7 +71,13 @@ impl Tool for GetWindowStateTool {s}});- let default_mode = self.state.config.read().unwrap().capture_mode.clone();+ // Effective config resolves call-arg > session-override > global. The+ // daemon injects `_session_id` for named MCP sessions; absent => global.+ let session_id = args.opt_str("_session_id");+ let (default_mode, effective_max_dim) = {+ let cfg = self.state.config.read().unwrap();+ self.state.session_config.effective(session_id.as_deref(), &cfg)+ };let capture_mode = args.opt_str("capture_mode").unwrap_or(default_mode);// Walk AX tree (unless vision-only mode). Accept "tree" as deprecated alias for "ax".@@ -107,8 +113,9 @@ impl Tool for GetWindowStateTool {self.state.element_cache.update(pid, window_id, &r.nodes);}- // Screenshot (unless ax-only mode).- let max_dim = self.state.config.read().unwrap().max_image_dimension;+ // Screenshot (unless ax-only mode). Uses the session-effective max+ // dimension resolved above.+ let max_dim = effective_max_dim;// Returns (b64_or_path, final_w, final_h, Option<original_w>, is_file_path)let screenshot = if capture_mode != "ax" {let out_file = screenshot_out_file.clone();diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rsindex baa5731f67..e1b9f3c389 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs@@ -180,13 +180,80 @@ pub fn write_driver_config_key(key: &str, value: &serde_json::Value) -> Result<(Ok(())}+/// Per-session config overrides layered over the global persisted `DriverConfig`.+///+/// The cua-driver daemon is one shared process: every `cua-driver mcp` proxy+/// connects to it and shares its `ToolState`. `DriverConfig` is therefore+/// multi-tenant AND persisted to disk — so without session scoping, session A's+/// `set_config capture_mode=vision` clobbers session B's value and flips the+/// on-disk default under everyone. These overrides fix that: a named MCP session+/// gets an in-memory, non-persisted override keyed by its `_session_id`; the+/// anonymous session (CLI / one-shot `call`) still writes the shared global ++/// disk. `None` fields mean "fall through to the global layer".+#[derive(Clone, Default)]+pub struct ConfigOverrides {+ pub capture_mode: Option<String>,+ pub max_image_dimension: Option<u32>,+}++/// Thread-safe map of `session_id` → `ConfigOverrides`, mirroring+/// `CursorRegistry`'s registry shape. Cleared per session on `session_end`.+pub struct SessionConfigRegistry {+ inner: std::sync::Mutex<HashMap<String, ConfigOverrides>>,+}++impl SessionConfigRegistry {+ pub fn new() -> Self { Self { inner: std::sync::Mutex::new(HashMap::new()) } }++ /// Merge `delta` into `session`'s overrides (only the `Some` fields of+ /// `delta` overwrite; existing overrides for unset fields are preserved).+ pub fn set(&self, session: &str, delta: ConfigOverrides) {+ let mut map = self.inner.lock().unwrap();+ let entry = map.entry(session.to_owned()).or_default();+ if delta.capture_mode.is_some() {+ entry.capture_mode = delta.capture_mode;+ }+ if delta.max_image_dimension.is_some() {+ entry.max_image_dimension = delta.max_image_dimension;+ }+ }++ /// Resolve the effective config for `session`, layering its overrides over+ /// the global `DriverConfig`. `session = None` (anonymous) returns the+ /// global values verbatim — today's behavior.+ pub fn effective(&self, session: Option<&str>, global: &DriverConfig) -> (String, u32) {+ let ov = session.and_then(|s| self.inner.lock().unwrap().get(s).cloned());+ match ov {+ Some(ov) => (+ ov.capture_mode.unwrap_or_else(|| global.capture_mode.clone()),+ ov.max_image_dimension.unwrap_or(global.max_image_dimension),+ ),+ None => (global.capture_mode.clone(), global.max_image_dimension),+ }+ }++ /// Drop `session`'s overrides. No-op for an unknown id (so `session_end`+ /// for an anonymous / never-set session is harmless).+ pub fn clear(&self, session: &str) {+ self.inner.lock().unwrap().remove(session);+ }+}++impl Default for SessionConfigRegistry {+ fn default() -> Self { Self::new() }+}+/// Shared state passed to all tools.pub struct ToolState {pub element_cache: Arc<ElementCache>,pub cursor_registry: Arc<CursorRegistry>,pub zoom_registry: Arc<ZoomRegistry>,pub resize_registry: Arc<ResizeRegistry>,+ /// Global, disk-persisted config — the base layer and the only one the+ /// anonymous session / CLI writes.pub config: Arc<std::sync::RwLock<DriverConfig>>,+ /// Per-MCP-session in-memory config overrides layered over `config`.+ pub session_config: Arc<SessionConfigRegistry>,}impl Default for ToolState {@@ -199,6 +266,7 @@ impl Default for ToolState {// Load persisted config from ~/.cua-driver/config.json so that// `cua-driver config set` changes carry over into MCP sessions.config: Arc::new(std::sync::RwLock::new(load_driver_config())),+ session_config: Arc::new(SessionConfigRegistry::new()),}}}@@ -213,6 +281,16 @@ pub fn register_all(registry: &mut ToolRegistry, compat: bool) {// resolve element_index → window-local screenshot coords for click.png.crate::recording_hooks::set_element_cache(state.element_cache.clone());+ // Drop a disconnecting session's config overrides on `session_end`. The+ // daemon fans the session id out to this hook; recording ownership is+ // handled separately on the core RecordingSession.+ {+ let session_config = state.session_config.clone();+ cua_driver_core::session::register_session_end_hook(move |session_id| {+ session_config.clear(session_id);+ });+ }+registry.register(Box::new(list_apps::ListAppsTool));registry.register(Box::new(list_windows::ListWindowsTool));registry.register(Box::new(get_window_state::GetWindowStateTool::new(state.clone())));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 532e4478b8..345c881dd0 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@@ -3,7 +3,7 @@ use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};use serde_json::Value;use std::sync::Arc;-use super::{write_driver_config_key, ToolState};+use super::{write_driver_config_key, ConfigOverrides, ToolState};pub struct SetConfigTool {state: Arc<ToolState>,@@ -61,23 +61,50 @@ impl Tool for SetConfigTool {async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;- let mut cfg = self.state.config.write().unwrap();- if let Some(mode) = args.opt_str("capture_mode") {- cfg.capture_mode = mode.clone();- if let Err(e) = write_driver_config_key("capture_mode", &Value::String(mode)) {- tracing::warn!("set_config: failed to persist capture_mode: {e}");+ // The daemon injects `_session_id` for non-anonymous MCP sessions.+ // Absent => anonymous/global session (CLI one-shot, legacy proxy) =>+ // today's behavior: write the shared global DriverConfig + persist to+ // disk. Present => session-scoped in-memory override only, never+ // touching the global config or the on-disk default, so two concurrent+ // sessions don't clobber each other or the persisted default.+ let session_id = args.opt_str("_session_id");++ // Validate max_image_dimension up front so both branches share the+ // u32 check and we never half-apply.+ let max_dim: Option<u32> = match args.opt_u64("max_image_dimension") {+ Some(dim) => match u32::try_from(dim) {+ Ok(d) => Some(d),+ Err(_) => return ToolResult::error(format!("max_image_dimension {dim} exceeds u32::MAX")),+ },+ None => None,+ };+ let capture_mode = args.opt_str("capture_mode");++ let (effective_mode, effective_dim) = if let Some(sid) = session_id.as_deref() {+ // Session-scoped override: in-memory only, no global write, no disk.+ self.state.session_config.set(sid, ConfigOverrides {+ capture_mode: capture_mode.clone(),+ max_image_dimension: max_dim,+ });+ self.state.session_config.effective(Some(sid), &self.state.config.read().unwrap())+ } else {+ // Anonymous/global session: write the shared global + persist,+ // exactly as before this change.+ let mut cfg = self.state.config.write().unwrap();+ if let Some(mode) = capture_mode.clone() {+ cfg.capture_mode = mode.clone();+ if let Err(e) = write_driver_config_key("capture_mode", &Value::String(mode)) {+ tracing::warn!("set_config: failed to persist capture_mode: {e}");+ }}- }- if let Some(dim) = args.opt_u64("max_image_dimension") {- if let Ok(dim32) = u32::try_from(dim) {+ if let Some(dim32) = max_dim {cfg.max_image_dimension = dim32;- if let Err(e) = write_driver_config_key("max_image_dimension", &Value::Number(dim.into())) {+ if let Err(e) = write_driver_config_key("max_image_dimension", &Value::Number(u64::from(dim32).into())) {tracing::warn!("set_config: failed to persist max_image_dimension: {e}");}- } else {- return ToolResult::error(format!("max_image_dimension {dim} exceeds u32::MAX"));}- }+ (cfg.capture_mode.clone(), cfg.max_image_dimension)+ };// 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();@@ -101,9 +128,14 @@ impl Tool for SetConfigTool {pip_note = format!(" — restart cua-driver for experimental_pip_geometry={geom} to take effect");}}+ let scope_note = if session_id.is_some() {+ " (session-scoped; persisted default unchanged)"+ } else {+ ""+ };ToolResult::text(format!(- "Config updated: capture_mode={}, max_image_dimension={}{}",- cfg.capture_mode, cfg.max_image_dimension, pip_note+ "Config updated: capture_mode={}, max_image_dimension={}{}{}",+ effective_mode, effective_dim, scope_note, pip_note))}}