Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-driver-rs)(macos): per-session agent cursors (#1777) (#1779)

Francesco Bonaccida4a17008600
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.mdx
index 7bf024bf4f..8dc947900f 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
@@ -104,8 +104,11 @@ The daemon drives **one** physical machine, and every `cua-driver mcp` client sh
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.
+- **Recording ownership.** `start_recording` stamps the live recording with the calling session. On `session_end` 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 `session_end` 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.
+- **Agent cursor.** Each session owns an overlay cursor keyed by its identity, removed on `session_end` — see [the per-session cursors note](/cua-driver/reference/mcp-tools#set_agent_cursor_enabled).
+
+**How `session_end` fires — the per-session reaper.** Each proxy opens **one long-lived control connection** to the daemon at startup (separate from the per-call connections it opens per tool call) and holds it open for its entire lifetime. When the proxy exits — a clean stdin EOF **or** an ungraceful `kill -9` / crash — the kernel closes that socket, the daemon's reader hits EOF, and it fires `session_end` for that session. This makes cleanup reliable even when the proxy dies without a chance to send anything. Liveness is connection-based, not activity-based: a connected-but-idle session (zero tool calls) keeps its control connection parked open and is never reaped. The daemon idle-TTL on recordings is now only a secondary backstop for a non-proxy client.
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.
@@ -115,7 +118,7 @@ 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.
+- Cleanup is driven by the proxy's persistent control connection, not a best-effort message: on **any** exit (clean stdin EOF, I/O error, or `kill -9` / crash) the kernel closes that connection and the daemon fires `session_end`, dropping this session's owned state (recording, config overrides, agent cursor). `session_end` is idempotent, so a graceful exit and the EOF reaper can't double-fire.
- 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.mdx
index f73097f8a3..9c2cd20983 100644
--- a/docs/content/docs/cua-driver/reference/mcp-tools.mdx
+++ b/docs/content/docs/cua-driver/reference/mcp-tools.mdx
@@ -111,9 +111,11 @@ Pure read-only.
### get_agent_cursor_state
-Return the current state of all agent cursor instances: position, config (color, icon, label, size, opacity), enabled flag.
+Return the current state of **this session's** agent cursor: position, config (color, icon, label, size, opacity), enabled flag. The result is scoped to the cursor the call resolves to (precedence **explicit `cursor_id` > session identity > `"default"`**), so concurrent sessions no longer see each other's cursors and the top-level `enabled` flag is deterministic. Pass `cursor_id` to inspect a specific instance.
-**Arguments:** none.
+**Arguments:**
+
+- `cursor_id` (string, optional): Cursor instance to inspect. Omit it and the call targets the calling session's own cursor (macOS); the anonymous / one-shot path targets `"default"`.
## Action tools
@@ -383,7 +385,7 @@ Move the agent cursor overlay to (x, y). Does NOT move the real mouse cursor —
**Arguments:**
-- `cursor_id` (string, optional): Cursor instance to move. Default: 'default'.
+- `cursor_id` (string, optional): Explicit cursor-instance override. Omit it and the move targets the calling session's own cursor (macOS); the anonymous path targets 'default'. See the per-session agent cursors note under [set_agent_cursor_enabled](#set_agent_cursor_enabled).
- `x` (number, required)
- `y` (number, required)
@@ -452,7 +454,7 @@ Start trajectory recording. Every subsequent action-tool invocation (click, righ
Turn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.
-**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.
+**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 session ends, and the daemon stops only the recording that session owns — so a forgotten session no longer keeps writing to disk. Session-end is detected reliably even on **ungraceful proxy death** (`kill -9`, crash): each proxy holds one long-lived control connection to the daemon, and the kernel closing that socket on proxy exit (graceful **or** killed) fires `session_end`. A daemon-side idle timeout (~5 min of no tool activity) remains as a secondary backstop for a non-proxy client that started a recording and died.
**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+.
@@ -515,9 +517,11 @@ Update cua-driver-rs configuration. Changes to capture_mode and max_image_dimens
- `experimental_pip_geometry` (string, optional): PiP window size + optional position in `WxH` or `WxH+X+Y` form (e.g. `320x200+24+24`). Applies on next daemon restart.
- `max_image_dimension` (integer, optional): Max dimension for screenshot resizing (0 = no limit).
+**Per-session agent cursors (macOS).** The agent cursor is owned per MCP session. On the daemon-proxy path every `cua-driver mcp` client mints a session identity, and that identity is the cursor key when the caller passes no explicit `cursor_id` — so two concurrent sessions each drive their own overlay cursor (distinct auto-assigned colour) drawn simultaneously, instead of clobbering one shared cursor last-writer-wins. The key is resolved with the precedence **explicit `cursor_id` &gt; session identity &gt; `"default"`**: an explicit `cursor_id` stays an orthogonal, user-facing handle, so a wrapper can deliberately share or override a cursor across sessions by passing the same `cursor_id`. When a session ends (`session_end`), that session's cursor is removed from the overlay automatically — including on **ungraceful proxy death** (`kill -9`, crash), because the daemon detects the proxy's control-connection EOF and fires `session_end` without any cooperation from the dying proxy. A late, in-flight cursor command that arrives after removal cannot resurrect the cursor (a render-side tombstone keyed on the session id). The anonymous / one-shot `cua-driver call` path (no session identity, no `cursor_id`) maps to the seeded `"default"` cursor, which is never removed — backward compatible. (Windows/Linux keep the single shared cursor today.)
+
### set_agent_cursor_enabled
-Show or hide the agent cursor overlay for a cursor instance.
+Show or hide the agent cursor overlay for a cursor instance. With no `cursor_id`, this targets the calling session's own cursor (see the per-session note above).
**Arguments:**
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index 2203a84428..526d1cef56 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.6"
+version = "0.4.0"
dependencies = [
"anyhow",
"async-trait",
@@ -305,7 +305,7 @@ dependencies = [
[[package]]
name = "cua-driver-core"
-version = "0.3.6"
+version = "0.4.0"
dependencies = [
"anyhow",
"async-trait",
@@ -320,7 +320,7 @@ dependencies = [
[[package]]
name = "cua-driver-uia"
-version = "0.3.6"
+version = "0.4.0"
dependencies = [
"anyhow",
"cua-driver-core",
@@ -335,7 +335,7 @@ dependencies = [
[[package]]
name = "cursor-overlay"
-version = "0.3.6"
+version = "0.4.0"
dependencies = [
"anyhow",
"image",
@@ -488,7 +488,7 @@ checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
[[package]]
name = "focus-monitor-win"
-version = "0.3.6"
+version = "0.4.0"
dependencies = [
"windows 0.58.0",
]
@@ -1192,7 +1192,7 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pip-preview"
-version = "0.3.6"
+version = "0.4.0"
dependencies = [
"anyhow",
"serde_json",
@@ -1207,7 +1207,7 @@ checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
[[package]]
name = "platform-linux"
-version = "0.3.6"
+version = "0.4.0"
dependencies = [
"anyhow",
"async-trait",
@@ -1228,7 +1228,7 @@ dependencies = [
[[package]]
name = "platform-macos"
-version = "0.3.6"
+version = "0.4.0"
dependencies = [
"anyhow",
"async-trait",
@@ -1241,6 +1241,7 @@ dependencies = [
"foreign-types 0.5.0",
"futures-util",
"image",
+ "indexmap",
"libc",
"objc2",
"objc2-app-kit",
@@ -1260,7 +1261,7 @@ dependencies = [
[[package]]
name = "platform-windows"
-version = "0.3.6"
+version = "0.4.0"
dependencies = [
"anyhow",
"async-trait",
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.rs
index 6d4d6e2684..602d079bf0 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
@@ -189,6 +189,23 @@ impl RecordingSession {
/// gates teardown.
pub fn start(&self, output_dir: &str, record_video: bool, owner: Option<&str>) -> anyhow::Result<()> {
let mut inner = self.inner.lock().unwrap();
+ // Write-boundary resurrection guard — checked INSIDE the lock so the
+ // is_session_ended test is atomic with the enabled/owner write below.
+ // An in-flight start_recording that lands after its owning session ended
+ // (passed the dispatch gate, then the proxy died) must not create a
+ // recording owned by a dead session — a leaked ffmpeg/SCStream. The
+ // teardown sites call `fire_session_end` (which marks ENDED_SESSIONS)
+ // BEFORE `stop_owner`, so either the mark is already set and we bail
+ // here, or we win the lock first and the reaper's later stop_owner(owner)
+ // reaps what we started. Anonymous starts (owner = None: CLI one-shot /
+ // legacy shim) are never gated.
+ if let Some(o) = owner {
+ if crate::session::is_session_ended(o) {
+ anyhow::bail!(
+ "session {o} has ended; refusing to start a recording owned by a dead session"
+ );
+ }
+ }
// If a previous session is still open, gracefully tear it down
// first so the caller doesn't accidentally leak an ffmpeg process.
if let Some(rec) = inner.video.take() {
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.rs
index f66b7d8c10..aa96bb9337 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
@@ -18,16 +18,30 @@
//! `recording.rs` — a registry-free, platform-pluggable hook set with no
//! reverse coupling from core into the platform crates.
+use std::collections::HashSet;
use std::sync::{Mutex, OnceLock};
type SessionEndHook = Box<dyn Fn(&str) + Send + Sync>;
static SESSION_END_HOOKS: OnceLock<Mutex<Vec<SessionEndHook>>> = OnceLock::new();
+/// Session ids that have already had their `session_end` fired. Dedupes the
+/// control-connection EOF teardown (the reaper) against any stray legacy
+/// `session_end` method that a mixed-version (new proxy / old proxy) rollout
+/// might still send — `fire_session_end` is the single fan-out point and must
+/// be idempotent because the overlay Remove + recording stop must run exactly
+/// once. Growth is bounded (one short string per ended session over the
+/// daemon's lifetime); eviction is a deliberate non-blocking follow-up.
+static ENDED_SESSIONS: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
+
fn hooks() -> &'static Mutex<Vec<SessionEndHook>> {
SESSION_END_HOOKS.get_or_init(|| Mutex::new(Vec::new()))
}
+fn ended_sessions() -> &'static Mutex<HashSet<String>> {
+ ENDED_SESSIONS.get_or_init(|| Mutex::new(HashSet::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
@@ -39,9 +53,63 @@ pub fn register_session_end_hook(hook: impl Fn(&str) + Send + Sync + 'static) {
}
/// Fan a session-end out to every registered cleanup hook. Called by the daemon
-/// `session_end` arm. No-op when no hooks are registered.
+/// on control-connection EOF (the reaper) and by the legacy `session_end` method
+/// arm. Idempotent: the FIRST fire for a given `session_id` runs every hook; any
+/// later fire for the same id is a no-op. This dedupes the EOF path against a
+/// stray legacy `session_end` (mixed-version rollout) so cursor-remove +
+/// recording-stop run exactly once. No-op when no hooks are registered.
pub fn fire_session_end(session_id: &str) {
+ // Mark-then-fan-out under a short critical section, releasing the lock
+ // before running hooks (hooks may be slow / re-entrant and must not hold
+ // the dedupe lock).
+ {
+ let mut ended = ended_sessions().lock().unwrap();
+ if !ended.insert(session_id.to_owned()) {
+ return; // already ended — idempotent no-op.
+ }
+ }
for hook in hooks().lock().unwrap().iter() {
hook(session_id);
}
}
+
+/// Whether `fire_session_end` has already run for this `session_id`. The
+/// daemon-side authority for "this session is permanently gone"; the macOS
+/// overlay keeps its own render-side tombstone keyed on the same id.
+pub fn is_session_ended(session_id: &str) -> bool {
+ ended_sessions().lock().unwrap().contains(session_id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::Arc;
+
+ #[test]
+ fn fire_session_end_is_idempotent_per_id() {
+ // Distinct, test-local ids so we don't collide with other tests that
+ // share the process-global ENDED_SESSIONS set.
+ let sid = "test-dedupe-session-AABBCC";
+ let calls = Arc::new(AtomicUsize::new(0));
+ let calls2 = calls.clone();
+ let want = sid.to_owned();
+ register_session_end_hook(move |got| {
+ if got == want {
+ calls2.fetch_add(1, Ordering::Relaxed);
+ }
+ });
+
+ assert!(!is_session_ended(sid));
+ fire_session_end(sid);
+ assert!(is_session_ended(sid));
+ // Second + third fire for the same id must be no-ops.
+ fire_session_end(sid);
+ fire_session_end(sid);
+ assert_eq!(
+ calls.load(Ordering::Relaxed),
+ 1,
+ "hook must run exactly once for a given session id"
+ );
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
index 74be7c52de..865857984b 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
@@ -62,6 +62,33 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {
let session_id = mint_session_id();
debug!(session_id = %session_id, "proxy session minted");
+ // Open ONE long-lived "control" connection to the daemon and hold it open
+ // for this proxy's entire lifetime (separate from the per-call connections
+ // that `send_request` opens and closes per tool call). It sends a single
+ // `session_begin` line and then parks reading — it never writes again and
+ // never closes until this process dies.
+ //
+ // This is the reaper: when the proxy exits (graceful stdin EOF) OR is
+ // SIGKILLed/crashes, the kernel closes this socket; the daemon's
+ // per-connection reader hits EOF and fires `session_end` for `session_id`,
+ // tearing down every piece of state this session owns (overlay cursor,
+ // config overrides, recording). Liveness is connection-based, so an
+ // alive-but-idle session — one issuing zero tool calls — is never reaped:
+ // its control connection stays parked open.
+ //
+ // Detached + fire-and-forget. If the connect races daemon startup and
+ // fails, we log and continue — the per-call `send_request` has its own
+ // retry/timeout, and a restarted daemon loses session state anyway, so a
+ // missing control connection only degrades to no-reaper (the recording
+ // idle-TTL still backstops a leaked recording). It must NOT bail the proxy.
+ {
+ let socket = socket_path.clone();
+ let sid = session_id.clone();
+ tokio::spawn(async move {
+ run_control_connection(socket, sid).await;
+ });
+ }
+
// 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
@@ -115,48 +142,130 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {
}
// 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(),
+ // "MCP client disconnected" seam. Session teardown is NO LONGER done here:
+ // it's fully subsumed by the persistent control connection spawned at
+ // startup. On any proxy exit — graceful stdin EOF (this path), an I/O
+ // error propagated via `?`, OR a SIGKILL/crash — the kernel closes the
+ // control socket, the daemon's reader hits EOF, and it fires
+ // `session_end(session_id)` once (idempotent). That single path reliably
+ // covers the ungraceful-death case the old best-effort exit hook missed.
+ Ok(())
+}
+
+/// Own the proxy's single long-lived control connection. Connects directly to
+/// the daemon socket (its OWN async open — `send_request` is sync, blocking,
+/// and one-shot, so it cannot be reused here), sends one `session_begin` line
+/// carrying `session_id`, then parks in a read loop until the connection
+/// closes. It never writes again. The daemon records `session_id` from
+/// `session_begin` and fires `session_end` when this connection EOFs — which
+/// the kernel triggers on proxy exit AND on kill -9.
+///
+/// On any read result/error (daemon-side close, broken pipe), the loop exits
+/// and the task ends; the proxy keeps running on its per-call connections. A
+/// connect failure (racing daemon startup) is logged and swallowed — it must
+/// not bail the proxy.
+async fn run_control_connection(socket_path: String, session_id: String) {
+ let begin = DaemonRequest {
+ method: "session_begin".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)
+ let line = match serde_json::to_string(&begin) {
+ Ok(s) => s + "\n",
+ Err(e) => {
+ warn!("control connection: serialize session_begin failed: {e}");
+ return;
+ }
+ };
+
+ #[cfg(unix)]
+ {
+ use tokio::net::UnixStream;
+ // Retry the connect briefly — the daemon may still be spinning up
+ // (mirrors the windows pipe-open retry below). The is_daemon_listening
+ // precheck makes the window tiny, but keep both paths symmetric.
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
+ let mut stream = loop {
+ match UnixStream::connect(&socket_path).await {
+ Ok(s) => break s,
+ Err(_) if std::time::Instant::now() < deadline => {
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ Err(e) => {
+ debug!(session_id = %session_id, "control connect failed (daemon starting?): {e}");
+ return;
+ }
+ }
+ };
+ if let Err(e) = stream.write_all(line.as_bytes()).await {
+ debug!("control connection: write session_begin failed: {e}");
+ return;
+ }
+ let _ = stream.flush().await;
+ debug!(session_id = %session_id, "control connection established (session_begin sent)");
+
+ // Park: read until the daemon closes (it ACKs session_begin then keeps
+ // the conn open; we drain anything and only return on EOF/error). The
+ // proxy never writes here again — the connection lives until process
+ // death, when the kernel closes it and the daemon reaps the session.
+ let mut reader = BufReader::new(stream);
+ let mut buf = String::new();
+ loop {
+ buf.clear();
+ match reader.read_line(&mut buf).await {
+ Ok(0) | Err(_) => break, // daemon closed or error — task done.
+ Ok(_) => continue, // ACK / stray line — ignore, keep parked.
+ }
}
- Err(e) => warn!("proxy-exit session_end transport error: {e}"),
- _ => debug!("proxy-exit session_end sent"),
+ debug!(session_id = %session_id, "control connection closed");
}
- Ok(())
+ #[cfg(all(not(unix), target_os = "windows"))]
+ {
+ use tokio::net::windows::named_pipe::ClientOptions;
+ // Retry the pipe open briefly — the daemon may still be spinning up its
+ // next instance (mirrors send_request's open-retry).
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
+ let client = loop {
+ match ClientOptions::new().open(&socket_path) {
+ Ok(c) => break Some(c),
+ Err(_) if std::time::Instant::now() < deadline => {
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ Err(e) => {
+ debug!(session_id = %session_id, "control pipe open failed (daemon starting?): {e}");
+ break None;
+ }
+ }
+ };
+ let mut client = match client {
+ Some(c) => c,
+ None => return,
+ };
+ if let Err(e) = client.write_all(line.as_bytes()).await {
+ debug!("control connection: write session_begin failed: {e}");
+ return;
+ }
+ let _ = client.flush().await;
+ debug!(session_id = %session_id, "control connection established (session_begin sent)");
+
+ let mut reader = BufReader::new(client);
+ let mut buf = String::new();
+ loop {
+ buf.clear();
+ match reader.read_line(&mut buf).await {
+ Ok(0) | Err(_) => break,
+ Ok(_) => continue,
+ }
+ }
+ debug!(session_id = %session_id, "control connection closed");
+ }
+
+ #[cfg(all(not(unix), not(target_os = "windows")))]
+ {
+ let _ = (line, session_id, socket_path);
+ }
}
/// Mint a session id unique among the live proxies sharing one daemon, for the
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
index 9d50a55027..d1e029c147 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -47,10 +47,11 @@ fn recording_idle_ttl_secs() -> u64 {
/// 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
+/// Defense-in-depth for #1764: the primary teardown is now the per-session
+/// reaper (the proxy's persistent control connection EOF fires `session_end`,
+/// covering proxy SIGKILL/crash). This TTL covers the residual case a non-proxy
+/// raw client starts a recording and dies without ever sending `session_begin`.
+/// 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,
@@ -83,7 +84,14 @@ fn spawn_recording_idle_backstop(
// 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);
+ // stop_owner can SYNCHRONOUSLY finalize the recording's mp4
+ // (SCStream::stop_capture blocks on disk I/O), so run it on a
+ // blocking thread to keep the reactor free (see the EOF reaper).
+ let reg2 = registry.clone();
+ let _ = tokio::task::spawn_blocking(move || {
+ reg2.recording.stop_owner(None)
+ })
+ .await;
}
}
}
@@ -355,15 +363,16 @@ 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.
+ // Idle-TTL recording backstop (#1764), now demoted to SECONDARY cover. The
+ // PRIMARY teardown is the per-session reaper: the proxy holds a persistent
+ // control connection (session_begin) whose EOF — on graceful exit AND on
+ // kill -9 — fires session_end, stopping that session's recording reliably.
+ // This TTL still uniquely covers (a) a non-proxy raw client that starts a
+ // recording and dies without ever sending session_begin and (b) a
+ // daemon-internal wedge. We track the last `call` activity timestamp; a
+ // background task auto-stops the recording after `RECORDING_IDLE_TTL_SECS`
+ // of zero tool activity. Keyed on call activity (NOT connection liveness),
+ // so an actively-used session 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());
@@ -379,6 +388,14 @@ pub async fn run_serve(
let (reader, mut writer) = stream.into_split();
let mut lines = BufReader::new(reader).lines();
+ // Set ONLY by a `session_begin` on this connection — i.e.
+ // the proxy's persistent control connection. Per-call
+ // connections (call/list/describe) leave this None, so
+ // their immediate EOF triggers NO teardown. When a control
+ // connection EOFs (graceful proxy exit OR kill -9, both
+ // kernel-guaranteed), the post-loop block reaps the session.
+ let mut control_session_id: Option<String> = None;
+
while let Ok(Some(line)) = lines.next_line().await {
let req: DaemonRequest = match serde_json::from_str(&line) {
Ok(r) => r,
@@ -488,6 +505,38 @@ pub async fn run_serve(
}
}
}
+ // Resurrection guard: a call carrying a session
+ // id whose session has already ended (control
+ // connection EOF → fire_session_end) must NOT
+ // run. The render-side overlay tombstone blocks
+ // the visible ghost cursor, but the metadata
+ // CursorRegistry and config-override map are
+ // get-or-create — an in-flight per-call request
+ // that lands AFTER session_end (a slow AX click,
+ // a racing set_config) would re-create
+ // session-owned state that is never reaped
+ // again. Skip the invoke and return a benign ok
+ // so no registry/override/recording state is
+ // created or mutated. ONLY gate when a session
+ // id is present AND ended — a live session and
+ // anonymous/one-shot calls (no session id) pass
+ // through unchanged.
+ if let Some(sid) = &req.session_id {
+ if cua_driver_core::session::is_session_ended(sid) {
+ let resp = DaemonResponse::ok(serde_json::json!({
+ "content": [{
+ "type": "text",
+ "text": "session ended; tool call ignored"
+ }],
+ "isError": false,
+ "sessionEnded": true
+ }));
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ continue;
+ }
+ }
if reg.get_def(&tool_name).is_none() {
let resp = DaemonResponse::err(
format!("Unknown tool: {tool_name}"), 64
@@ -529,18 +578,51 @@ pub async fn run_serve(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
}
+ "session_begin" => {
+ // The proxy's persistent control connection.
+ // Record the session_id so this connection's EOF
+ // (graceful proxy exit OR kill -9) reaps the
+ // session in the post-loop block below. This is
+ // the ONLY place a connection is marked control;
+ // per-call connections never send this. ACK ok.
+ if let Some(sid) = req.session_id.as_deref() {
+ control_session_id = Some(sid.to_owned());
+ }
+ let resp = DaemonResponse::ok(
+ serde_json::json!({"session_begin": true})
+ );
+ let _ = writer.write_all(
+ (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.
+ // Legacy back-compat: a new-daemon/old-proxy
+ // pairing still sends this explicitly on graceful
+ // stdin EOF. It arrives on a per-call connection
+ // (control_session_id stays None) so it does NOT
+ // double-fire against the EOF reaper, and
+ // fire_session_end is idempotent regardless. New
+ // proxies never send it — the control-connection
+ // EOF is the single teardown path. Always ACK ok.
if let Some(sid) = req.session_id.as_deref() {
- let _ = reg.recording.stop_owner(Some(sid));
+ // stop_owner can SYNCHRONOUSLY finalize the
+ // recording's mp4 — run it off the reactor on
+ // a blocking thread (see the EOF reaper).
+ // fire_session_end stays inline (non-blocking).
+ // Mark the session ended FIRST so an in-flight
+ // start_recording sees ended=true and bails — the
+ // mark-before-reap invariant the cursor/config hooks
+ // already satisfy (their reap runs inside
+ // fire_session_end, after the mark). stop_owner does
+ // not consult is_session_ended, so reaping after the
+ // mark is safe.
cua_driver_core::session::fire_session_end(sid);
+ let reg2 = reg.clone();
+ let sid_for_stop = sid.to_owned();
+ let _ = tokio::task::spawn_blocking(move || {
+ reg2.recording.stop_owner(Some(&sid_for_stop))
+ })
+ .await;
}
let resp = DaemonResponse::ok(
serde_json::json!({"session_end": true})
@@ -559,6 +641,35 @@ pub async fn run_serve(
}
}
}
+
+ // Reader EOF (`while let` exited): the kernel closes the
+ // socket on graceful proxy exit AND on kill -9. If this was
+ // the proxy's persistent control connection, reap the
+ // session now — the reliable ungraceful-death teardown that
+ // the old graceful-only proxy-exit hook could not provide.
+ // Per-call connections leave control_session_id None, so
+ // their (immediate) EOF is a no-op here. fire_session_end is
+ // idempotent, so racing a legacy explicit session_end is
+ // benign.
+ if let Some(sid) = control_session_id {
+ // stop_owner can SYNCHRONOUSLY finalize the recording's
+ // mp4 — on macOS it hits SCStream::stop_capture(), which
+ // blocks on disk I/O (video_sckit.rs). Run it on a
+ // blocking thread so it does not stall a runtime worker.
+ // fire_session_end stays inline: its hooks (overlay
+ // Remove, config-override clear) are non-blocking.
+ // Mark the session ended FIRST so an in-flight start_recording
+ // sees ended=true and bails (mark-before-reap; the cursor/config
+ // hooks already reap inside fire_session_end after the mark).
+ // stop_owner ignores is_session_ended, so reaping after is safe.
+ cua_driver_core::session::fire_session_end(&sid);
+ let reg2 = reg.clone();
+ let sid_for_stop = sid.clone();
+ let _ = tokio::task::spawn_blocking(move || {
+ reg2.recording.stop_owner(Some(&sid_for_stop))
+ })
+ .await;
+ }
});
}
_ = &mut shutdown_rx => {
@@ -829,6 +940,13 @@ pub async fn run_serve(
let (reader, mut writer) = tokio::io::split(server);
let mut lines = BufReader::new(reader).lines();
+ // See the unix branch: set only by `session_begin` on the
+ // proxy's persistent control connection; drives the post-loop
+ // EOF reaper. Named-pipe peer death surfaces as
+ // ERROR_BROKEN_PIPE on the next read, ending the while-let
+ // loop equally reliably.
+ let mut control_session_id: Option<String> = None;
+
while let Ok(Some(line)) = lines.next_line().await {
let req: DaemonRequest = match serde_json::from_str(&line) {
Ok(r) => r,
@@ -912,6 +1030,30 @@ pub async fn run_serve(
}
}
}
+ // Resurrection guard (see the unix branch above
+ // for the full rationale): a call carrying an
+ // already-ended session id must NOT run — it
+ // would re-create session-owned metadata
+ // (CursorRegistry / config override) that the
+ // reaper has already passed. Skip + benign ok.
+ // Only when a session id is present AND ended;
+ // live and anonymous calls pass through.
+ if let Some(sid) = &req.session_id {
+ if cua_driver_core::session::is_session_ended(sid) {
+ let resp = DaemonResponse::ok(serde_json::json!({
+ "content": [{
+ "type": "text",
+ "text": "session ended; tool call ignored"
+ }],
+ "isError": false,
+ "sessionEnded": true
+ }));
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ continue;
+ }
+ }
if reg.get_def(&tool_name).is_none() {
let resp = DaemonResponse::err(format!("Unknown tool: {tool_name}"), 64);
let _ = writer.write_all(
@@ -945,13 +1087,44 @@ pub async fn run_serve(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
}
+ "session_begin" => {
+ // The proxy's persistent control connection (see
+ // the unix branch). Record the session_id so this
+ // pipe instance's EOF / broken-pipe reaps the
+ // session in the post-loop block below. ACK ok.
+ if let Some(sid) = req.session_id.as_deref() {
+ control_session_id = Some(sid.to_owned());
+ }
+ let resp = DaemonResponse::ok(
+ serde_json::json!({"session_begin": true})
+ );
+ let _ = writer.write_all(
+ (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.
+ // Legacy back-compat (see the unix branch). Per-call
+ // connection; control_session_id stays None so no
+ // EOF double-fire. fire_session_end is idempotent.
if let Some(sid) = req.session_id.as_deref() {
- let _ = reg.recording.stop_owner(Some(sid));
+ // stop_owner can SYNCHRONOUSLY finalize the
+ // recording's mp4 — run it off the reactor on
+ // a blocking thread (see the EOF reaper).
+ // fire_session_end stays inline (non-blocking).
+ // Mark the session ended FIRST so an in-flight
+ // start_recording sees ended=true and bails — the
+ // mark-before-reap invariant the cursor/config hooks
+ // already satisfy (their reap runs inside
+ // fire_session_end, after the mark). stop_owner does
+ // not consult is_session_ended, so reaping after the
+ // mark is safe.
cua_driver_core::session::fire_session_end(sid);
+ let reg2 = reg.clone();
+ let sid_for_stop = sid.to_owned();
+ let _ = tokio::task::spawn_blocking(move || {
+ reg2.recording.stop_owner(Some(&sid_for_stop))
+ })
+ .await;
}
let resp = DaemonResponse::ok(
serde_json::json!({"session_end": true})
@@ -968,6 +1141,28 @@ pub async fn run_serve(
}
}
}
+
+ // Reader EOF / ERROR_BROKEN_PIPE: named-pipe peer death on
+ // graceful proxy exit AND kill -9. Reap the session if this
+ // was the proxy's control connection (see the unix branch for
+ // the full rationale). Per-call connections leave
+ // control_session_id None.
+ if let Some(sid) = control_session_id {
+ // Run stop_owner off the reactor (see the unix branch):
+ // recording finalize can be a synchronous blocking call.
+ // fire_session_end stays inline (non-blocking hooks).
+ // Mark the session ended FIRST so an in-flight start_recording
+ // sees ended=true and bails (mark-before-reap; the cursor/config
+ // hooks already reap inside fire_session_end after the mark).
+ // stop_owner ignores is_session_ended, so reaping after is safe.
+ cua_driver_core::session::fire_session_end(&sid);
+ let reg2 = reg.clone();
+ let sid_for_stop = sid.clone();
+ let _ = tokio::task::spawn_blocking(move || {
+ reg2.recording.stop_owner(Some(&sid_for_stop))
+ })
+ .await;
+ }
});
}
_ = &mut shutdown_rx => {
@@ -1109,3 +1304,176 @@ pub fn run_status_cmd(socket_path: &str, pid_file_path: &str) {
std::process::exit(1);
}
}
+
+// ── Tests ───────────────────────────────────────────────────────────────────
+
+#[cfg(all(test, unix))]
+mod gate_tests {
+ //! Ended-session resurrection guard wired into the `call` dispatch.
+ //!
+ //! Closes PR #1779's gap: `is_session_ended()` was dead code, so an
+ //! in-flight per-call request landing AFTER `session_end` fired would
+ //! re-create session-owned metadata (cursor registry / config override)
+ //! the reaper already passed. The gate skips a `call` carrying an ended
+ //! session id (benign ok); live and anonymous calls pass through.
+
+ use super::{run_serve, send_request, DaemonRequest};
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::Arc;
+
+ use async_trait::async_trait;
+ use cua_driver_core::protocol::ToolResult;
+ use cua_driver_core::tool::{Tool, ToolDef, ToolRegistry};
+ use serde_json::Value;
+
+ static PROBE_INVOCATIONS: AtomicUsize = AtomicUsize::new(0);
+
+ struct ProbeTool {
+ def: ToolDef,
+ }
+
+ impl ProbeTool {
+ fn new() -> Self {
+ Self {
+ def: ToolDef {
+ name: "probe".into(),
+ description: "test probe; bumps a shared invocation counter".into(),
+ input_schema: serde_json::json!({"type": "object"}),
+ read_only: false,
+ destructive: false,
+ idempotent: true,
+ open_world: false,
+ },
+ }
+ }
+ }
+
+ #[async_trait]
+ impl Tool for ProbeTool {
+ fn def(&self) -> &ToolDef {
+ &self.def
+ }
+ async fn invoke(&self, _args: Value) -> ToolResult {
+ PROBE_INVOCATIONS.fetch_add(1, Ordering::SeqCst);
+ ToolResult::text("probe ran")
+ }
+ }
+
+ fn call_req(sid: Option<&str>) -> DaemonRequest {
+ DaemonRequest {
+ method: "call".into(),
+ name: Some("probe".into()),
+ args: Some(serde_json::json!({})),
+ session_id: sid.map(|s| s.to_owned()),
+ }
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn ended_session_call_is_gated_live_and_anon_pass() {
+ PROBE_INVOCATIONS.store(0, Ordering::SeqCst);
+
+ let mut reg = ToolRegistry::new();
+ reg.register(Box::new(ProbeTool::new()));
+ let registry = Arc::new(reg);
+
+ // Unique temp socket — never the default socket / CuaDriver.app daemon.
+ let socket = format!(
+ "/tmp/cua-driver-gate-test-{}-{}.sock",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ );
+ let socket_for_server = socket.clone();
+ let reg_for_server = registry.clone();
+ let server = tokio::spawn(async move {
+ let _ = run_serve(reg_for_server, &socket_for_server, None).await;
+ });
+
+ // Wait for the daemon to bind.
+ for _ in 0..100 {
+ if std::path::Path::new(&socket).exists() {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+
+ let sid = "gate-test-session-A1B2C3";
+
+ // 1. LIVE session call → tool runs.
+ let socket1 = socket.clone();
+ let s1 = sid.to_owned();
+ let resp = tokio::task::spawn_blocking(move || send_request(&socket1, &call_req(Some(&s1))))
+ .await
+ .unwrap()
+ .expect("live call response");
+ assert!(resp.ok, "live-session call should succeed");
+ assert_eq!(
+ PROBE_INVOCATIONS.load(Ordering::SeqCst),
+ 1,
+ "live-session call must invoke the tool"
+ );
+
+ // 2. End the session (mirrors the control-conn EOF reaper path).
+ let socket2 = socket.clone();
+ let end = DaemonRequest {
+ method: "session_end".into(),
+ name: None,
+ args: None,
+ session_id: Some(sid.to_owned()),
+ };
+ let resp = tokio::task::spawn_blocking(move || send_request(&socket2, &end))
+ .await
+ .unwrap()
+ .expect("session_end response");
+ assert!(resp.ok, "session_end should ack ok");
+
+ // 3. ENDED session call carrying the same sid → GATED. Tool must NOT run.
+ let socket3 = socket.clone();
+ let s3 = sid.to_owned();
+ let resp = tokio::task::spawn_blocking(move || send_request(&socket3, &call_req(Some(&s3))))
+ .await
+ .unwrap()
+ .expect("ended call response");
+ assert!(resp.ok, "gated call returns a benign ok");
+ assert_eq!(
+ resp.result
+ .as_ref()
+ .and_then(|r| r.get("sessionEnded"))
+ .and_then(|v| v.as_bool()),
+ Some(true),
+ "gated response must carry sessionEnded:true"
+ );
+ assert_eq!(
+ PROBE_INVOCATIONS.load(Ordering::SeqCst),
+ 1,
+ "ended-session call must be a no-op (counter unchanged) — resurrection closed"
+ );
+
+ // 4. Anonymous call (no session id) still passes — no false positive.
+ let socket4 = socket.clone();
+ let resp = tokio::task::spawn_blocking(move || send_request(&socket4, &call_req(None)))
+ .await
+ .unwrap()
+ .expect("anon call response");
+ assert!(resp.ok, "anonymous call should succeed");
+ assert_eq!(
+ PROBE_INVOCATIONS.load(Ordering::SeqCst),
+ 2,
+ "anonymous (no session id) call must still invoke the tool"
+ );
+
+ // Tear down the daemon.
+ let socket5 = socket.clone();
+ let shutdown = DaemonRequest {
+ method: "shutdown".into(),
+ name: None,
+ args: None,
+ session_id: None,
+ };
+ let _ = tokio::task::spawn_blocking(move || send_request(&socket5, &shutdown)).await;
+ let _ = server.await;
+ let _ = std::fs::remove_file(&socket);
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/mcp_protocol_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/mcp_protocol_test.rs
index af62d72b16..2962a1a9e5 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/mcp_protocol_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/mcp_protocol_test.rs
@@ -492,16 +492,33 @@ fn test_multi_cursor_instance_state() {
let r5 = read_response(&mut stdout);
assert!(!r5["result"]["isError"].as_bool().unwrap_or(false));
- // get_agent_cursor_state — should have multiple instances.
+ // get_agent_cursor_state is now session-scoped: each call returns ONLY the
+ // cursor it resolves to (explicit cursor_id > injected _session_id >
+ // "default"). Query each instance by its cursor_id and assert independent
+ // state (agent2 was hidden; agent1 was left enabled).
send_request(stdin, &serde_json::json!({
"jsonrpc":"2.0","id":6,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{}}
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"agent1"}}
}));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
- let cursors = &resp["result"]["structuredContent"]["cursors"];
- assert!(cursors.as_array().map(|a| a.len() >= 2).unwrap_or(false),
- "Expected at least 2 cursor instances, got: {cursors:?}");
+ let resp1 = read_response(&mut stdout);
+ assert!(!resp1["result"]["isError"].as_bool().unwrap_or(false));
+ let cursors1 = resp1["result"]["structuredContent"]["cursors"].as_array().cloned().unwrap_or_default();
+ assert_eq!(cursors1.len(), 1, "agent1 query must return exactly its own cursor, got: {cursors1:?}");
+ assert_eq!(cursors1[0]["config"]["cursor_id"].as_str(), Some("agent1"));
+ assert_eq!(resp1["result"]["structuredContent"]["enabled"].as_bool(), Some(true),
+ "agent1 was never disabled");
+
+ send_request(stdin, &serde_json::json!({
+ "jsonrpc":"2.0","id":7,"method":"tools/call",
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"agent2"}}
+ }));
+ let resp2 = read_response(&mut stdout);
+ assert!(!resp2["result"]["isError"].as_bool().unwrap_or(false));
+ let cursors2 = resp2["result"]["structuredContent"]["cursors"].as_array().cloned().unwrap_or_default();
+ assert_eq!(cursors2.len(), 1, "agent2 query must return exactly its own cursor, got: {cursors2:?}");
+ assert_eq!(cursors2[0]["config"]["cursor_id"].as_str(), Some("agent2"));
+ assert_eq!(resp2["result"]["structuredContent"]["enabled"].as_bool(), Some(false),
+ "agent2 was hidden");
std::thread::sleep(Duration::from_millis(50));
assert!(child.try_wait().expect("try_wait").is_none(), "cua-driver crashed during multi-cursor test");
@@ -1751,14 +1768,15 @@ fn test_concurrent_multi_driver_isolation() {
assert!(resp_b["error"].is_null(), "Driver B set_agent_cursor_enabled failed: {resp_b:?}");
// Each driver queries its own cursor state — should reflect what it set.
- // get_agent_cursor_state takes no arguments; returns { "cursors": [...] }.
+ // get_agent_cursor_state is session-scoped, so pass the cursor_id each
+ // driver owns; the response carries { "cursors": [<that one>], "enabled" }.
send_request(stdin_a, &serde_json::json!({
"jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{}}
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"alpha"}}
}));
send_request(stdin_b, &serde_json::json!({
"jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{}}
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"beta"}}
}));
let state_a = read_response(&mut stdout_a);
let state_b = read_response(&mut stdout_b);
@@ -2513,15 +2531,27 @@ fn test_multi_cursor_instance_state_windows() {
}));
assert!(!read_response(&mut stdout)["result"]["isError"].as_bool().unwrap_or(false));
+ // Session-scoped: query each instance by cursor_id (see the macOS variant).
send_request(stdin, &serde_json::json!({
"jsonrpc":"2.0","id":6,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{}}
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"agent1"}}
}));
- let resp = read_response(&mut stdout);
- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false));
- let cursors = &resp["result"]["structuredContent"]["cursors"];
- assert!(cursors.as_array().map(|a| a.len() >= 2).unwrap_or(false),
- "Expected at least 2 cursor instances: {cursors:?}");
+ let resp1 = read_response(&mut stdout);
+ assert!(!resp1["result"]["isError"].as_bool().unwrap_or(false));
+ let cursors1 = resp1["result"]["structuredContent"]["cursors"].as_array().cloned().unwrap_or_default();
+ assert_eq!(cursors1.len(), 1, "agent1 query must return exactly its own cursor: {cursors1:?}");
+ assert_eq!(cursors1[0]["config"]["cursor_id"].as_str(), Some("agent1"));
+
+ send_request(stdin, &serde_json::json!({
+ "jsonrpc":"2.0","id":7,"method":"tools/call",
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"agent2"}}
+ }));
+ let resp2 = read_response(&mut stdout);
+ assert!(!resp2["result"]["isError"].as_bool().unwrap_or(false));
+ let cursors2 = resp2["result"]["structuredContent"]["cursors"].as_array().cloned().unwrap_or_default();
+ assert_eq!(cursors2.len(), 1, "agent2 query must return exactly its own cursor: {cursors2:?}");
+ assert_eq!(cursors2[0]["config"]["cursor_id"].as_str(), Some("agent2"));
+ assert_eq!(resp2["result"]["structuredContent"]["enabled"].as_bool(), Some(false), "agent2 hidden");
std::thread::sleep(Duration::from_millis(50));
assert!(child.try_wait().expect("try_wait").is_none(), "cua-driver crashed during multi-cursor test");
@@ -3232,13 +3262,14 @@ fn test_concurrent_multi_driver_isolation_windows() {
assert!(resp_a["error"].is_null(), "Driver A failed: {resp_a:?}");
assert!(resp_b["error"].is_null(), "Driver B failed: {resp_b:?}");
+ // Session-scoped: query each driver's own cursor by id (see macOS variant).
send_request(stdin_a, &serde_json::json!({
"jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{}}
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"alpha"}}
}));
send_request(stdin_b, &serde_json::json!({
"jsonrpc":"2.0","id":3,"method":"tools/call",
- "params":{"name":"get_agent_cursor_state","arguments":{}}
+ "params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"beta"}}
}));
let state_a = read_response(&mut stdout_a);
let state_b = read_response(&mut stdout_b);
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
index d19078fdc4..ff7fe23abc 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
@@ -23,7 +23,7 @@ pub use motion::{MotionConfig, Spring};
pub use bezier::CubicBezier;
pub use path_planner::{PathPlanner, PlannedPath, PathState};
pub use shape::CursorShape;
-pub use render_state::{RenderStateCore, FocusRect, render_frame, draw_default_arrow};
+pub use render_state::{RenderStateCore, FocusRect, render_frame, paint_cursor, draw_default_arrow};
pub use z_order::ZOrderEnforcer;
/// Configuration assembled from CLI arguments and passed to every
@@ -238,6 +238,36 @@ impl Default for CursorRegistry {
fn default() -> Self { Self::new() }
}
+/// Identifier for one owned cursor in the keyed render collection.
+///
+/// Resolved by the macOS tool layer (see `resolve_cursor_key`) with the
+/// precedence: explicit `cursor_id` arg > injected `_session_id` > `"default"`.
+/// The render side treats it as an opaque insertion-ordered map key; the
+/// `"default"` key is special-cased (never removed) so the anonymous /
+/// one-shot `cua-driver call` path is backward compatible.
+pub type CursorKey = String;
+
+/// A render command tagged with the cursor it targets. Wrapping the key
+/// here (rather than inside [`OverlayCommand`]) keeps `OverlayCommand` and
+/// the shared `apply_command_base` / `render_frame` API untouched, so the
+/// Windows and Linux overlays — which never see a key — keep compiling
+/// and behaving exactly as before.
+#[derive(Debug, Clone)]
+pub struct KeyedOverlayCommand {
+ pub key: CursorKey,
+ pub cmd: OverlayCommand,
+}
+
+/// Message carried over the macOS overlay channel. Either a keyed render
+/// command or a lifecycle removal. A separate lifecycle enum (rather than an
+/// `OverlayCommand::Remove` variant) keeps `OverlayCommand` render-only and
+/// avoids forcing a no-op arm onto the Windows/Linux match.
+#[derive(Debug, Clone)]
+pub enum OverlayMsg {
+ Cmd(KeyedOverlayCommand),
+ Remove(CursorKey),
+}
+
/// Commands sent from MCP tool handlers to the overlay's render thread.
#[derive(Debug, Clone)]
pub enum OverlayCommand {
diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs
index fa6f4dfaae..82fb78cd78 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs
@@ -463,9 +463,30 @@ pub fn render_frame(
let h = height.max(1);
let mut pm = tiny_skia::Pixmap::new(w, h)
.unwrap_or_else(|| tiny_skia::Pixmap::new(1, 1).unwrap());
+ paint_cursor(&mut pm, core, origin_x, origin_y, focus_rect);
+ pm
+}
+/// Paint a single cursor (bloom + click-pulse + optional focus-rect + arrow)
+/// into a caller-owned [`tiny_skia::Pixmap`]. tiny-skia's `fill_*` / `stroke_*`
+/// are alpha-over, so painting several cursors into the same pixmap composites
+/// them with later calls drawn on top — this is what lets the macOS overlay
+/// render N owned cursors into one buffer / one NSWindow.
+///
+/// `origin_x` / `origin_y` are subtracted from `core.pos` before drawing
+/// (Windows passes the virtual-screen origin; macOS / Linux pass `(0.0, 0.0)`).
+///
+/// Quiescent / hidden cursors early-return before touching the pixmap, so an
+/// idle session costs essentially nothing in the per-frame composite loop.
+pub fn paint_cursor(
+ pm: &mut tiny_skia::Pixmap,
+ core: &RenderStateCore,
+ origin_x: f64,
+ origin_y: f64,
+ focus_rect: Option<FocusRect>,
+) {
if !core.visible || core.pos.0 < -100.0 || core.idle_alpha < 0.004 {
- return pm;
+ return;
}
let (px, py) = (core.pos.0 - origin_x, core.pos.1 - origin_y);
@@ -614,7 +635,7 @@ pub fn render_frame(
Some(&core.gradient_colors)
};
draw_default_arrow(
- &mut pm,
+ pm,
&core.palette,
grad_override,
px as f32,
@@ -623,8 +644,6 @@ pub fn render_frame(
alpha_scale,
);
}
-
- pm
}
/// Rasterise the built-in gradient arrow at `(px, py)` rotated by
diff --git a/libs/cua-driver/rust/crates/platform-macos/Cargo.toml b/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
index 944ba230c9..b37a7af046 100644
--- a/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
@@ -14,6 +14,10 @@ base64 = { workspace = true }
image = { workspace = true }
async-trait = "0.1"
uuid = { workspace = true }
+# Insertion-ordered map for the keyed per-session cursor render collection.
+# IndexMap gives deterministic iteration order = stable cursor z-order frame
+# to frame (a plain HashMap would flicker overlapping cursors).
+indexmap = "2"
cua-driver-core = { path = "../cua-driver-core" }
cursor-overlay = { path = "../cursor-overlay" }
pip-preview = { path = "../pip-preview" }
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs b/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
index 034e51ec90..97a9b6fada 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs
@@ -29,46 +29,180 @@
//! variants of MoveTo / ClickPulse — see the wrapper around
//! `apply_command_base` below.
+use std::collections::HashMap;
use std::ffi::c_void;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use cursor_overlay::{
- CursorConfig, FocusRect, MotionConfig, OverlayCommand, RenderStateCore, ZOrderEnforcer,
+ CursorConfig, CursorKey, FocusRect, KeyedOverlayCommand, MotionConfig, OverlayCommand,
+ OverlayMsg, Palette, RenderStateCore, ZOrderEnforcer,
};
+use indexmap::IndexMap;
-// ── Arrival-signal channel ────────────────────────────────────────────────
+// ── Arrival-signal channels (one waiter slot per cursor key) ──────────────
+//
+// Each session's `animate_cursor_to` registers an arrival oneshot keyed by its
+// own cursor key. A new animation only supersedes the SAME key's prior waiter,
+// so concurrent sessions never cross-cancel each other's arrivals.
+
+static ARRIVAL_TX: Mutex<Option<HashMap<CursorKey, tokio::sync::oneshot::Sender<()>>>> =
+ Mutex::new(None);
+
+fn arrival_register(key: CursorKey, tx: tokio::sync::oneshot::Sender<()>) {
+ let mut guard = ARRIVAL_TX.lock().unwrap();
+ let map = guard.get_or_insert_with(HashMap::new);
+ // Cancel only the same key's previous waiter (superseded by new animation).
+ if let Some(old_tx) = map.insert(key, tx) {
+ let _ = old_tx.send(());
+ }
+}
-static ARRIVAL_TX: Mutex<Option<tokio::sync::oneshot::Sender<()>>> = Mutex::new(None);
+fn arrival_fire(key: &CursorKey) {
+ if let Ok(mut guard) = ARRIVAL_TX.lock() {
+ if let Some(map) = guard.as_mut() {
+ if let Some(tx) = map.remove(key) {
+ let _ = tx.send(());
+ }
+ }
+ }
+}
// ── Global overlay state ──────────────────────────────────────────────────
-static CMD_TX: OnceLock<std::sync::mpsc::SyncSender<OverlayCommand>> = OnceLock::new();
+static CMD_TX: OnceLock<std::sync::mpsc::SyncSender<OverlayMsg>> = OnceLock::new();
// Single-consumer slot; receiver is moved into run_on_main_thread().
-static CMD_RX_CELL: Mutex<Option<std::sync::mpsc::Receiver<OverlayCommand>>> = Mutex::new(None);
-static RENDER: Mutex<Option<RenderState>> = Mutex::new(None);
+static CMD_RX_CELL: Mutex<Option<std::sync::mpsc::Receiver<OverlayMsg>>> = Mutex::new(None);
+static RENDER: Mutex<Option<RenderMap>> = Mutex::new(None);
+
+/// The keyed, insertion-ordered collection of owned cursors that the render
+/// loop composites every frame. Insertion order = stable z-order (later keys
+/// paint on top). `win_w` / `win_h` are screen-global, hoisted out of the
+/// per-cursor `RenderState` (written once in `run_appkit`).
+struct RenderMap {
+ cursors: IndexMap<CursorKey, RenderState>,
+ win_w: f64,
+ win_h: f64,
+ /// Frozen launch-time config used as the template for lazily-created
+ /// cursors (its palette is overridden per-key via `Palette::for_instance`).
+ template: CursorConfig,
+ /// Render-side tombstone of permanently-ended session cursor keys. A `Cmd`
+ /// for a key in here is dropped WITHOUT get-or-create, so an in-flight
+ /// click/move from another task that lands AFTER the owning session's
+ /// `Remove` can never resurrect the just-removed cursor (the ghost-cursor
+ /// resurrection race). Keyed on session_id, which is unique per session, so
+ /// a permanent tombstone is correct (no cursor_id reuse across a
+ /// session_end boundary). "default" is never tombstoned.
+ ended: std::collections::HashSet<CursorKey>,
+}
+
+/// Build the `RenderState` for a lazily-created cursor key: derive from the
+/// launch template but give each non-default key its own palette so distinct
+/// sessions get distinct colours automatically.
+fn render_state_for_key(template: &CursorConfig, key: &str) -> RenderState {
+ let mut rs = RenderState::new(template.clone());
+ rs.core.palette = Palette::for_instance(key);
+ rs
+}
+
+/// Apply one inbound [`OverlayMsg`] to the render map (drain step). Factored
+/// out as a pure function so the per-session ownership + removal lifecycle is
+/// unit-testable without AppKit.
+///
+/// Returns the resolved cursor key for a `Cmd` (so the caller can track the
+/// last-active key for z-order pinning); `None` for a `Remove`.
+fn apply_msg(map: &mut RenderMap, msg: OverlayMsg) -> Option<CursorKey> {
+ match msg {
+ OverlayMsg::Remove(key) => {
+ // The "default" cursor backs the anonymous / one-shot path and
+ // must survive every session_end + the daemon lifetime.
+ if key != "default" {
+ map.cursors.shift_remove(&key);
+ if let Ok(mut guard) = ARRIVAL_TX.lock() {
+ if let Some(m) = guard.as_mut() {
+ m.remove(&key);
+ }
+ }
+ // Tombstone the key so a late in-flight Cmd from another task
+ // (an animate/click racing the owning session's death) cannot
+ // re-create the just-removed cursor. Never tombstone "default".
+ map.ended.insert(key);
+ }
+ None
+ }
+ OverlayMsg::Cmd(KeyedOverlayCommand { key, cmd }) => {
+ // Drop a command for an already-ended session WITHOUT get-or-create
+ // — this is the resurrection guard. Without it, a ClickPulse/MoveTo
+ // landing after Remove would re-insert (and re-leak) the cursor.
+ if map.ended.contains(&key) {
+ return None;
+ }
+ let template = map.template.clone();
+ let k = key.clone();
+ let rs = map
+ .cursors
+ .entry(key)
+ .or_insert_with(|| render_state_for_key(&template, &k));
+ rs.apply_command(cmd);
+ Some(k)
+ }
+ }
+}
/// Initialise global overlay state (call once, before run_on_main_thread).
pub fn init(cfg: CursorConfig) {
let (tx, rx) = std::sync::mpsc::sync_channel(4096);
let _ = CMD_TX.set(tx);
*CMD_RX_CELL.lock().unwrap() = Some(rx);
- *RENDER.lock().unwrap() = Some(RenderState::new(cfg));
+ *ARRIVAL_TX.lock().unwrap() = Some(HashMap::new());
+ let mut cursors = IndexMap::new();
+ cursors.insert("default".to_owned(), RenderState::new(cfg.clone()));
+ *RENDER.lock().unwrap() = Some(RenderMap {
+ cursors,
+ win_w: 0.0,
+ win_h: 0.0,
+ template: cfg,
+ ended: std::collections::HashSet::new(),
+ });
+}
+
+/// Send a keyed command from any thread (MCP tool, etc.). Non-blocking; drops
+/// if the channel is full (old commands are less important than new ones).
+pub fn send_command(key: CursorKey, cmd: OverlayCommand) {
+ if let Some(tx) = CMD_TX.get() {
+ let _ = tx.try_send(OverlayMsg::Cmd(KeyedOverlayCommand { key, cmd }));
+ }
+}
+
+/// Convenience for callsites not yet threaded with a session key: drives the
+/// seeded `"default"` cursor (the anonymous / one-shot identity).
+pub fn send_command_default(cmd: OverlayCommand) {
+ send_command("default".to_owned(), cmd);
}
-/// Send a command from any thread (MCP tool, etc.). Non-blocking; drops if
-/// the channel is full (old commands are less important than new ones).
-pub fn send_command(cmd: OverlayCommand) {
+/// Remove a session's owned cursor from the render collection (fired from the
+/// `session_end` hook). The `"default"` key is guarded against removal on the
+/// render side, so this is a no-op for it; removing an absent key (anonymous
+/// session that never created a cursor) is a harmless no-op.
+pub fn remove_cursor(key: CursorKey) {
if let Some(tx) = CMD_TX.get() {
- let _ = tx.try_send(cmd);
+ let _ = tx.try_send(OverlayMsg::Remove(key));
}
}
-/// Return a snapshot of the current motion config (for use by set_agent_cursor_motion
-/// to apply partial overrides without losing other knobs).
-pub fn current_motion() -> MotionConfig {
- RENDER.lock().unwrap()
- .as_ref()
+/// Return a snapshot of a cursor's current motion config (for use by
+/// set_agent_cursor_motion to apply partial overrides without losing other
+/// knobs). Reads the motion of the cursor `key`, falling back to the
+/// `"default"` cursor's motion when that key has no own entry yet (e.g. a
+/// session whose first motion call precedes any move/enable).
+pub fn current_motion(key: &str) -> MotionConfig {
+ let guard = RENDER.lock().unwrap();
+ let Some(map) = guard.as_ref() else {
+ return MotionConfig::default();
+ };
+ map.cursors
+ .get(key)
+ .or_else(|| map.cursors.get("default"))
.map(|rs| rs.core.motion.clone())
.unwrap_or_default()
}
@@ -81,11 +215,12 @@ pub fn current_motion() -> MotionConfig {
/// - the overlay is disabled, or
/// - the cursor is still at the off-screen sentinel `(-200, -200)` — in that
/// case the caller should rely on `ClickPulse` to snap the cursor.
-pub async fn animate_cursor_to(x: f64, y: f64) {
- // Check whether animation should run.
+pub async fn animate_cursor_to(key: CursorKey, x: f64, y: f64) {
+ // Check whether animation should run for THIS cursor. A not-yet-created
+ // cursor (sentinel position) relies on ClickPulse to snap, same as before.
let should_animate = {
let guard = RENDER.lock().unwrap();
- match guard.as_ref() {
+ match guard.as_ref().and_then(|m| m.cursors.get(&key)) {
Some(rs) if rs.core.cfg.enabled && rs.core.pos.0 > -50.0 => true,
_ => false,
}
@@ -94,20 +229,13 @@ pub async fn animate_cursor_to(x: f64, y: f64) {
return;
}
- // Create a one-shot channel; store the sender so the render thread can
- // fire it when the path finishes.
+ // Create a one-shot channel; store the sender (keyed) so the render thread
+ // can fire it when this cursor's path finishes.
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
- {
- let mut guard = ARRIVAL_TX.lock().unwrap();
- // Cancel any previous waiter (superseded by new animation).
- if let Some(old_tx) = guard.take() {
- let _ = old_tx.send(());
- }
- *guard = Some(tx);
- }
+ arrival_register(key.clone(), tx);
// Send the MoveTo command (click offset applied inside apply_command).
- send_command(OverlayCommand::MoveTo {
+ send_command(key, OverlayCommand::MoveTo {
x,
y,
// Arrive pointing upper-left (45°), matching the macOS system-cursor
@@ -135,8 +263,8 @@ pub fn run_on_main_thread() {
let cfg = {
let guard = RENDER.lock().unwrap();
- match &*guard {
- Some(rs) => rs.core.cfg.clone(),
+ match guard.as_ref() {
+ Some(m) => m.template.clone(),
None => return,
}
};
@@ -175,9 +303,6 @@ pub fn run_on_main_thread() {
struct RenderState {
core: RenderStateCore,
- /// Window (frame) size in NSScreen points (top-left origin after Y-flip).
- win_w: f64,
- win_h: f64,
/// Focus-highlight rectangle `[x, y, w, h]` in screen coords; None = not shown.
focus_rect: Option<[f64; 4]>,
/// Fade progress for the focus rect: 0.0 = fully visible, 1.0 = gone.
@@ -188,8 +313,6 @@ impl RenderState {
fn new(cfg: CursorConfig) -> Self {
RenderState {
core: RenderStateCore::new(cfg),
- win_w: 0.0,
- win_h: 0.0,
focus_rect: None,
focus_rect_t: 1.0,
}
@@ -236,7 +359,7 @@ impl RenderState {
// ── AppKit / CGImage plumbing ─────────────────────────────────────────────
-unsafe fn run_appkit(_cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayCommand>) {
+unsafe fn run_appkit(_cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayMsg>) {
use objc2::runtime::AnyObject;
use objc2::{class, msg_send};
use objc2_foundation::NSRect;
@@ -307,12 +430,12 @@ unsafe fn run_appkit(_cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayCo
];
let _: () = msg_send![layer, setContentsGravity: gravity_ns];
- // ---- Update RenderState with screen size ----
+ // ---- Update RenderMap header with screen size (screen-global) ----
{
let mut guard = RENDER.lock().unwrap();
- if let Some(rs) = guard.as_mut() {
- rs.win_w = win_w;
- rs.win_h = win_h;
+ if let Some(m) = guard.as_mut() {
+ m.win_w = win_w;
+ m.win_h = win_h;
}
}
@@ -333,7 +456,7 @@ unsafe fn run_appkit(_cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayCo
fn render_loop(
layer_ptr: usize,
win_ptr: usize,
- rx: std::sync::mpsc::Receiver<OverlayCommand>,
+ rx: std::sync::mpsc::Receiver<OverlayMsg>,
_win_w: f64, _win_h: f64,
) {
let target_frame_ms = Duration::from_millis(16); // ~60 fps
@@ -348,28 +471,43 @@ fn render_loop(
let dt = now.duration_since(last_tick).as_secs_f64().min(0.05);
last_tick = now;
- // Drain incoming commands and tick animation.
- let (pinned_wid, fire_arrival) = {
+ // ── Phase 1: drain + tick all cursors (one lock acquisition) ──────
+ // `pinned_wid` follows the most-recently-updated cursor: a single
+ // NSWindow can occupy only one z-band, so the last-active cursor's
+ // target wins. `arrived` collects the keys whose path just ended.
+ let (pinned_wid, arrived, win_w, win_h) = {
let mut guard = RENDER.lock().unwrap();
match guard.as_mut() {
- Some(rs) => {
- while let Ok(cmd) = rx.try_recv() {
- rs.apply_command(cmd);
+ Some(map) => {
+ // Drain via get-or-create; track the last-touched key so we
+ // can read its pinned_wid after ticking.
+ let mut last_key: Option<CursorKey> = None;
+ while let Ok(msg) = rx.try_recv() {
+ if let Some(k) = apply_msg(map, msg) {
+ last_key = Some(k);
+ }
+ }
+ // Tick every cursor; record the ones that just arrived.
+ let mut arrived: Vec<CursorKey> = Vec::new();
+ for (k, rs) in map.cursors.iter_mut() {
+ if rs.tick(dt) {
+ arrived.push(k.clone());
+ }
}
- let arrived = rs.tick(dt);
- (rs.core.pinned_wid, arrived)
+ let pinned = last_key
+ .as_ref()
+ .and_then(|k| map.cursors.get(k))
+ .map(|rs| rs.core.pinned_wid)
+ .unwrap_or(None);
+ (pinned, arrived, map.win_w, map.win_h)
}
None => break,
}
};
- // Fire arrival signal so animate_cursor_to() can unblock.
- if fire_arrival {
- if let Ok(mut guard) = ARRIVAL_TX.lock() {
- if let Some(tx) = guard.take() {
- let _ = tx.send(());
- }
- }
+ // Fire arrival signals so each session's animate_cursor_to() unblocks.
+ for k in &arrived {
+ arrival_fire(k);
}
// Repin: immediately on target change, then defensive every ~1 s.
@@ -386,21 +524,31 @@ fn render_loop(
repin_frames = 0;
}
- // Render frame.
+ // ── Phase 2: composite every cursor into ONE pixmap ───────────────
+ // Allocate the full-screen pixmap once per frame, then paint each
+ // owned cursor into it (alpha-over, insertion order = z-order). The
+ // expensive CGImage copy + setContents happen once regardless of N;
+ // idle/hidden cursors early-return inside paint_cursor.
let pixmap = {
let guard = RENDER.lock().unwrap();
- if let Some(rs) = guard.as_ref() {
- let focus = rs.focus_rect.map(|rect| FocusRect {
- rect,
- t: rs.focus_rect_t,
- });
- cursor_overlay::render_frame(
- &rs.core,
- rs.win_w.max(1.0) as u32,
- rs.win_h.max(1.0) as u32,
- 0.0, 0.0, // macOS uses screen-local coords (no origin offset)
- focus,
- )
+ if let Some(map) = guard.as_ref() {
+ let w = win_w.max(1.0) as u32;
+ let h = win_h.max(1.0) as u32;
+ let mut pm = tiny_skia::Pixmap::new(w.max(1), h.max(1))
+ .unwrap_or_else(|| tiny_skia::Pixmap::new(1, 1).unwrap());
+ for (_k, rs) in &map.cursors {
+ let focus = rs.focus_rect.map(|rect| FocusRect {
+ rect,
+ t: rs.focus_rect_t,
+ });
+ cursor_overlay::paint_cursor(
+ &mut pm,
+ &rs.core,
+ 0.0, 0.0, // macOS uses screen-local coords (no origin offset)
+ focus,
+ );
+ }
+ pm
} else {
break;
}
@@ -617,3 +765,156 @@ fn pixmap_to_cgimage(pixmap: &tiny_skia::Pixmap) -> Option<usize> {
if img.is_null() { None } else { Some(img as usize) }
}
}
+
+// ── Headless unit tests for the keyed render collection ───────────────────
+//
+// These prove the per-session ownership data model, the session_end removal
+// lifecycle, the "default" guard, and per-key arrival isolation WITHOUT any
+// AppKit / NSWindow. The on-screen rendering (CGImage / CALayer setContents)
+// still needs a real display and is verified separately on the macOS VM.
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::HashMap;
+
+ fn empty_map() -> RenderMap {
+ let mut cursors = IndexMap::new();
+ cursors.insert("default".to_owned(), RenderState::new(CursorConfig::default()));
+ RenderMap {
+ cursors,
+ win_w: 100.0,
+ win_h: 100.0,
+ template: CursorConfig::default(),
+ ended: std::collections::HashSet::new(),
+ }
+ }
+
+ fn move_msg(key: &str, x: f64, y: f64) -> OverlayMsg {
+ OverlayMsg::Cmd(KeyedOverlayCommand {
+ key: key.to_owned(),
+ cmd: OverlayCommand::MoveTo { x, y, end_heading_radians: 0.0 },
+ })
+ }
+
+ #[test]
+ fn two_sessions_produce_two_distinct_render_entries() {
+ let mut map = empty_map();
+ apply_msg(&mut map, OverlayMsg::Cmd(KeyedOverlayCommand {
+ key: "sessA".to_owned(),
+ cmd: OverlayCommand::SetEnabled(true),
+ }));
+ apply_msg(&mut map, move_msg("sessB", 42.0, 24.0));
+ // default + sessA + sessB = 3 distinct owned cursors (the core
+ // regression today is that they would clobber to one).
+ assert_eq!(map.cursors.len(), 3);
+ assert!(map.cursors.contains_key("sessA"));
+ assert!(map.cursors.contains_key("sessB"));
+ assert!(map.cursors.contains_key("default"));
+ }
+
+ #[test]
+ fn session_end_removes_only_that_session() {
+ let mut map = empty_map();
+ apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
+ apply_msg(&mut map, move_msg("sessB", 20.0, 20.0));
+ assert_eq!(map.cursors.len(), 3);
+
+ // session_end(A): A gone, B + default retained.
+ apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
+ assert!(!map.cursors.contains_key("sessA"));
+ assert!(map.cursors.contains_key("sessB"));
+ assert!(map.cursors.contains_key("default"));
+ assert_eq!(map.cursors.len(), 2);
+
+ // Remove("default") is guarded — default survives.
+ apply_msg(&mut map, OverlayMsg::Remove("default".to_owned()));
+ assert!(map.cursors.contains_key("default"));
+
+ // Remove of an absent key (anonymous session that never created a
+ // cursor) is a harmless no-op.
+ let before = map.cursors.len();
+ apply_msg(&mut map, OverlayMsg::Remove("never-existed".to_owned()));
+ assert_eq!(map.cursors.len(), before);
+ }
+
+ #[test]
+ fn lazily_created_cursors_get_distinct_palettes() {
+ let mut map = empty_map();
+ apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
+ apply_msg(&mut map, move_msg("sessB", 20.0, 20.0));
+ let a = &map.cursors["sessA"].core.palette;
+ let b = &map.cursors["sessB"].core.palette;
+ let def = &map.cursors["default"].core.palette;
+ // default uses the blue palette; the two sessions derive their own.
+ assert_ne!(a.name, def.name);
+ assert_ne!(b.name, def.name);
+ }
+
+ #[test]
+ fn insertion_order_is_stable_z_order() {
+ let mut map = empty_map();
+ apply_msg(&mut map, move_msg("first", 1.0, 1.0));
+ apply_msg(&mut map, move_msg("second", 2.0, 2.0));
+ // Re-touching "first" must NOT move it to the back (IndexMap keeps the
+ // original insertion slot), so z-order is stable frame to frame.
+ apply_msg(&mut map, move_msg("first", 3.0, 3.0));
+ let keys: Vec<&String> = map.cursors.keys().collect();
+ assert_eq!(keys, vec!["default", "first", "second"]);
+ }
+
+ #[test]
+ fn tombstone_blocks_resurrection_after_remove() {
+ // The resurrection race: a Cmd for a session lands AFTER its Remove
+ // (an in-flight click from another task as the session dies). The
+ // tombstone must drop it so the just-removed cursor is NOT re-created.
+ let mut map = empty_map();
+ apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
+ assert_eq!(map.cursors.len(), 2); // default + sessA
+
+ // Session ends → cursor removed, key tombstoned.
+ apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
+ assert!(!map.cursors.contains_key("sessA"));
+ assert_eq!(map.cursors.len(), 1);
+
+ // A late in-flight Cmd for the ended session must be dropped WITHOUT
+ // re-inserting (no get-or-create resurrection).
+ let resolved = apply_msg(&mut map, move_msg("sessA", 99.0, 99.0));
+ assert!(resolved.is_none(), "ended-session Cmd must be dropped, not resolved");
+ assert!(!map.cursors.contains_key("sessA"), "tombstone must block resurrection");
+ assert_eq!(map.cursors.len(), 1, "render map length must stay at default only");
+ }
+
+ #[test]
+ fn default_is_never_tombstoned() {
+ // Remove("default") is guarded, so default is never tombstoned and a
+ // subsequent Cmd on default still renders.
+ let mut map = empty_map();
+ apply_msg(&mut map, OverlayMsg::Remove("default".to_owned()));
+ assert!(map.cursors.contains_key("default"));
+ assert!(!map.ended.contains("default"));
+
+ let resolved = apply_msg(&mut map, move_msg("default", 5.0, 5.0));
+ assert_eq!(resolved.as_deref(), Some("default"));
+ assert!(map.cursors.contains_key("default"));
+ }
+
+ #[test]
+ fn per_key_arrival_isolation() {
+ // Two concurrent waiters keyed A and B; firing A must not cancel B.
+ // This mirrors the ARRIVAL_TX HashMap logic in isolation (no statics).
+ let mut waiters: HashMap<CursorKey, tokio::sync::oneshot::Sender<()>> = HashMap::new();
+ let (txa, mut rxa) = tokio::sync::oneshot::channel::<()>();
+ let (txb, mut rxb) = tokio::sync::oneshot::channel::<()>();
+ waiters.insert("A".to_owned(), txa);
+ waiters.insert("B".to_owned(), txb);
+
+ // Fire A's arrival.
+ if let Some(tx) = waiters.remove("A") {
+ let _ = tx.send(());
+ }
+ // A resolved, B still pending.
+ assert!(matches!(rxa.try_recv(), Ok(())));
+ assert!(matches!(rxb.try_recv(), Err(tokio::sync::oneshot::error::TryRecvError::Empty)));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/cursor/state.rs b/libs/cua-driver/rust/crates/platform-macos/src/cursor/state.rs
index 9ba06c7171..7af933cbf2 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/cursor/state.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/cursor/state.rs
@@ -69,13 +69,42 @@ impl CursorRegistry {
pub fn get_or_create(&self, cursor_id: &str) -> CursorState {
let mut inner = self.inner.lock().unwrap();
+ // Write-boundary resurrection guard: a per-session cursor keys on the
+ // session_id, so an in-flight call that lands AFTER session_end (a slow
+ // AX click that passed the dispatch gate, then the proxy died and the
+ // reaper removed this cursor) must NOT re-create the entry the reaper
+ // just cleared — it would be invisible and never reaped again.
+ // `fire_session_end` marks ENDED_SESSIONS *before* fanning out to the
+ // remove hook, so this check is authoritative. The seeded "default" key
+ // and any explicit non-session cursor_id are never in ENDED_SESSIONS, so
+ // they pass through unchanged. Return the live entry if one survives,
+ // else a transient default so callers get a sane value without a write.
+ if cua_driver_core::session::is_session_ended(cursor_id) {
+ return inner.get(cursor_id).cloned().unwrap_or_else(|| CursorState {
+ config: CursorConfig { cursor_id: cursor_id.to_owned(), ..Default::default() },
+ position: None,
+ });
+ }
inner.entry(cursor_id.to_owned()).or_insert_with(|| CursorState {
config: CursorConfig { cursor_id: cursor_id.to_owned(), ..Default::default() },
position: None,
}).clone()
}
+ /// Non-creating read of a single cursor's state. Returns None when the id
+ /// has no entry (used by get_agent_cursor_state to scope its result to the
+ /// caller's session without materialising a phantom cursor).
+ pub fn get(&self, cursor_id: &str) -> Option<CursorState> {
+ self.inner.lock().unwrap().get(cursor_id).cloned()
+ }
+
pub fn update_config(&self, config: CursorConfig) {
+ // Write-boundary resurrection guard (see get_or_create): no-op for an
+ // ended session id so a post-session_end set_config can't resurrect the
+ // cursor metadata. "default" / non-session ids are never ended.
+ if cua_driver_core::session::is_session_ended(&config.cursor_id) {
+ return;
+ }
let mut inner = self.inner.lock().unwrap();
let entry = inner.entry(config.cursor_id.clone()).or_insert_with(|| CursorState {
config: config.clone(),
@@ -85,13 +114,29 @@ impl CursorRegistry {
}
pub fn update_position(&self, cursor_id: &str, x: f64, y: f64) {
- let mut inner = self.inner.lock().unwrap();
- if let Some(state) = inner.get_mut(cursor_id) {
- state.position = Some(CursorPosition { x, y });
+ // Write-boundary resurrection guard (see get_or_create): no-op for an
+ // ended session id so an in-flight move after session_end can't
+ // re-create the cleared cursor. "default" / non-session ids never ended.
+ if cua_driver_core::session::is_session_ended(cursor_id) {
+ return;
}
+ let mut inner = self.inner.lock().unwrap();
+ // Get-or-create so a per-session cursor that moves before any explicit
+ // enable/style call still shows up in get_agent_cursor_state.
+ let state = inner.entry(cursor_id.to_owned()).or_insert_with(|| CursorState {
+ config: CursorConfig { cursor_id: cursor_id.to_owned(), ..Default::default() },
+ position: None,
+ });
+ state.position = Some(CursorPosition { x, y });
}
pub fn set_enabled(&self, cursor_id: &str, enabled: bool) {
+ // Write-boundary resurrection guard (see get_or_create): no-op for an
+ // ended session id so a post-session_end enable/disable can't resurrect
+ // the cleared cursor. "default" / non-session ids are never ended.
+ if cua_driver_core::session::is_session_ended(cursor_id) {
+ return;
+ }
let mut inner = self.inner.lock().unwrap();
let state = inner.entry(cursor_id.to_owned()).or_insert_with(|| CursorState {
config: CursorConfig { cursor_id: cursor_id.to_owned(), ..Default::default() },
@@ -103,6 +148,17 @@ impl CursorRegistry {
pub fn all_states(&self) -> Vec<CursorState> {
self.inner.lock().unwrap().values().cloned().collect()
}
+
+ /// Remove a cursor instance's metadata (fired from the `session_end` hook
+ /// when a session disconnects). The `"default"` cursor backs the
+ /// anonymous / one-shot path and is never removed — guarding here AND in
+ /// the overlay Remove arm keeps the backward-compatibility contract intact.
+ pub fn remove(&self, cursor_id: &str) {
+ if cursor_id == "default" {
+ return;
+ }
+ self.inner.lock().unwrap().remove(cursor_id);
+ }
}
impl Default for CursorRegistry {
@@ -110,3 +166,76 @@ impl Default for CursorRegistry {
Self::new()
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cua_driver_core::session::fire_session_end;
+
+ // Each test uses a unique session id so the process-global ENDED_SESSIONS
+ // set never collides across tests running in the same process.
+
+ #[test]
+ fn ended_session_id_is_not_resurrected_by_mutators() {
+ // THE FIX: mark a session ended (as fire_session_end does before the
+ // reaper's remove hook runs), then drive every guarded mutator with that
+ // session id. None may create an entry — proving the in-flight write
+ // that lands after session_end cannot resurrect the cleared cursor.
+ let reg = CursorRegistry::new();
+ let sid = "wb-cursor-ended-A1B2C3";
+ fire_session_end(sid);
+ assert!(cua_driver_core::session::is_session_ended(sid));
+
+ reg.set_enabled(sid, true);
+ reg.update_position(sid, 10.0, 20.0);
+ reg.update_config(CursorConfig { cursor_id: sid.to_owned(), ..Default::default() });
+ let got = reg.get_or_create(sid);
+
+ // get_or_create returns a transient default value, but must NOT persist.
+ assert_eq!(got.config.cursor_id, sid);
+ assert!(reg.get(sid).is_none(), "no entry may be created for an ended session");
+ assert!(
+ !reg.all_states().iter().any(|s| s.config.cursor_id == sid),
+ "ended session cursor must never appear in the registry"
+ );
+ }
+
+ #[test]
+ fn default_cursor_unaffected_by_guard() {
+ // "default" is seeded and is never tombstoned — its mutators still work.
+ let reg = CursorRegistry::new();
+ assert!(!cua_driver_core::session::is_session_ended("default"));
+ reg.set_enabled("default", false);
+ reg.update_position("default", 1.0, 2.0);
+ let s = reg.get("default").expect("default cursor always present");
+ assert!(!s.config.enabled);
+ assert_eq!(s.position.as_ref().map(|p| (p.x, p.y)), Some((1.0, 2.0)));
+ }
+
+ #[test]
+ fn explicit_non_session_cursor_id_unaffected_by_guard() {
+ // A user-supplied cursor_id that is not a session id is never in
+ // ENDED_SESSIONS, so the plain is_session_ended check leaves it working.
+ let reg = CursorRegistry::new();
+ let cid = "wb-explicit-user-cursor-XYZ";
+ assert!(!cua_driver_core::session::is_session_ended(cid));
+ reg.set_enabled(cid, true);
+ reg.update_position(cid, 5.0, 6.0);
+ let s = reg.get(cid).expect("explicit cursor_id must materialise");
+ assert!(s.config.enabled);
+ assert_eq!(s.position.as_ref().map(|p| (p.x, p.y)), Some((5.0, 6.0)));
+ }
+
+ #[test]
+ fn live_session_cursor_writes_still_take_effect() {
+ // A live (not-ended) session id writes normally.
+ let reg = CursorRegistry::new();
+ let sid = "wb-cursor-live-LMNOP";
+ assert!(!cua_driver_core::session::is_session_ended(sid));
+ reg.set_enabled(sid, true);
+ reg.update_position(sid, 7.0, 8.0);
+ let s = reg.get(sid).expect("live session cursor must exist");
+ assert!(s.config.enabled);
+ assert_eq!(s.position.as_ref().map(|p| (p.x, p.y)), Some((7.0, 8.0)));
+ }
+}
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.rs
index 7da57f73ab..dcf125dc46 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
@@ -103,6 +103,9 @@ impl Tool for ClickTool {
async fn invoke(&self, args: Value) -> ToolResult {
use cua_driver_core::tool_args::ArgsExt;
let pid = match args.require_i32("pid") { Ok(v) => v, Err(e) => return e };
+ // Resolve this action's cursor key so its click-pulse / glide land on
+ // the calling session's cursor, not the shared "default" one.
+ let cursor_key = super::cursor_tools::resolve_cursor_key(&args);
let element_index = args.opt_u64("element_index").map(|v| v as usize);
let window_id = args.opt_u64("window_id").map(|v| v as u32);
@@ -134,13 +137,14 @@ impl Tool for ClickTool {
if let Some((cx, cy)) = center {
// Pin overlay above target window first.
crate::cursor::overlay::send_command(
- cursor_overlay::OverlayCommand::PinAbove(wid as u64)
+ cursor_key.clone(),
+ cursor_overlay::OverlayCommand::PinAbove(wid as u64),
);
- crate::cursor::overlay::animate_cursor_to(cx, cy).await;
+ crate::cursor::overlay::animate_cursor_to(cursor_key.clone(), cx, cy).await;
// Keep the registry in sync with the overlay so
// get_agent_cursor_state reports a truthful position even when
// the click was dispatched via the AX path (no pixel coords).
- self.state.cursor_registry.update_position("default", cx, cy);
+ self.state.cursor_registry.update_position(&cursor_key, cx, cy);
}
// ── Focus-suppression wrap (Swift WindowChangeDetector + FocusGuard) ──
@@ -154,13 +158,18 @@ impl Tool for ClickTool {
// Run AX work on a blocking thread (can't block async executor).
let action_clone = action.clone();
+ // Thread the resolved session cursor key into the blocking AX path
+ // so its ShowFocusRect + ClickPulse land on THIS session's cursor,
+ // not the shared "default" one (which would light the wrong cursor
+ // and stomp default for a non-default session).
+ let ck = cursor_key.clone();
let result = focus_guard::with_focus_suppressed(
Some(pid),
prior_front,
"click.AXPress",
|| async move {
tokio::task::spawn_blocking(move || {
- perform_ax_click(element_ptr, idx, pid, wid, &action_clone)
+ perform_ax_click(element_ptr, idx, pid, wid, &action_clone, &ck)
})
.await
},
@@ -292,17 +301,19 @@ impl Tool for ClickTool {
// the cursor is already sandwiched correctly while it glides in.
if let Some(wid) = window_id {
crate::cursor::overlay::send_command(
- cursor_overlay::OverlayCommand::PinAbove(wid as u64)
+ cursor_key.clone(),
+ cursor_overlay::OverlayCommand::PinAbove(wid as u64),
);
}
// Animate the visual cursor to the click point and wait for it to
// arrive — mirrors Swift's `AgentCursor.shared.animateAndWait(to:)`.
- crate::cursor::overlay::animate_cursor_to(screen_x, screen_y).await;
+ crate::cursor::overlay::animate_cursor_to(cursor_key.clone(), screen_x, screen_y).await;
// Keep the registry in sync with the overlay (see AX path above).
- self.state.cursor_registry.update_position("default", screen_x, screen_y);
+ self.state.cursor_registry.update_position(&cursor_key, screen_x, screen_y);
// Show click-pulse on the agent cursor overlay.
crate::cursor::overlay::send_command(
- cursor_overlay::OverlayCommand::ClickPulse { x: screen_x, y: screen_y }
+ cursor_key.clone(),
+ cursor_overlay::OverlayCommand::ClickPulse { x: screen_x, y: screen_y },
);
// ── Focus-suppression wrap (Swift WindowChangeDetector + FocusGuard) ──
@@ -365,6 +376,7 @@ fn perform_ax_click(
pid: i32,
window_id: u32,
action_str: &str,
+ cursor_key: &str,
) -> anyhow::Result<(String, bool)> {
let ax_action = map_action(action_str);
let element = element_ptr as AXUIElementRef;
@@ -431,14 +443,19 @@ fn perform_ax_click(
// Show focus-rect highlight around the element (matches Swift showFocusRect).
// Also move the cursor to the element center so the glide animation plays.
if let Some(rect) = unsafe { element_screen_rect(element) } {
+ // Drive THIS session's cursor (threaded in via `cursor_key`), matching
+ // the keyed glide already played in the invoke body above. The keyed
+ // glide already played on the session's cursor in the invoke body.
crate::cursor::overlay::send_command(
- cursor_overlay::OverlayCommand::ShowFocusRect(Some(rect))
+ cursor_key.to_owned(),
+ cursor_overlay::OverlayCommand::ShowFocusRect(Some(rect)),
);
// Animate cursor to element center.
let cx = rect[0] + rect[2] / 2.0;
let cy = rect[1] + rect[3] / 2.0;
crate::cursor::overlay::send_command(
- cursor_overlay::OverlayCommand::ClickPulse { x: cx, y: cy }
+ cursor_key.to_owned(),
+ cursor_overlay::OverlayCommand::ClickPulse { x: cx, y: cy },
);
}
let _ = pid; let _ = window_id; // used by caller context
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/cursor_tools.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/cursor_tools.rs
index f0b33f4132..ffccaae2f6 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/cursor_tools.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/cursor_tools.rs
@@ -11,6 +11,28 @@ use std::sync::Arc;
use super::ToolState;
+/// Resolve the cursor key for a tool invocation.
+///
+/// Precedence (mandatory): an explicit, non-empty `cursor_id` arg wins, then
+/// the daemon-injected `_session_id` (so each MCP session owns a cursor by
+/// default), then the seeded `"default"` cursor (anonymous / one-shot
+/// `cua-driver call`). Putting `cursor_id` first means a wrapper that
+/// deliberately shares one cursor_id across sessions is NOT fragmented.
+pub(crate) fn resolve_cursor_key(args: &Value) -> String {
+ use cua_driver_core::tool_args::ArgsExt;
+ if let Some(explicit) = args.opt_str("cursor_id") {
+ if !explicit.is_empty() {
+ return explicit;
+ }
+ }
+ if let Some(session) = args.opt_str("_session_id") {
+ if !session.is_empty() {
+ return session;
+ }
+ }
+ "default".to_owned()
+}
+
// ── SetAgentCursorEnabled ─────────────────────────────────────────────────────
pub struct SetAgentCursorEnabledTool {
@@ -50,12 +72,14 @@ impl Tool for SetAgentCursorEnabledTool {
async fn invoke(&self, args: Value) -> ToolResult {
use cua_driver_core::tool_args::ArgsExt;
let enabled = match args.require_bool("enabled") { Ok(v) => v, Err(e) => return e };
- let cursor_id_owned = args.str_or("cursor_id", "default");
- let cursor_id = cursor_id_owned.as_str();
- self.state.cursor_registry.set_enabled(cursor_id, enabled);
- // Drive the visual overlay.
- crate::cursor::overlay::send_command(cursor_overlay::OverlayCommand::SetEnabled(enabled));
- ToolResult::text(format!("Agent cursor '{}' {}.", cursor_id, if enabled { "enabled" } else { "disabled" }))
+ let key = resolve_cursor_key(&args);
+ self.state.cursor_registry.set_enabled(&key, enabled);
+ // Drive the visual overlay for THIS session's cursor.
+ crate::cursor::overlay::send_command(
+ key.clone(),
+ cursor_overlay::OverlayCommand::SetEnabled(enabled),
+ );
+ ToolResult::text(format!("Agent cursor '{}' {}.", key, if enabled { "enabled" } else { "disabled" }))
}
}
@@ -154,7 +178,7 @@ impl Tool for SetAgentCursorMotionTool {
async fn invoke(&self, args: Value) -> ToolResult {
use cua_driver_core::tool_args::ArgsExt;
- let cursor_id = args.str_or("cursor_id", "default");
+ let cursor_id = resolve_cursor_key(&args);
// Start from the current state or defaults.
let mut current = self.state.cursor_registry.get_or_create(&cursor_id);
@@ -194,8 +218,9 @@ impl Tool for SetAgentCursorMotionTool {
|| args.get("idle_hide_ms").is_some();
if motion_changed {
- // Read current motion from overlay, apply overrides, push back.
- let current_motion = crate::cursor::overlay::current_motion();
+ // Read this cursor's current motion from the overlay, apply
+ // overrides, push back.
+ let current_motion = crate::cursor::overlay::current_motion(&cursor_id);
let new_motion = current_motion.with_overrides(
num(args.get("start_handle")),
num(args.get("end_handle")),
@@ -208,7 +233,8 @@ impl Tool for SetAgentCursorMotionTool {
None, // press_duration_ms not exposed
);
crate::cursor::overlay::send_command(
- cursor_overlay::OverlayCommand::SetMotion(new_motion.clone())
+ cursor_id.clone(),
+ cursor_overlay::OverlayCommand::SetMotion(new_motion.clone()),
);
ToolResult::text(format!(
"Cursor '{}' updated. Motion: start={:.2} end={:.2} arc={:.2} flow={:.2} \
@@ -289,8 +315,7 @@ impl Tool for SetAgentCursorStyleTool {
fn def(&self) -> &ToolDef { style_def() }
async fn invoke(&self, args: Value) -> ToolResult {
- use cua_driver_core::tool_args::ArgsExt;
- let cursor_id = args.str_or("cursor_id", "default");
+ let cursor_id = resolve_cursor_key(&args);
// ── image_path ────────────────────────────────────────────────────────
let image_path = args.get("image_path").and_then(|v| v.as_str());
@@ -349,18 +374,21 @@ impl Tool for SetAgentCursorStyleTool {
None
};
- // ── Dispatch to overlay ───────────────────────────────────────────────
+ // ── Dispatch to overlay (keyed to this session's cursor) ──────────────
if let Some(cmd) = shape_cmd {
- crate::cursor::overlay::send_command(cmd);
+ crate::cursor::overlay::send_command(cursor_id.clone(), cmd);
}
let gradient_provided = args.get("gradient_colors").is_some();
let bloom_provided = args.get("bloom_color").is_some();
if gradient_provided || bloom_provided {
- crate::cursor::overlay::send_command(cursor_overlay::OverlayCommand::SetGradient {
- gradient_colors,
- bloom_color: bloom_color.flatten(),
- });
+ crate::cursor::overlay::send_command(
+ cursor_id.clone(),
+ cursor_overlay::OverlayCommand::SetGradient {
+ gradient_colors,
+ bloom_color: bloom_color.flatten(),
+ },
+ );
}
// Build response summary.
@@ -424,9 +452,16 @@ static STATE_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();
fn state_def() -> &'static ToolDef {
STATE_DEF.get_or_init(|| ToolDef {
name: "get_agent_cursor_state".into(),
- description: "Return the current state of all agent cursor instances: position, \
- config (color, icon, label, size, opacity), enabled flag.".into(),
- input_schema: serde_json::json!({"type":"object","properties":{},"additionalProperties":false}),
+ description: "Return the current state of THIS session's agent cursor: position, \
+ config (color, icon, label, size, opacity), enabled flag. Pass cursor_id to \
+ inspect a specific instance.".into(),
+ input_schema: serde_json::json!({
+ "type": "object",
+ "properties": {
+ "cursor_id": { "type": "string", "description": "Cursor instance. Default: this session's cursor." }
+ },
+ "additionalProperties": false
+ }),
read_only: true,
destructive: false,
idempotent: true,
@@ -438,12 +473,90 @@ fn state_def() -> &'static ToolDef {
impl Tool for GetAgentCursorStateTool {
fn def(&self) -> &ToolDef { state_def() }
- async fn invoke(&self, _args: Value) -> ToolResult {
- let states = self.state.cursor_registry.all_states();
- let json = serde_json::to_value(&states).unwrap_or_default();
- // Top-level "enabled" mirrors Swift's field for parity — use the default cursor.
- let enabled = states.first().map(|s| s.config.enabled).unwrap_or(true);
- ToolResult::text(format!("{} cursor instance(s).", states.len()))
+ async fn invoke(&self, args: Value) -> ToolResult {
+ // Scope to the CALLER's cursor (explicit cursor_id > injected
+ // _session_id > "default"). Returning every session's cursors here was a
+ // cross-session leak, and deriving the top-level `enabled` via
+ // `.first()` over a HashMap-backed Vec was nondeterministic with N
+ // cursors. A non-creating `get` keeps a never-touched session from
+ // materialising a phantom entry.
+ let key = resolve_cursor_key(&args);
+ let state = self.state.cursor_registry.get(&key);
+ // `enabled` defaults to true when the session has no cursor yet — the
+ // anonymous / one-shot path resolves to "default", which is always
+ // present, so this default only applies to a brand-new session that has
+ // not enabled/moved its cursor, where "visible by default" is correct.
+ let enabled = state.as_ref().map(|s| s.config.enabled).unwrap_or(true);
+ let cursors: Vec<&crate::cursor::CursorState> = state.iter().collect();
+ let json = serde_json::to_value(&cursors).unwrap_or_default();
+ ToolResult::text(format!("{} cursor instance(s) for '{}'.", cursors.len(), key))
.with_structured(serde_json::json!({ "cursors": json, "enabled": enabled }))
}
}
+
+// ── Headless unit tests for cursor-key resolution ─────────────────────────
+
+#[cfg(test)]
+mod tests {
+ use super::resolve_cursor_key;
+ use serde_json::json;
+
+ #[test]
+ fn anonymous_resolves_to_default() {
+ // No cursor_id, no _session_id → seeded "default" cursor (backward
+ // compatible one-shot `cua-driver call`).
+ assert_eq!(resolve_cursor_key(&json!({})), "default");
+ assert_eq!(resolve_cursor_key(&json!({ "x": 1 })), "default");
+ }
+
+ #[test]
+ fn session_id_owns_a_cursor_by_default() {
+ assert_eq!(
+ resolve_cursor_key(&json!({ "_session_id": "sess-7" })),
+ "sess-7"
+ );
+ }
+
+ #[test]
+ fn explicit_cursor_id_wins_over_session() {
+ // Precedence: explicit cursor_id > injected _session_id > "default".
+ assert_eq!(
+ resolve_cursor_key(&json!({ "cursor_id": "user-handle", "_session_id": "sess-7" })),
+ "user-handle"
+ );
+ }
+
+ #[test]
+ fn get_agent_cursor_state_is_session_scoped() {
+ // A fabricated registry with two sessions' cursors; the scoped read for
+ // one session must return ONLY that session's cursor (no cross-session
+ // leak) and a deterministic `enabled` for that key.
+ use crate::cursor::CursorRegistry;
+ let reg = CursorRegistry::new();
+ reg.set_enabled("sessA", true);
+ reg.set_enabled("sessB", false);
+
+ let a = reg.get("sessA").expect("sessA present");
+ assert!(a.config.enabled);
+ let b = reg.get("sessB").expect("sessB present");
+ assert!(!b.config.enabled);
+ // Scoping to sessB must not see sessA's enabled flag.
+ assert_ne!(a.config.enabled, b.config.enabled);
+ // A never-touched session has no entry — no phantom materialised.
+ assert!(reg.get("sessC-never-touched").is_none());
+ }
+
+ #[test]
+ fn empty_strings_fall_through() {
+ // An empty cursor_id falls through to _session_id; empty session falls
+ // through to "default".
+ assert_eq!(
+ resolve_cursor_key(&json!({ "cursor_id": "", "_session_id": "sess-7" })),
+ "sess-7"
+ );
+ assert_eq!(
+ resolve_cursor_key(&json!({ "cursor_id": "", "_session_id": "" })),
+ "default"
+ );
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs
index f20052e439..ede8bf62f8 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs
@@ -56,6 +56,7 @@ impl Tool for DoubleClickTool {
async fn invoke(&self, args: Value) -> ToolResult {
use cua_driver_core::tool_args::ArgsExt;
let pid = match args.require_i32("pid") { Ok(v) => v, Err(e) => return e };
+ let cursor_key = super::cursor_tools::resolve_cursor_key(&args);
let element_index = args.opt_u64("element_index").map(|v| v as usize);
let window_id = args.opt_u64("window_id").map(|v| v as u32);
@@ -68,8 +69,11 @@ impl Tool for DoubleClickTool {
)),
};
+ // Thread the resolved session cursor key into the blocking AX path
+ // so its ClickPulse lands on THIS session's cursor, not "default".
+ let ck = cursor_key.clone();
let result = tokio::task::spawn_blocking(move || {
- ax_double_click(pid, element_ptr, idx)
+ ax_double_click(pid, element_ptr, idx, &ck)
}).await;
return match result {
@@ -127,12 +131,16 @@ impl Tool for DoubleClickTool {
// Pin overlay above the target window before animating.
if let Some(wid) = window_id {
crate::cursor::overlay::send_command(
- cursor_overlay::OverlayCommand::PinAbove(wid as u64)
+ cursor_key.clone(),
+ cursor_overlay::OverlayCommand::PinAbove(wid as u64),
);
}
// Animate cursor to the click point; wait for arrival before firing.
- crate::cursor::overlay::animate_cursor_to(screen_x, screen_y).await;
- crate::cursor::overlay::send_command(cursor_overlay::OverlayCommand::ClickPulse { x: screen_x, y: screen_y });
+ crate::cursor::overlay::animate_cursor_to(cursor_key.clone(), screen_x, screen_y).await;
+ crate::cursor::overlay::send_command(
+ cursor_key.clone(),
+ cursor_overlay::OverlayCommand::ClickPulse { x: screen_x, y: screen_y },
+ );
let result = tokio::task::spawn_blocking(move || {
if let Some(wid) = window_id {
@@ -154,7 +162,7 @@ impl Tool for DoubleClickTool {
// ── Blocking AX path ─────────────────────────────────────────────────────────
-fn ax_double_click(pid: i32, element_ptr: usize, idx: usize) -> anyhow::Result<String> {
+fn ax_double_click(pid: i32, element_ptr: usize, idx: usize, cursor_key: &str) -> anyhow::Result<String> {
let element = element_ptr as AXUIElementRef;
// Try AXOpen first (Finder items, openable list rows, document cells).
@@ -171,7 +179,11 @@ fn ax_double_click(pid: i32, element_ptr: usize, idx: usize) -> anyhow::Result<S
let (cx, cy) = unsafe { element_screen_center(element) }
.ok_or_else(|| anyhow::anyhow!("Cannot resolve screen center for element [{idx}]"))?;
- crate::cursor::overlay::send_command(cursor_overlay::OverlayCommand::ClickPulse { x: cx, y: cy });
+ // Drive THIS session's cursor (threaded in via `cursor_key`), not "default".
+ crate::cursor::overlay::send_command(
+ cursor_key.to_owned(),
+ cursor_overlay::OverlayCommand::ClickPulse { x: cx, y: cy },
+ );
crate::input::mouse::click_at_xy(pid, cx, cy, 2, &[])?;
Ok(format!("✅ Double-clicked element [{idx}] at ({cx:.1}, {cy:.1})."))
}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs
index 2ebf6a95e3..d7fe0fa91a 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs
@@ -101,6 +101,7 @@ impl Tool for DragTool {
async fn invoke(&self, args: Value) -> ToolResult {
use cua_driver_core::tool_args::ArgsExt;
let pid = match args.require_i32("pid") { Ok(v) => v, Err(e) => return e };
+ let cursor_key = super::cursor_tools::resolve_cursor_key(&args);
// Coerce integer or float from JSON for coordinate fields.
let coerce = |key: &str| -> Option<f64> {
@@ -191,10 +192,11 @@ impl Tool for DragTool {
// Animate agent cursor along drag path (start → end).
if let Some(wid) = window_id {
crate::cursor::overlay::send_command(
- cursor_overlay::OverlayCommand::PinAbove(wid as u64)
+ cursor_key.clone(),
+ cursor_overlay::OverlayCommand::PinAbove(wid as u64),
);
}
- crate::cursor::overlay::animate_cursor_to(from_sx, from_sy).await;
+ crate::cursor::overlay::animate_cursor_to(cursor_key.clone(), from_sx, from_sy).await;
// ── Focus-suppression wrap (Swift WindowChangeDetector + FocusGuard) ──
// Drags can trigger drag-and-drop side-effects that spawn helper
@@ -234,10 +236,11 @@ impl Tool for DragTool {
let changes = snapshot.detect_async().await;
// Animate cursor to end position.
- crate::cursor::overlay::animate_cursor_to(to_sx, to_sy).await;
+ crate::cursor::overlay::animate_cursor_to(cursor_key.clone(), to_sx, to_sy).await;
if let Some(wid) = window_id {
crate::cursor::overlay::send_command(
- cursor_overlay::OverlayCommand::PinAbove(wid as u64)
+ cursor_key.clone(),
+ cursor_overlay::OverlayCommand::PinAbove(wid as u64),
);
}
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.rs
index e1b9f3c389..1d05ce2991 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
@@ -208,6 +208,15 @@ impl SessionConfigRegistry {
/// 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) {
+ // Write-boundary resurrection guard: keyed by session_id, so an
+ // in-flight set_config that lands AFTER session_end (passed the dispatch
+ // gate, then the proxy died and the reaper cleared this session's
+ // overrides) must NOT re-create the entry — it would be invisible and
+ // never reaped again. `fire_session_end` marks ENDED_SESSIONS *before*
+ // running the config-clear hook, so this check is authoritative.
+ if cua_driver_core::session::is_session_ended(session) {
+ return;
+ }
let mut map = self.inner.lock().unwrap();
let entry = map.entry(session.to_owned()).or_default();
if delta.capture_mode.is_some() {
@@ -281,13 +290,22 @@ 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.
+ // Drop a disconnecting session's config overrides + owned cursor 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();
+ let cursor_registry = state.cursor_registry.clone();
cua_driver_core::session::register_session_end_hook(move |session_id| {
session_config.clear(session_id);
+ // Per-session agent cursor: the session_id is the cursor key when
+ // the caller gave no explicit cursor_id, so dropping it here both
+ // prunes the metadata registry and stops the overlay painting that
+ // session's cursor. Both paths guard "default" so the anonymous /
+ // one-shot cursor survives. Anonymous sessions that never created a
+ // cursor are a harmless no-op.
+ cursor_registry.remove(session_id);
+ crate::cursor::overlay::remove_cursor(session_id.to_owned());
});
}
@@ -338,3 +356,90 @@ pub fn register_all(registry: &mut ToolRegistry, compat: bool) {
// Recording / replay tools are platform-independent — live in mcp-server.
registry.register_recording_tools();
}
+
+#[cfg(test)]
+mod session_config_guard_tests {
+ use super::*;
+ use cua_driver_core::session::fire_session_end;
+
+ fn overrides(mode: &str) -> ConfigOverrides {
+ ConfigOverrides { capture_mode: Some(mode.to_owned()), max_image_dimension: None }
+ }
+
+ #[test]
+ fn ended_session_config_set_is_noop() {
+ // THE FIX (config side): an ended session id keys the overrides map, so
+ // an in-flight set_config after session_end must not re-create the entry
+ // the reaper's clear hook removed. effective() then falls back to global.
+ let reg = SessionConfigRegistry::new();
+ let global = DriverConfig::default();
+ let sid = "wb-config-ended-Q9R8S7";
+ fire_session_end(sid);
+ assert!(cua_driver_core::session::is_session_ended(sid));
+
+ reg.set(sid, overrides("raw"));
+ let (mode, _) = reg.effective(Some(sid), &global);
+ assert_eq!(mode, global.capture_mode, "ended session must not get an override entry");
+ }
+
+ #[test]
+ fn live_session_config_set_takes_effect() {
+ let reg = SessionConfigRegistry::new();
+ let global = DriverConfig::default();
+ let sid = "wb-config-live-T1U2V3";
+ assert!(!cua_driver_core::session::is_session_ended(sid));
+ reg.set(sid, overrides("raw"));
+ let (mode, _) = reg.effective(Some(sid), &global);
+ assert_eq!(mode, "raw", "live session override must apply");
+ }
+}
+
+// RecordingSession lives in cua-driver-core, but its `start()` pulls in the
+// macOS cursor sampler (CoreGraphics), so the start-guard test runs here in
+// platform-macos where build.rs links the frameworks — the core crate's test
+// binary has no CoreGraphics linkage.
+#[cfg(test)]
+mod recording_start_guard_tests {
+ use cua_driver_core::recording::RecordingSession;
+ use cua_driver_core::session::fire_session_end;
+
+ #[test]
+ fn start_refuses_for_ended_session_owner() {
+ // THE FIX (recording side): an in-flight start_recording owned by a
+ // session that already ended would leak an ffmpeg/SCStream process owned
+ // by a dead session that is never reaped. start() must refuse.
+ let rec = RecordingSession::new();
+ let sid = "wb-recording-ended-W4X5Y6";
+ fire_session_end(sid);
+ assert!(cua_driver_core::session::is_session_ended(sid));
+
+ let dir = std::env::temp_dir().join("wb-rec-ended");
+ let err = rec.start(dir.to_str().unwrap(), false, Some(sid));
+ assert!(err.is_err(), "start for an ended session owner must error");
+ assert!(!rec.current_state().enabled, "no recording may start for a dead session");
+ }
+
+ #[test]
+ fn start_succeeds_for_live_session_owner() {
+ let rec = RecordingSession::new();
+ let sid = "wb-recording-live-Z7A8B9";
+ assert!(!cua_driver_core::session::is_session_ended(sid));
+ let dir = std::env::temp_dir().join("wb-rec-live");
+ // record_video=false avoids spawning ffmpeg in the test.
+ let ok = rec.start(dir.to_str().unwrap(), false, Some(sid));
+ assert!(ok.is_ok(), "start for a live session owner must succeed");
+ assert!(rec.current_state().enabled);
+ let _ = rec.stop_owner(Some(sid));
+ }
+
+ #[test]
+ fn start_succeeds_for_anonymous_owner() {
+ // owner = None (CLI one-shot / legacy shim) is never gated.
+ let rec = RecordingSession::new();
+ let dir = std::env::temp_dir().join("wb-rec-anon");
+ let ok = rec.start(dir.to_str().unwrap(), false, None);
+ assert!(ok.is_ok(), "anonymous start must never be gated");
+ assert!(rec.current_state().enabled);
+ let _ = rec.stop_owner(None);
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/move_cursor.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/move_cursor.rs
index a5fe0b25d6..7807009c7c 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/move_cursor.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/move_cursor.rs
@@ -46,14 +46,14 @@ impl Tool for MoveCursorTool {
use cua_driver_core::tool_args::ArgsExt;
let x = match args.require_f64("x") { Ok(v) => v, Err(e) => return e };
let y = match args.require_f64("y") { Ok(v) => v, Err(e) => return e };
- let cursor_id_owned = args.str_or("cursor_id", "default");
- let cursor_id = cursor_id_owned.as_str();
+ let cursor_id = super::cursor_tools::resolve_cursor_key(&args);
- self.state.cursor_registry.update_position(cursor_id, x, y);
- // Drive the visual overlay (no-op when overlay is disabled).
- // End pointing upper-left (45°) — matches Swift's
+ self.state.cursor_registry.update_position(&cursor_id, x, y);
+ // Drive the visual overlay for THIS session's cursor (no-op when the
+ // overlay is disabled). End pointing upper-left (45°) — matches Swift's
// `AgentCursor.animateAndWait(endAngleDegrees: 45)` convention.
crate::cursor::overlay::send_command(
+ cursor_id.clone(),
cursor_overlay::OverlayCommand::MoveTo { x, y, end_heading_radians: std::f64::consts::FRAC_PI_4 }
);
ToolResult::text(format!("Agent cursor '{cursor_id}' moved to ({x:.1}, {y:.1})."))
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs
index f433fa6c53..5312cc34da 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs
@@ -78,6 +78,7 @@ impl Tool for RightClickTool {
async fn invoke(&self, args: Value) -> ToolResult {
use cua_driver_core::tool_args::ArgsExt;
let pid = match args.require_i32("pid") { Ok(v) => v, Err(e) => return e };
+ let cursor_key = super::cursor_tools::resolve_cursor_key(&args);
let element_index = args.opt_u64("element_index").map(|v| v as usize);
let window_id = args.opt_u64("window_id").map(|v| v as u32);
@@ -162,12 +163,16 @@ impl Tool for RightClickTool {
// Pin overlay above the target window before animating.
if let Some(wid) = window_id {
crate::cursor::overlay::send_command(
- cursor_overlay::OverlayCommand::PinAbove(wid as u64)
+ cursor_key.clone(),
+ cursor_overlay::OverlayCommand::PinAbove(wid as u64),
);
}
// Animate cursor to the click point; wait for arrival before firing.
- crate::cursor::overlay::animate_cursor_to(screen_x, screen_y).await;
- crate::cursor::overlay::send_command(cursor_overlay::OverlayCommand::ClickPulse { x: screen_x, y: screen_y });
+ crate::cursor::overlay::animate_cursor_to(cursor_key.clone(), screen_x, screen_y).await;
+ crate::cursor::overlay::send_command(
+ cursor_key.clone(),
+ cursor_overlay::OverlayCommand::ClickPulse { x: screen_x, y: screen_y },
+ );
let mod_suffix = if modifiers.is_empty() {
String::new()