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): support multiple direct runtimes per process (#2575)

Francesco Bonacci5f786b058162
diff --git a/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx b/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx
index fc63fdefb4..816b4275df 100644
--- a/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx
+++ b/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx
@@ -125,23 +125,34 @@ for the hosted-daemon procedure.
## Current process facility contract
-The first SDK-owned-runtime milestone deliberately permits one direct runtime
-per process. This makes the remaining process facilities explicit without
-pretending that two in-process objects are isolated:
+A trusted application may own multiple direct runtimes in one process. This is
+lifecycle and resource coordination, not a security boundary or desktop
+virtualization:
| Facility | Current ownership | Concurrency rule |
| --- | --- | --- |
-| Runtime ceiling, effective session contexts, revocation | Runtime-owned | Isolated within the one runtime generation |
-| Tool registry, browser engine and grants, recording session | Runtime-owned | Released on session/runtime shutdown |
+| Runtime ceiling, effective session contexts, revocation | Runtime-owned | Isolated within each opaque runtime generation |
+| Tool registry, browser engine and grants, recording session | Runtime-owned | Released only by their owning session/runtime |
| Permission/policy compatibility caches and bounded compatibility manifest | Immutable process configuration | Explicit configured constructors must agree with contradictory environment values or fail |
-| Session activity, capture scopes, element-token registry, CDP port claims | Process-coordinated | Safe only under the one-direct-runtime guard |
-| Recording platform callbacks, video/PiP factories, observers, ABI executor | Immutable process callbacks/coordinator | First installation is shared by the runtime generation |
-| macOS cursor overlay and other UI event-loop facilities | Process/platform coordinated | Requires the appropriate host main-thread adapter or an explicit worker/service |
-
-A second direct `CuaDriver.create()` returns the structured
-`runtime_already_exists` conflict. Separate trust domains use separate
-runtime-owner processes. Complete same-process multi-runtime support remains a
-later isolation gate; it cannot be enabled merely by removing the guard.
+| Session activity, capture scopes, element tokens, browser refs, cursor keys | Runtime-namespaced | The same public session label in two runtimes remains independent; stale or cross-runtime handles fail closed |
+| Physical pointer, keyboard, focus, overlay, and platform event loops | Process/platform coordinated | Native input and focus action turns are admitted one at a time; all runtimes still operate the same physical desktop |
+| CDP listener claims and the download gate | Process-coordinated | A listener/profile claim or download lease cannot be silently taken over by another runtime |
+| Recording platform callbacks, video/PiP factories, policy, observers, ABI executor | Immutable process callbacks/coordinator | Shared only where the process identity and platform configuration are the same |
+
+Shutting down runtime A does not revoke runtime B's sessions or stop its
+recording. Public session labels and element-token wire formats remain
+unchanged; the runtime generation is private and never accepted from a tool
+argument.
+
+The reserved anonymous `default` cursor/session fallback is process-shared and
+does not provide lifecycle isolation. Give each concurrent host operation an
+explicit session (or cursor ID). The first enabled runtime initializes the
+process-global overlay template; later runtimes reuse it and can customize
+their own namespaced cursors through the cursor tools.
+
+Arbitrary code in the host process can inspect or interfere with every
+runtime. Use separate private workers or services for crash isolation,
+different trust domains, different OS identities, or independent desktops.
On macOS, the cursor overlay additionally requires an AppKit main-thread UI
owner. A direct runtime without a certified host adapter returns structured
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index 5d9deb9669..e6206fdacd 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -543,7 +543,7 @@ State persists for the life of the daemon; a restart resets to disabled with no
Stop trajectory recording. Disables further per-turn capture and, when video was enabled, gracefully terminates the ffmpeg subprocess so the mp4's moov atom is finalized (the file is playable). Calling stop on an already-stopped session is a no-op. The response carries `last_video_path` pointing at the finalized mp4 (when video was on).
-A manual `stop_recording` is **unconditional** — it stops whatever recording is active regardless of which session started it. Ownership-scoped teardown (so one MCP client disconnecting can't stop a recording a later client started) is handled by the daemon's `session_end` lifecycle signal, not by this tool.
+A manual `stop_recording` is **unconditional** — it stops whatever recording is active regardless of which session started it. Ownership-scoped teardown (so one client disconnecting can't stop a recording a later client started) is handled by the registry's `session_end` lifecycle hook, not by this tool.
**Arguments:** none.
diff --git a/docs/content/docs/reference/cua-driver/process-model.mdx b/docs/content/docs/reference/cua-driver/process-model.mdx
index 55609921da..c9c7ed2426 100644
--- a/docs/content/docs/reference/cua-driver/process-model.mdx
+++ b/docs/content/docs/reference/cua-driver/process-model.mdx
@@ -83,7 +83,18 @@ The daemon belongs in the interactive user session instead. It may be kept there
## Session identity and shared state
-A daemon drives one physical machine. Multiple MCP clients can connect at the same time, but they still share the same screen, keyboard, pointer, accessibility tree, and recording machinery. Session identity does not make concurrent control independent. Two agents clicking at once still contend for the same desktop.
+A daemon drives one physical machine. Multiple MCP clients can connect at the
+same time, and a trusted SDK host may create multiple direct runtimes, but they
+still share the same screen, keyboard, pointer, accessibility tree, and OS
+focus. Session or runtime identity does not create an independent desktop.
+Native pointer, keyboard, value-setting, and focus calls are admitted one at a
+time inside a process so their input delivery does not overlap. Post-action
+recording and PiP capture happen after that admission is released and may
+observe later desktop activity. Application lifecycle operations and
+browser/CDP mutations are not covered by the input gate. Higher-level sequences
+can still interleave unless the host schedules them; in particular, do not
+split a button-down/drag/up gesture across independently scheduled runtime
+calls.
On Windows and Linux, bare MCP processes each own a separate runtime. To
deliberately share one daemon across several MCP clients, start the daemon and
@@ -92,6 +103,15 @@ command. Do not rely on ambient daemon discovery.
Session identity solves a narrower state problem. When a proxy starts, it mints a session identity and stamps forwarded calls with it. The daemon uses that identity to scope mutable state to one client lifetime. Recording ownership, per-session config overrides, and the agent-cursor overlay are all keyed by session.
+For same-process SDK runtimes, Cua adds a private runtime generation behind the
+public session label. Two runtimes may therefore both use `research-1` without
+sharing capture scope, tombstones, cursor ownership, recording teardown,
+browser refs, or element tokens. The private generation is never serialized
+and is not a credential or same-process security boundary.
+
+`default` is the reserved anonymous fallback, not an isolated session label.
+Concurrent hosts should always declare an explicit session.
+
<VideoDemo
className="my-8"
src="https://trycua.github.io/assets/videos/cua-driver/windows-hermes-four-agent-windows.mp4"
@@ -114,7 +134,8 @@ construct a fresh tool registry or continue with partial state.
For a same-process SDK runtime, the importing application owns the equivalent
lifetime. End every session, await `shutdown()`, and release the generated
-binding handle during orderly teardown.
+binding handle during orderly teardown. Shutting down one direct runtime does
+not stop or revoke another direct runtime in the same process.
Before each daemon-backed SDK action, the client reads the daemon metadata and
verifies contract, tool-schema, capability, and MCP
diff --git a/docs/content/docs/reference/cua-driver/sdk-reference.mdx b/docs/content/docs/reference/cua-driver/sdk-reference.mdx
index 6be11cb7e2..e578da2c01 100644
--- a/docs/content/docs/reference/cua-driver/sdk-reference.mdx
+++ b/docs/content/docs/reference/cua-driver/sdk-reference.mdx
@@ -37,8 +37,10 @@ returns a tool error with stable code `permission_denied`.
`authorization` field is `RuntimeAuthorizationOptions`: an allowed-mode
set, the compatibility mode inherited by ordinary `CuaDriver` calls, bounded
manifest path when that compatibility mode is bounded, maximum absolute and
-idle session TTLs, and the separate unrestricted-risk acknowledgement. A
-second same-process runtime returns `DriverError.RuntimeAlreadyExists`.
+idle session TTLs, and the separate unrestricted-risk acknowledgement.
+Applications may create more than one same-process runtime. Each runtime owns
+an independent authorization ceiling, session registry, browser bindings,
+recording state, and shutdown lifecycle.
Trusted host code may call the top-level `create_trusted_session(driver, …)` /
`createTrustedSession(driver, …)` factory and receive a `CuaDriverSession`.
@@ -151,6 +153,10 @@ Inspect the result before consuming images or structured fields.
`Completed`, or `Unknown`. Do not automatically retry a non-idempotent action
when completion is unknown.
+`RuntimeAlreadyExists` remains in the stable error vocabulary for hosts or
+platform facilities that cannot safely establish another owner. Ordinary
+second-runtime creation no longer returns it.
+
See [MCP tools](/reference/cua-driver/mcp-tools) for the agent-facing tool
catalog and [SDK, MCP, and process hosting](/concepts/sdk-mcp-and-hosting) for
the architecture boundary.
diff --git a/libs/cua-driver/python/src/cua_driver/_native.py b/libs/cua-driver/python/src/cua_driver/_native.py
index 93932dcbc1..b8e19bc2eb 100644
--- a/libs/cua-driver/python/src/cua_driver/_native.py
+++ b/libs/cua-driver/python/src/cua_driver/_native.py
@@ -536,6 +536,8 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key() != 63712:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_runtime_scope_prefix() != 2453:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_scroll() != 52290:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_shutdown() != 36331:
@@ -1028,6 +1030,11 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_press_key.argtypes = (
cua_driver._native_contract._UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_press_key.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_runtime_scope_prefix.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_runtime_scope_prefix.restype = _UniffiRustBuffer
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_scroll.argtypes = (
ctypes.c_uint64,
cua_driver._native_contract._UniffiRustBuffer,
@@ -1258,6 +1265,9 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor.restype =
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_runtime_scope_prefix.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_runtime_scope_prefix.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_scroll.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_scroll.restype = ctypes.c_uint16
@@ -3338,6 +3348,8 @@ class CuaDriverProtocol(typing.Protocol):
raise NotImplementedError
async def press_key(self, input: cua_driver._native_contract.PressKeyInput) -> ToolResult:
raise NotImplementedError
+ def runtime_scope_prefix(self, ) -> typing.Optional[str]:
+ raise NotImplementedError
async def scroll(self, input: cua_driver._native_contract.ScrollInput) -> ToolResult:
raise NotImplementedError
async def shutdown(self, ) -> None:
@@ -3815,6 +3827,18 @@ class CuaDriver(CuaDriverProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ def runtime_scope_prefix(self, ) -> typing.Optional[str]:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterOptionalString.lift
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_runtime_scope_prefix,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
async def scroll(self, input: cua_driver._native_contract.ScrollInput) -> ToolResult:
cua_driver._native_contract._UniffiFfiConverterTypeScrollInput.check_lower(input)
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
index 79bb4c317e..43c8e7cb3b 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
@@ -24,13 +24,13 @@
//! omitted from the snapshot — never guessed.
use std::collections::{HashMap, HashSet};
-use std::sync::{Arc, Weak};
+use std::sync::{Arc, Mutex, Weak};
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use serde_json::{json, Value};
use uuid::Uuid;
-use crate::session::register_session_end_hook;
+use crate::session::register_scoped_session_end_hook;
use super::binding::{
cardinality_exact_candidate, correlate, selected_tab_target_id, BindingOutcome,
@@ -80,6 +80,7 @@ pub struct BrowserEngine {
pub(crate) approval_broker: crate::consent::ApprovalBroker,
mutation_gates: MutationGates,
reconnect_gates: ReconnectGates,
+ session_end_hook: Mutex<Option<crate::session::SessionEndHookRegistration>>,
}
fn refuse(code: BrowserRefusalCode, msg: impl Into<String>) -> BrowserRefusal {
@@ -543,9 +544,10 @@ impl BrowserEngine {
approval_broker: crate::consent::ApprovalBroker::new(provider),
mutation_gates: MutationGates::new(),
reconnect_gates: ReconnectGates::new(),
+ session_end_hook: Mutex::new(None),
});
let weak: Weak<Self> = Arc::downgrade(&engine);
- register_session_end_hook(move |session_id| {
+ let registration = register_scoped_session_end_hook(move |session_id| {
if let Some(engine) = weak.upgrade() {
engine.store.remove_session(session_id);
engine.cleanup_prepared_session(session_id);
@@ -569,6 +571,7 @@ impl BrowserEngine {
}
}
});
+ *engine.session_end_hook.lock().unwrap() = Some(registration);
engine
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/store.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/store.rs
index 2f856c30bd..ebbb3accf6 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/store.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/store.rs
@@ -254,19 +254,18 @@ pub fn format_ref(snapshot_id: u64, index: u32) -> String {
pub struct BrowserStore {
inner: Mutex<HashMap<String, SessionTargets>>,
- next_id: AtomicU64,
}
impl BrowserStore {
pub fn new() -> Self {
Self {
inner: Mutex::new(HashMap::new()),
- next_id: AtomicU64::new(1),
}
}
fn next(&self) -> u64 {
- self.next_id.fetch_add(1, Ordering::Relaxed)
+ static NEXT_BROWSER_SNAPSHOT_ID: AtomicU64 = AtomicU64::new(1);
+ NEXT_BROWSER_SNAPSHOT_ID.fetch_add(1, Ordering::Relaxed)
}
/// Mint a target id and insert the record under `session`.
@@ -581,6 +580,17 @@ mod tests {
assert_eq!(err.code, BrowserRefusalCode::BrowserBindingStale);
}
+ #[test]
+ fn page_refs_do_not_alias_across_runtime_owned_stores() {
+ let (_store_a, _target_a, _tab_a, ref_a) = store_with_ref();
+ let (store_b, target_b, tab_b, ref_b) = store_with_ref();
+ assert_ne!(ref_a, ref_b);
+ let error = store_b
+ .resolve_ref("sess-a", &target_b, &tab_b, &ref_a)
+ .unwrap_err();
+ assert_eq!(error.code, BrowserRefusalCode::BrowserRefStale);
+ }
+
#[test]
fn foreign_namespace_refs_are_refused_as_stale() {
let (store, tid, tab, _) = store_with_ref();
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs
index b7561bd728..27c2597146 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs
@@ -106,6 +106,13 @@ pub fn clear_session(session: &str) {
scopes().lock().unwrap().remove(session);
}
+pub fn clear_sessions_with_prefix(prefix: &str) -> usize {
+ let mut registry = scopes().lock().unwrap();
+ let before = registry.len();
+ registry.retain(|session, _| !session.starts_with(prefix));
+ before - registry.len()
+}
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EscalateError {
Ended,
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/cursor_sampler.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/cursor_sampler.rs
index 8e3001d218..4db005109f 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/cursor_sampler.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/cursor_sampler.rs
@@ -114,9 +114,13 @@ fn sample_cursor() -> Option<(f64, f64)> {
// CGEventGetLocation(event) → CGPoint. The point is in points
// (top-left origin) so it matches the cursor-space convention the
// renderer uses.
+ #[link(name = "ApplicationServices", kind = "framework")]
extern "C" {
fn CGEventCreate(source: *mut std::ffi::c_void) -> *mut std::ffi::c_void;
fn CGEventGetLocation(event: *mut std::ffi::c_void) -> CGPoint;
+ }
+ #[link(name = "CoreFoundation", kind = "framework")]
+ extern "C" {
fn CFRelease(cf: *mut std::ffi::c_void);
}
#[repr(C)]
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs
index 062caff68f..265f3d0a49 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs
@@ -93,13 +93,13 @@ struct SnapshotEntry {
/// pid's vec is the LRU (newest at the back). Vec instead of VecDeque
/// because the cap is tiny (8) and walks are linear either way.
pub struct TokenRegistry {
- by_pid: Mutex<HashMap<i32, Vec<SnapshotEntry>>>,
+ by_runtime_and_pid: Mutex<HashMap<(String, i32), Vec<SnapshotEntry>>>,
}
impl TokenRegistry {
fn new() -> Self {
Self {
- by_pid: Mutex::new(HashMap::new()),
+ by_runtime_and_pid: Mutex::new(HashMap::new()),
}
}
@@ -122,8 +122,9 @@ impl TokenRegistry {
// the 4-hex-char prefix can carry. Round-trip property:
// `resolve(format_token(id, idx))` always finds the entry.
let id = mint_snapshot_id() & 0xffff;
- let mut by_pid = self.by_pid.lock().unwrap();
- let lane = by_pid.entry(pid).or_default();
+ let runtime_scope = current_runtime_scope();
+ let mut entries = self.by_runtime_and_pid.lock().unwrap();
+ let lane = entries.entry((runtime_scope, pid)).or_default();
lane.push(SnapshotEntry {
snapshot_id: id,
window_id,
@@ -152,14 +153,29 @@ impl TokenRegistry {
pub fn resolve(&self, pid: i32, token: &str) -> Result<(u32, usize), String> {
let (sid, idx) =
parse_token(token).ok_or_else(|| "element_token has invalid format".to_string())?;
- let by_pid = self.by_pid.lock().unwrap();
- let lane = by_pid
- .get(&pid)
- .ok_or_else(|| STALE_TOKEN_ERROR.to_string())?;
- let entry = lane
- .iter()
- .find(|e| e.snapshot_id == sid)
- .ok_or_else(|| STALE_TOKEN_ERROR.to_string())?;
+ let runtime_scope = current_runtime_scope();
+ let entries = self.by_runtime_and_pid.lock().unwrap();
+ let belongs_to_another_runtime = || {
+ entries.iter().any(|((scope, entry_pid), snapshots)| {
+ scope != &runtime_scope
+ && *entry_pid == pid
+ && snapshots.iter().any(|entry| entry.snapshot_id == sid)
+ })
+ };
+ let lane = entries.get(&(runtime_scope.clone(), pid)).ok_or_else(|| {
+ if belongs_to_another_runtime() {
+ "element_token belongs to another runtime generation".to_owned()
+ } else {
+ STALE_TOKEN_ERROR.to_owned()
+ }
+ })?;
+ let entry = lane.iter().find(|e| e.snapshot_id == sid).ok_or_else(|| {
+ if belongs_to_another_runtime() {
+ "element_token belongs to another runtime generation".to_owned()
+ } else {
+ STALE_TOKEN_ERROR.to_owned()
+ }
+ })?;
if idx > entry.max_element_index {
return Err(format!(
"element_token element_index {idx} out of range (snapshot had {} elements)",
@@ -169,6 +185,13 @@ impl TokenRegistry {
Ok((entry.window_id, idx))
}
+ pub fn clear_runtime_scope(&self, runtime_scope: &str) -> usize {
+ let mut entries = self.by_runtime_and_pid.lock().unwrap();
+ let before = entries.len();
+ entries.retain(|(scope, _), _| scope != runtime_scope);
+ before - entries.len()
+ }
+
/// Build the canonical token string for `snapshot_id` / `element_index`.
/// Pure helper, mirrors [`format_token`] but lives on the registry so
/// callers don't have to import the free function.
@@ -181,22 +204,27 @@ impl TokenRegistry {
/// unit test to assert the cap was honoured.
#[cfg(test)]
fn snapshot_count(&self, pid: i32) -> usize {
- self.by_pid
+ self.by_runtime_and_pid
.lock()
.unwrap()
- .get(&pid)
- .map(|v| v.len())
- .unwrap_or(0)
+ .iter()
+ .filter(|((_, entry_pid), _)| *entry_pid == pid)
+ .map(|(_, entries)| entries.len())
+ .sum()
}
/// Test-only: clear all state. Lets parallel unit tests start clean
/// without relying on the global counter being at a specific value.
#[cfg(test)]
fn clear(&self) {
- self.by_pid.lock().unwrap().clear();
+ self.by_runtime_and_pid.lock().unwrap().clear();
}
}
+fn current_runtime_scope() -> String {
+ crate::tool::current_dispatch_runtime_scope().unwrap_or_else(|| "legacy".to_owned())
+}
+
impl Default for TokenRegistry {
fn default() -> Self {
Self::new()
@@ -334,9 +362,24 @@ pub fn resolve_element_args(
(idx_opt, Some(tok)) => {
// Token wins. Resolve through the registry; bail on stale
// or malformed without falling back to the integer.
- let (wid, idx) = global()
- .resolve(pid, tok)
- .map_err(crate::protocol::ToolResult::error)?;
+ let (wid, idx) = global().resolve(pid, tok).map_err(|message| {
+ let code = if message.contains("another runtime generation") {
+ "generation_mismatch"
+ } else if message == STALE_TOKEN_ERROR {
+ "stale_element_token"
+ } else {
+ "invalid_element_token"
+ };
+ crate::protocol::ToolResult::error(message.clone()).with_structured(
+ serde_json::json!({
+ "status": "refused",
+ "refusal": {
+ "code": code,
+ "message": message,
+ }
+ }),
+ )
+ })?;
if let Some(int_idx) = idx_opt {
if int_idx != idx {
// Disagreement is non-fatal — token wins, but we
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs
index 468769f832..3a032a25a9 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs
@@ -13,7 +13,7 @@
//! stop|status`) and removes the "is this a setting write?" ambiguity of
//! the old `set_*` name.
-use std::sync::{Arc, OnceLock, Weak};
+use std::sync::{Arc, Mutex, OnceLock, Weak};
use async_trait::async_trait;
use serde_json::{json, Value};
@@ -24,20 +24,7 @@ use crate::{
tool::{Tool, ToolDef, ToolRegistry},
};
-// ── Process-global weak reference to the registry (for replay) ───────────────
-//
-// Set once by `ToolRegistry::init_replay(weak)` after `Arc::new(registry)`.
-
-static REPLAY_REGISTRY: OnceLock<Weak<ToolRegistry>> = OnceLock::new();
-
-/// Called from `main.rs` after wrapping the registry in `Arc`.
-pub fn init_replay_registry(weak: Weak<ToolRegistry>) {
- let _ = REPLAY_REGISTRY.set(weak);
-}
-
-fn get_replay_registry() -> Option<Arc<ToolRegistry>> {
- REPLAY_REGISTRY.get()?.upgrade()
-}
+pub type ReplayRegistrySlot = Arc<Mutex<Weak<ToolRegistry>>>;
// ── start_recording ──────────────────────────────────────────────────────────
@@ -197,9 +184,9 @@ impl Tool for StopRecordingTool {
`last_video_path` pointing at the finalized mp4 (when video was on).\n\n\
A manual `stop_recording` is **unconditional** — it stops whatever \
recording is active regardless of which session started it. \
- Ownership-scoped teardown (so one MCP client disconnecting can't stop a \
- recording a later client started) is handled by the daemon's \
- `session_end` lifecycle signal, not by this tool."
+ Ownership-scoped teardown (so one client disconnecting can't stop a \
+ recording a later client started) is handled by the registry's \
+ `session_end` lifecycle hook, not by this tool."
.into(),
input_schema: json!({
"type": "object",
@@ -216,7 +203,7 @@ impl Tool for StopRecordingTool {
async fn invoke(&self, _args: Value) -> ToolResult {
// Manual stop is unconditional — `None` requester tears down whatever
// recording is active. Session-scoped teardown is driven by the
- // daemon's `session_end` arm (serve.rs), which calls `stop_owner(sid)`.
+ // registry-owned session-end hook, which calls `stop_owner(sid)`.
match self.session.stop_owner(None) {
Ok(()) => {
let state = self.session.current_state();
@@ -287,7 +274,15 @@ impl Tool for GetRecordingStateTool {
// ── replay_trajectory ─────────────────────────────────────────────────────────
-pub struct ReplayTrajectoryTool;
+pub struct ReplayTrajectoryTool {
+ registry: ReplayRegistrySlot,
+}
+
+impl ReplayTrajectoryTool {
+ pub fn new(registry: ReplayRegistrySlot) -> Self {
+ Self { registry }
+ }
+}
static REPLAY_DEF: OnceLock<ToolDef> = OnceLock::new();
@@ -388,7 +383,7 @@ impl Tool for ReplayTrajectoryTool {
));
}
- let registry = match get_replay_registry() {
+ let registry = match self.registry.lock().unwrap().upgrade() {
Some(r) => r,
None => {
return ToolResult::error("Replay not available: registry not initialised yet.")
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
index bea185f2c4..89f1b54132 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
@@ -863,7 +863,6 @@ pub async fn handle_request(
"_transport_session_id".to_owned(),
serde_json::Value::String(session.clone()),
);
- crate::session::touch_session(&session);
}
if call.name == "browser_prepare" {
if let Some(arguments) = call.args.as_object_mut() {
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 755c0d64a6..35aa4443f0 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
@@ -19,12 +19,15 @@
//! reverse coupling from core into the platform crates.
use std::collections::{HashMap, HashSet};
-use std::sync::{Arc, Mutex, OnceLock};
+use std::sync::{
+ atomic::{AtomicU64, Ordering},
+ Arc, Mutex, OnceLock,
+};
use std::time::{Duration, Instant};
use cua_driver_contract::{CaptureScope, EscalationReason};
-type SessionEndHook = Box<dyn Fn(&str) + Send + Sync>;
+type SessionEndHook = Arc<dyn Fn(&str) + Send + Sync>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionDeclaration {
@@ -69,6 +72,12 @@ pub struct SessionStartObservation {
pub capture_scope: CaptureScope,
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct SessionObservationState {
+ pub ended: bool,
+ pub capture_scope: CaptureScope,
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CursorStyleCategory {
Default,
@@ -166,7 +175,8 @@ pub trait SessionObserver: Send + Sync + 'static {
static SESSION_OBSERVER: OnceLock<Arc<dyn SessionObserver>> = OnceLock::new();
type CursorOutcomeReader = Arc<dyn Fn(&str) -> CursorOutcomeObservation + Send + Sync>;
-static CURSOR_OUTCOME_READER: OnceLock<Mutex<Option<CursorOutcomeReader>>> = OnceLock::new();
+static CURSOR_OUTCOME_READERS: OnceLock<Mutex<HashMap<u64, CursorOutcomeReader>>> = OnceLock::new();
+static NEXT_CURSOR_OUTCOME_READER_ID: AtomicU64 = AtomicU64::new(1);
pub fn set_session_observer(observer: Arc<dyn SessionObserver>) -> bool {
SESSION_OBSERVER.set(observer).is_ok()
@@ -176,13 +186,38 @@ pub fn set_session_observer(observer: Arc<dyn SessionObserver>) -> bool {
/// used only for the synchronous process-local lookup; the callback returns a
/// struct that cannot contain raw cursor values.
pub fn set_cursor_outcome_reader(reader: CursorOutcomeReader) -> bool {
- *CURSOR_OUTCOME_READER
- .get_or_init(|| Mutex::new(None))
+ CURSOR_OUTCOME_READERS
+ .get_or_init(|| Mutex::new(HashMap::new()))
.lock()
- .unwrap() = Some(reader);
+ .unwrap()
+ .insert(0, reader);
true
}
+pub fn register_scoped_cursor_outcome_reader(
+ reader: CursorOutcomeReader,
+) -> CursorOutcomeReaderRegistration {
+ let id = NEXT_CURSOR_OUTCOME_READER_ID.fetch_add(1, Ordering::Relaxed);
+ CURSOR_OUTCOME_READERS
+ .get_or_init(|| Mutex::new(HashMap::new()))
+ .lock()
+ .unwrap()
+ .insert(id, reader);
+ CursorOutcomeReaderRegistration { id }
+}
+
+pub struct CursorOutcomeReaderRegistration {
+ id: u64,
+}
+
+impl Drop for CursorOutcomeReaderRegistration {
+ fn drop(&mut self) {
+ if let Some(readers) = CURSOR_OUTCOME_READERS.get() {
+ readers.lock().unwrap().remove(&self.id);
+ }
+ }
+}
+
/// Private per-call context. The raw caller session id never crosses into a
/// serialized observation; it is retained only until the bounded completion
/// callback updates the process-local aggregate.
@@ -207,7 +242,8 @@ impl SessionToolContext {
}
}
-static SESSION_END_HOOKS: OnceLock<Mutex<Vec<SessionEndHook>>> = OnceLock::new();
+static SESSION_END_HOOKS: OnceLock<Mutex<HashMap<u64, SessionEndHook>>> = OnceLock::new();
+static NEXT_SESSION_END_HOOK_ID: AtomicU64 = AtomicU64::new(1);
/// Last-activity timestamp per live session id. A session is "touched" every
/// time a tool call carries its explicit `session` id (see the daemon boundary
@@ -236,6 +272,21 @@ pub fn begin_tool_call(
known_tool: bool,
transport: SessionTransport,
client_kind: SessionClientKind,
+) -> Option<SessionToolContext> {
+ begin_tool_call_with_state(tool_name, args, known_tool, transport, client_kind, None)
+}
+
+/// Begin observation with a runtime-owner-provided view of public session
+/// state. Runtime owners use this seam because their mutable scope and
+/// tombstone state is keyed by a private runtime generation, while telemetry
+/// must continue to report the caller's stable public session label.
+pub fn begin_tool_call_with_state(
+ tool_name: &str,
+ args: &serde_json::Value,
+ known_tool: bool,
+ transport: SessionTransport,
+ client_kind: SessionClientKind,
+ observed_state: Option<SessionObservationState>,
) -> Option<SessionToolContext> {
if !known_tool {
return None;
@@ -246,20 +297,23 @@ pub fn begin_tool_call(
.filter(|id| is_trackable(id))?;
let is_start = tool_name == "start_session";
let is_end = tool_name == "end_session";
- let revived = is_start && is_session_ended(session_id);
- if is_session_ended(session_id) && !is_start {
+ let ended = observed_state
+ .map(|state| state.ended)
+ .unwrap_or_else(|| is_session_ended(session_id));
+ let revived = is_start && ended;
+ if ended && !is_start {
return None;
}
- touch_session(session_id);
let capture_scope = if is_start {
args.get("capture_scope")
.cloned()
.and_then(|value| serde_json::from_value(value).ok())
.unwrap_or_default()
} else {
- crate::capture_scope::get_session(session_id)
- .map(|state| state.policy)
+ observed_state
+ .map(|state| state.capture_scope)
+ .or_else(|| crate::capture_scope::get_session(session_id).map(|state| state.policy))
.unwrap_or_default()
};
let escalation_reason = (tool_name == "escalate_session")
@@ -305,14 +359,28 @@ pub fn begin_tool_call(
/// 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 hooks() -> &'static Mutex<HashMap<u64, SessionEndHook>> {
+ SESSION_END_HOOKS.get_or_init(|| Mutex::new(HashMap::new()))
}
fn ended_sessions() -> &'static Mutex<HashSet<String>> {
ENDED_SESSIONS.get_or_init(|| Mutex::new(HashSet::new()))
}
+fn public_session_label(session_id: &str) -> &str {
+ let Some(rest) = session_id.strip_prefix("__cua_runtime_") else {
+ return session_id;
+ };
+ let Some((scope, public)) = rest.split_once(':') else {
+ return session_id;
+ };
+ if scope.len() == 32 && scope.bytes().all(|byte| byte.is_ascii_hexdigit()) {
+ public
+ } else {
+ session_id
+ }
+}
+
/// 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
@@ -320,7 +388,33 @@ fn ended_sessions() -> &'static Mutex<HashSet<String>> {
/// fires once per proxy exit, but a hook should treat a clear of an unseen id
/// as a no-op.
pub fn register_session_end_hook(hook: impl Fn(&str) + Send + Sync + 'static) {
- hooks().lock().unwrap().push(Box::new(hook));
+ std::mem::forget(register_scoped_session_end_hook(hook));
+}
+
+/// Register a runtime-owned cleanup hook. Dropping the returned guard removes
+/// the callback, preventing create/shutdown cycles from accumulating stale
+/// platform and browser hooks.
+pub fn register_scoped_session_end_hook(
+ hook: impl Fn(&str) + Send + Sync + 'static,
+) -> SessionEndHookRegistration {
+ let id = NEXT_SESSION_END_HOOK_ID.fetch_add(1, Ordering::Relaxed);
+ hooks().lock().unwrap().insert(id, Arc::new(hook));
+ SessionEndHookRegistration { id }
+}
+
+pub struct SessionEndHookRegistration {
+ id: u64,
+}
+
+impl Drop for SessionEndHookRegistration {
+ fn drop(&mut self) {
+ hooks().lock().unwrap().remove(&self.id);
+ }
+}
+
+#[doc(hidden)]
+pub fn session_end_hook_count() -> usize {
+ hooks().lock().unwrap().len()
}
/// Fan a session-end out to every registered cleanup hook. Called by the daemon
@@ -342,7 +436,13 @@ pub fn fire_session_end(session_id: &str) -> bool {
}
}
crate::capture_scope::clear_session(session_id);
- for hook in hooks().lock().unwrap().iter() {
+ let registered = hooks()
+ .lock()
+ .unwrap()
+ .values()
+ .cloned()
+ .collect::<Vec<_>>();
+ for hook in registered {
hook(session_id);
}
true
@@ -359,6 +459,35 @@ pub fn revoke_all_sessions() -> usize {
sessions.len()
}
+/// Revoke only sessions owned by one runtime-private namespace.
+pub fn revoke_sessions_with_prefix(prefix: &str) -> usize {
+ let sessions: Vec<String> = activity()
+ .lock()
+ .unwrap()
+ .keys()
+ .filter(|session| session.starts_with(prefix))
+ .cloned()
+ .collect();
+ for session in &sessions {
+ end_session(session);
+ }
+ sessions.len()
+}
+
+/// Forget terminal tombstones owned by a runtime generation that is itself
+/// being destroyed. Live runtimes must retain tombstones until an explicit
+/// `start_session` revival; otherwise an operator revocation could be bypassed
+/// by reusing the same public session label on another transport.
+pub fn forget_ended_sessions_with_prefix(prefix: &str) -> usize {
+ let mut ended = ended_sessions().lock().unwrap();
+ let before = ended.len();
+ ended.retain(|session| !session.starts_with(prefix));
+ let forgotten = before - ended.len();
+ drop(ended);
+ crate::capture_scope::clear_sessions_with_prefix(prefix);
+ forgotten
+}
+
/// 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.
@@ -383,11 +512,12 @@ pub fn revive_session(session_id: &str) -> bool {
ended_sessions().lock().unwrap().remove(session_id)
}
-/// Record activity for an explicit session id, resetting its idle-TTL clock.
-/// Called at the daemon boundary on every tool call that carries an explicit
-/// `session`. No-op for the anonymous fallback (`"default"` / empty) and for a
-/// session that has already ended (so a late in-flight call can't resurrect a
-/// reaped session's TTL entry).
+/// Record activity for an explicit runtime-private session id, resetting its
+/// idle-TTL clock. Called at the authorized registry boundary after public
+/// arguments have been mapped into their owning runtime namespace. No-op for
+/// the anonymous fallback (`"default"` / empty) and for a session that has
+/// already ended (so a late in-flight call can't resurrect a reaped session's
+/// TTL entry).
pub fn touch_session(session_id: &str) {
if !is_trackable(session_id) || is_session_ended(session_id) {
return;
@@ -398,6 +528,20 @@ pub fn touch_session(session_id: &str) {
.insert(session_id.to_owned(), Instant::now());
}
+#[doc(hidden)]
+pub fn has_session_activity(session_id: &str) -> bool {
+ activity().lock().unwrap().contains_key(session_id)
+}
+
+#[doc(hidden)]
+pub fn session_idle_duration(session_id: &str) -> Option<Duration> {
+ activity()
+ .lock()
+ .unwrap()
+ .get(session_id)
+ .map(Instant::elapsed)
+}
+
/// End a session explicitly (the `end_session` tool / `session end` CLI verb):
/// drop its idle-TTL entry and fan `fire_session_end` out to every cleanup hook
/// (overlay remove, recording stop, config-override clear). Idempotent via
@@ -411,13 +555,32 @@ fn end_session_with_reason(session_id: &str, reason: SessionEndReason) {
return;
}
activity().lock().unwrap().remove(session_id);
- let cursor_reader = CURSOR_OUTCOME_READER
+ let mut cursor_readers = CURSOR_OUTCOME_READERS
.get()
- .and_then(|reader| reader.lock().unwrap().clone());
- let cursor = cursor_reader.map(|reader| reader(session_id));
+ .map(|readers| {
+ readers
+ .lock()
+ .unwrap()
+ .iter()
+ .map(|(id, reader)| (*id, reader.clone()))
+ .collect::<Vec<_>>()
+ })
+ .unwrap_or_default();
+ cursor_readers.sort_by_key(|(id, _)| *id);
+ let mut fallback = None;
+ let cursor = cursor_readers.into_iter().find_map(|(_, reader)| {
+ let outcome = reader(session_id);
+ if outcome.observed {
+ Some(outcome)
+ } else {
+ fallback.get_or_insert(outcome);
+ None
+ }
+ });
+ let cursor = cursor.or(fallback);
if fire_session_end(session_id) {
if let Some(observer) = SESSION_OBSERVER.get() {
- observer.on_session_ended(session_id, reason, cursor);
+ observer.on_session_ended(public_session_label(session_id), reason, cursor);
}
}
}
@@ -443,6 +606,23 @@ pub fn evict_idle(ttl: Duration) -> Vec<String> {
stale
}
+/// Runtime-scoped form of [`evict_idle`]. The namespace prefix is minted by
+/// the trusted runtime and never accepted from a tool argument.
+pub fn evict_idle_with_prefix(ttl: Duration, prefix: &str) -> Vec<String> {
+ let now = Instant::now();
+ let stale: Vec<String> = {
+ let map = activity().lock().unwrap();
+ map.iter()
+ .filter(|(id, last)| id.starts_with(prefix) && now.duration_since(**last) >= ttl)
+ .map(|(id, _)| id.clone())
+ .collect()
+ };
+ for id in &stale {
+ end_session_with_reason(id, SessionEndReason::IdleTimeout);
+ }
+ stale
+}
+
/// Number of sessions with a live idle-TTL entry. Diagnostics only.
pub fn active_session_count() -> usize {
activity().lock().unwrap().len()
@@ -659,6 +839,28 @@ mod tests {
assert!(!revive_session("test-never-ended-778899"));
}
+ #[test]
+ fn runtime_revoke_retains_tombstones_until_revival_or_runtime_teardown() {
+ let prefix = "__cua_runtime_00112233445566778899aabbccddeeff:";
+ let sid = format!("{prefix}revoked-session");
+ touch_session(&sid);
+
+ assert_eq!(revoke_sessions_with_prefix(prefix), 1);
+ assert!(is_session_ended(&sid));
+ touch_session(&sid);
+ assert!(
+ !has_session_activity(&sid),
+ "ordinary traffic must not resurrect a revoked runtime session"
+ );
+
+ assert!(revive_session(&sid));
+ touch_session(&sid);
+ assert!(has_session_activity(&sid));
+ end_session(&sid);
+ assert_eq!(forget_ended_sessions_with_prefix(prefix), 1);
+ assert!(!is_session_ended(&sid));
+ }
+
#[test]
fn revive_is_noop_for_anonymous_ids() {
// The anonymous fallback is never tracked, so there is nothing to revive.
@@ -804,6 +1006,20 @@ mod tests {
.unwrap();
fire_session_end(control);
+ let runtime_owned = "test-observer-runtime-owned-QR78";
+ begin_tool_call_with_state(
+ "click",
+ &serde_json::json!({"session": runtime_owned}),
+ true,
+ SessionTransport::Daemon,
+ SessionClientKind::Direct,
+ Some(SessionObservationState {
+ ended: false,
+ capture_scope: CaptureScope::Window,
+ }),
+ )
+ .unwrap();
+
let starts = probe.starts.lock().unwrap();
assert!(starts.iter().any(|(id, observation)| {
id == explicit
@@ -820,6 +1036,11 @@ mod tests {
assert!(starts
.iter()
.any(|(id, observation)| id == revived && observation.revived));
+ assert!(starts.iter().any(|(id, observation)| {
+ id == runtime_owned
+ && observation.declaration == SessionDeclaration::ImplicitFirstAction
+ && observation.capture_scope == CaptureScope::Window
+ }));
drop(starts);
let ends = probe.ends.lock().unwrap();
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs
index e85259e487..83673716be 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session_authorization.rs
@@ -192,6 +192,24 @@ pub struct EffectiveAuthorizationContext {
}
impl EffectiveAuthorizationContext {
+ /// Opaque process-local generation used to bind mutable runtime resources.
+ ///
+ /// This value is never serialized or accepted from caller input. Core
+ /// dispatch uses it to keep session state, replay registries, element
+ /// handles, browser bindings, and teardown scoped to their owning runtime.
+ #[doc(hidden)]
+ pub fn runtime_scope_key(&self) -> String {
+ self.daemon_generation.0.simple().to_string()
+ }
+
+ #[doc(hidden)]
+ pub fn runtime_session_key(&self, public_session: &str) -> String {
+ format!(
+ "__cua_runtime_{}:{public_session}",
+ self.runtime_scope_key()
+ )
+ }
+
pub fn mode(&self) -> PermissionMode {
self.mode
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
index 657f93ce75..04151d8aef 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
@@ -1,17 +1,22 @@
//! Tool trait and registry.
use std::collections::HashMap;
-use std::sync::Arc;
+use std::sync::{Arc, OnceLock};
use async_trait::async_trait;
use serde_json::Value;
+thread_local! {
+ static CONSTRUCTION_RUNTIME_SCOPE: std::cell::RefCell<Option<String>> =
+ const { std::cell::RefCell::new(None) };
+}
+
use crate::{
pip_hook,
protocol::{Content, ToolResult},
recording::{now_ms, screenshot_for, RecordingSession},
recording_tools::{
- init_replay_registry, GetRecordingStateTool, ReplayTrajectoryTool, StartRecordingTool,
+ GetRecordingStateTool, ReplayRegistrySlot, ReplayTrajectoryTool, StartRecordingTool,
StopRecordingTool,
},
tool_args::ArgsExt,
@@ -23,6 +28,9 @@ tokio::task_local! {
/// surface; caller arguments and public session labels cannot influence it.
static DISPATCH_AUTHORIZATION_CONTEXT:
Arc<crate::session_authorization::EffectiveAuthorizationContext>;
+ /// Opaque generation for runtime-owned mutable resources. Nested
+ /// dispatches inherit this key, while public arguments can never select it.
+ static DISPATCH_RUNTIME_SCOPE: String;
}
/// Return the immutable authorization context bound to the current dispatch.
@@ -35,6 +43,34 @@ pub(crate) fn current_dispatch_authorization_context(
DISPATCH_AUTHORIZATION_CONTEXT.try_with(Arc::clone).ok()
}
+#[doc(hidden)]
+pub fn current_dispatch_runtime_scope() -> Option<String> {
+ DISPATCH_RUNTIME_SCOPE
+ .try_with(Clone::clone)
+ .ok()
+ .or_else(|| CONSTRUCTION_RUNTIME_SCOPE.with(|scope| scope.borrow().clone()))
+}
+
+#[doc(hidden)]
+pub fn with_runtime_scope<T>(scope: String, action: impl FnOnce() -> T) -> T {
+ struct RestoreScope(Option<String>);
+ impl Drop for RestoreScope {
+ fn drop(&mut self) {
+ CONSTRUCTION_RUNTIME_SCOPE.with(|scope| {
+ scope.replace(self.0.take());
+ });
+ }
+ }
+ let previous = CONSTRUCTION_RUNTIME_SCOPE.with(|current| current.replace(Some(scope)));
+ let _restore = RestoreScope(previous);
+ action()
+}
+
+fn desktop_action_coordinator() -> &'static tokio::sync::Mutex<()> {
+ static COORDINATOR: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
+ COORDINATOR.get_or_init(|| tokio::sync::Mutex::new(()))
+}
+
pub use cua_driver_contract::{CAPABILITY_VERSION, TOOLS_LIST_SCHEMA_VERSION};
/// Metadata for a single tool.
@@ -317,6 +353,16 @@ pub trait Tool: Send + Sync {
async fn invoke(&self, args: Value) -> ToolResult;
}
+struct RuntimeCleanup(Option<Box<dyn FnOnce() + Send + Sync>>);
+
+impl Drop for RuntimeCleanup {
+ fn drop(&mut self) {
+ if let Some(cleanup) = self.0.take() {
+ cleanup();
+ }
+ }
+}
+
/// Thread-safe collection of all registered tools.
pub struct ToolRegistry {
tools: HashMap<String, Box<dyn Tool>>,
@@ -324,6 +370,10 @@ pub struct ToolRegistry {
order: Vec<String>,
/// Shared recording session — auto-records each non-read-only tool call.
pub recording: Arc<RecordingSession>,
+ replay_registry: ReplayRegistrySlot,
+ session_end_hooks: Vec<crate::session::SessionEndHookRegistration>,
+ cursor_outcome_readers: Vec<crate::session::CursorOutcomeReaderRegistration>,
+ runtime_cleanups: Vec<RuntimeCleanup>,
}
impl ToolRegistry {
@@ -332,6 +382,10 @@ impl ToolRegistry {
tools: HashMap::new(),
order: Vec::new(),
recording: Arc::new(RecordingSession::new()),
+ replay_registry: Arc::new(std::sync::Mutex::new(std::sync::Weak::new())),
+ session_end_hooks: Vec::new(),
+ cursor_outcome_readers: Vec::new(),
+ runtime_cleanups: Vec::new(),
}
}
@@ -341,6 +395,25 @@ impl ToolRegistry {
self.tools.insert(name, tool);
}
+ pub fn retain_session_end_hook(
+ &mut self,
+ registration: crate::session::SessionEndHookRegistration,
+ ) {
+ self.session_end_hooks.push(registration);
+ }
+
+ pub fn retain_cursor_outcome_reader(
+ &mut self,
+ registration: crate::session::CursorOutcomeReaderRegistration,
+ ) {
+ self.cursor_outcome_readers.push(registration);
+ }
+
+ pub fn retain_runtime_cleanup(&mut self, cleanup: impl FnOnce() + Send + Sync + 'static) {
+ self.runtime_cleanups
+ .push(RuntimeCleanup(Some(Box::new(cleanup))));
+ }
+
/// Register the four platform-independent recording/replay tools.
/// Call this after all platform tools have been registered.
pub fn register_recording_tools(&mut self) {
@@ -348,7 +421,9 @@ impl ToolRegistry {
self.register(Box::new(StartRecordingTool::new(session.clone())));
self.register(Box::new(StopRecordingTool::new(session.clone())));
self.register(Box::new(GetRecordingStateTool::new(session)));
- self.register(Box::new(ReplayTrajectoryTool));
+ self.register(Box::new(ReplayTrajectoryTool::new(
+ self.replay_registry.clone(),
+ )));
self.register(Box::new(crate::recording_tools::InstallFfmpegTool));
}
@@ -368,7 +443,7 @@ impl ToolRegistry {
/// Wire up the replay tool's weak self-reference.
/// Call this once, immediately after `Arc::new(registry)`.
pub fn init_self_weak(self: &Arc<Self>) {
- init_replay_registry(Arc::downgrade(self));
+ *self.replay_registry.lock().unwrap() = Arc::downgrade(self);
}
pub fn tools_list(&self) -> Value {
@@ -420,6 +495,29 @@ impl ToolRegistry {
/// Invoke a tool by name and (if recording is enabled) write its result to disk.
pub async fn invoke(&self, name: &str, args: Value) -> ToolResult {
if let Ok(context) = DISPATCH_AUTHORIZATION_CONTEXT.try_with(Arc::clone) {
+ let mut args = args;
+ crate::tool_args::sanitize_reserved_args(&mut args);
+ if let Some(bound_session) = context.public_session() {
+ let Some(arguments) = args.as_object_mut() else {
+ return permission_denied_result(
+ "session-bound nested actions require an object argument".to_owned(),
+ );
+ };
+ if arguments
+ .get("session")
+ .and_then(Value::as_str)
+ .is_some_and(|session| session != bound_session)
+ {
+ return permission_denied_result(
+ "nested action session does not match the bound authorization context"
+ .to_owned(),
+ );
+ }
+ arguments.insert(
+ "session".to_owned(),
+ Value::String(bound_session.to_owned()),
+ );
+ }
return self.invoke_authorized(name, args, context.as_ref()).await;
}
let context = match crate::session_authorization::configured_registry()
@@ -446,18 +544,23 @@ impl ToolRegistry {
args: Value,
context: Arc<crate::session_authorization::EffectiveAuthorizationContext>,
) -> ToolResult {
- DISPATCH_AUTHORIZATION_CONTEXT
- .scope(
- context.clone(),
- self.invoke_authorized(name, args, context.as_ref()),
- )
+ let runtime_scope = context.runtime_scope_key();
+ DISPATCH_RUNTIME_SCOPE
+ .scope(runtime_scope, async {
+ DISPATCH_AUTHORIZATION_CONTEXT
+ .scope(
+ context.clone(),
+ self.invoke_authorized(name, args, context.as_ref()),
+ )
+ .await
+ })
.await
}
async fn invoke_authorized(
&self,
name: &str,
- args: Value,
+ mut args: Value,
context: &crate::session_authorization::EffectiveAuthorizationContext,
) -> ToolResult {
// Deprecated alias: `type_text_chars` → `type_text`. Swift's
@@ -492,13 +595,31 @@ impl ToolRegistry {
return permission_denied_result(error.to_string());
}
+ let public_args = args.clone();
+ let recording_args = recording_args_for(resolved_name, &args);
+
+ // Public session labels remain part of the stable transport contract,
+ // but mutable core/platform state must not be keyed by that
+ // caller-chosen label alone. Translate it only after authorization so
+ // policy and manifests continue to evaluate the public request.
+ let runtime_prefix = namespace_runtime_args(&mut args, context);
+ let runtime_session = args
+ .get("session")
+ .and_then(Value::as_str)
+ .map(str::to_owned);
+ if let Some(session) = runtime_session.as_deref() {
+ crate::session::touch_session(session);
+ }
+
// Reject modality violations before reserving a recording turn. A
// rejected action has no before/after evidence and must not leave a
// pending recorder entry behind.
if let Err(violation) = crate::capture_scope::enforce_tool(resolved_name, &args) {
let structured =
violation.as_json(args.get("session").and_then(Value::as_str).unwrap_or(""));
- return ToolResult::error(violation.message).with_structured(structured);
+ let mut result = ToolResult::error(violation.message).with_structured(structured);
+ restore_public_runtime_result(&mut result, &runtime_prefix);
+ return result;
}
// Capture start time for recording timestamps only after validation.
@@ -512,7 +633,20 @@ impl ToolRegistry {
"start_recording" | "stop_recording" | "get_recording_state" | "replay_trajectory"
);
let private_consent_turn = is_existing_profile_prepare(resolved_name, &args);
- let recording_args = recording_args_for(resolved_name, &args);
+ let _desktop_action = if is_physical_desktop_action(resolved_name) {
+ let coordinator = desktop_action_coordinator();
+ // Avoid yielding the dispatch task when the process-wide input
+ // lane is uncontended. On Windows, that yield creates a window in
+ // which the foreground target can lose keyboard eligibility
+ // between the fixture's focus proof and SendInput. Contended
+ // runtimes still wait and serialize through the same mutex.
+ Some(match coordinator.try_lock() {
+ Ok(guard) => guard,
+ Err(_) => coordinator.lock().await,
+ })
+ } else {
+ None
+ };
let pending_turn = should_record
.then(|| {
if private_consent_turn {
@@ -526,6 +660,18 @@ impl ToolRegistry {
.flatten();
let mut result = tool.invoke(args.clone()).await;
+ // Coordinate the physical action itself, not post-action evidence
+ // capture or result shaping. Keeping the global desktop lock through
+ // recording/PiP screenshots would unnecessarily block an unrelated
+ // runtime after the input side effect has already completed.
+ drop(_desktop_action);
+ // A long-running authorized action is active work, not idle time.
+ // Refresh again at completion so the idle TTL measures the gap
+ // between calls rather than time spent executing the previous call.
+ if let Some(session) = runtime_session.as_deref() {
+ crate::session::touch_session(session);
+ }
+ restore_public_runtime_result(&mut result, &runtime_prefix);
let validate_portable_output = match resolved_name {
"get_desktop_state" | "get_screen_size" | "get_cursor_position" => true,
"move_cursor" | "click" | "drag" | "scroll" | "type_text" | "press_key" | "hotkey" => {
@@ -583,7 +729,7 @@ impl ToolRegistry {
let window_id = args.opt_u64("window_id");
let pid = args.opt_i64("pid");
if let Some(png_bytes) = screenshot_for(window_id, pid) {
- let label = synthesize_action_label(name, &args);
+ let label = synthesize_action_label(name, &public_args);
pip_hook::push_pip_frame(pip_hook::PipHookFrame {
png_bytes,
action_label: label,
@@ -596,6 +742,359 @@ impl ToolRegistry {
}
}
+fn is_physical_desktop_action(tool: &str) -> bool {
+ matches!(
+ tool,
+ "click"
+ | "double_click"
+ | "right_click"
+ | "scroll"
+ | "drag"
+ | "mouse_drag"
+ | "parallel_mouse_drag"
+ | "move_cursor"
+ | "mouse_button_down"
+ | "mouse_button_up"
+ | "type_text"
+ | "press_key"
+ | "hotkey"
+ | "set_value"
+ | "bring_to_front"
+ )
+}
+
+fn namespace_runtime_args(
+ args: &mut Value,
+ context: &crate::session_authorization::EffectiveAuthorizationContext,
+) -> String {
+ let runtime_prefix = format!("__cua_runtime_{}:", context.runtime_scope_key());
+ let Some(arguments) = args.as_object_mut() else {
+ return runtime_prefix;
+ };
+ // The registry is the first boundary shared by every transport and the
+ // direct SDK. Transport adapters may already have injected `_session_id`,
+ // but a direct runtime call only carries the public `session` field. Mint
+ // the trusted ownership key here, after authorization, so recording and
+ // every other session-owned resource use the same runtime-private identity
+ // regardless of which adapter invoked the registry.
+ if !arguments.contains_key("_session_id") {
+ if let Some(session) = arguments
+ .get("session")
+ .and_then(Value::as_str)
+ .filter(|value| !value.is_empty())
+ .map(str::to_owned)
+ {
+ arguments.insert("_session_id".to_owned(), Value::String(session));
+ }
+ }
+ for key in ["session", "_session_id", "cursor_id"] {
+ let Some(public) = arguments
+ .get(key)
+ .and_then(Value::as_str)
+ .filter(|value| !value.is_empty() && *value != "default")
+ .map(str::to_owned)
+ else {
+ continue;
+ };
+ let internal = if public.starts_with(&runtime_prefix) {
+ public
+ } else {
+ format!("{runtime_prefix}{public}")
+ };
+ arguments.insert(key.to_owned(), Value::String(internal));
+ }
+ runtime_prefix
+}
+
+fn restore_public_runtime_result(result: &mut ToolResult, runtime_prefix: &str) {
+ for content in &mut result.content {
+ if let Content::Text { text, .. } = content {
+ *text = text.replace(runtime_prefix, "");
+ }
+ }
+ let mut key_collision = false;
+ if let Some(structured) = result.structured_content.as_mut() {
+ key_collision = restore_public_runtime_value(structured, runtime_prefix);
+ }
+ if key_collision {
+ *result = ToolResult::error(
+ "internal runtime namespace restoration produced a duplicate output key",
+ )
+ .with_structured(serde_json::json!({
+ "code": "runtime_output_key_collision",
+ }));
+ }
+}
+
+fn restore_public_runtime_value(value: &mut Value, runtime_prefix: &str) -> bool {
+ match value {
+ Value::String(text) => {
+ *text = text.replace(runtime_prefix, "");
+ false
+ }
+ Value::Array(values) => values.iter_mut().fold(false, |collision, value| {
+ restore_public_runtime_value(value, runtime_prefix) || collision
+ }),
+ Value::Object(values) => {
+ let original = std::mem::take(values);
+ let mut collision = false;
+ for (key, mut value) in original {
+ collision |= restore_public_runtime_value(&mut value, runtime_prefix);
+ collision |= values
+ .insert(key.replace(runtime_prefix, ""), value)
+ .is_some();
+ }
+ collision
+ }
+ _ => false,
+ }
+}
+
+#[cfg(test)]
+mod runtime_isolation_tests {
+ use super::{
+ desktop_action_coordinator, namespace_runtime_args, restore_public_runtime_result,
+ DISPATCH_RUNTIME_SCOPE,
+ };
+ use crate::{
+ authorization::PermissionMode,
+ protocol::ToolResult,
+ session_authorization::{SessionAuthorizationRegistry, SessionModeCeiling},
+ };
+ use std::sync::{
+ atomic::{AtomicUsize, Ordering},
+ Arc,
+ };
+ use std::time::Duration;
+
+ fn standard_context() -> Arc<crate::session_authorization::EffectiveAuthorizationContext> {
+ let ceiling = SessionModeCeiling::for_trusted_sessions(
+ [PermissionMode::Standard],
+ false,
+ Duration::from_secs(60),
+ Duration::from_secs(30),
+ )
+ .unwrap();
+ SessionAuthorizationRegistry::with_ceiling(ceiling)
+ .compatibility_context(PermissionMode::Standard, None)
+ .unwrap()
+ }
+
+ struct ReplayProbe {
+ hits: Arc<AtomicUsize>,
+ def: super::ToolDef,
+ }
+
+ #[async_trait::async_trait]
+ impl super::Tool for ReplayProbe {
+ fn def(&self) -> &super::ToolDef {
+ &self.def
+ }
+
+ async fn invoke(&self, _args: serde_json::Value) -> crate::protocol::ToolResult {
+ self.hits.fetch_add(1, Ordering::SeqCst);
+ crate::protocol::ToolResult::text("probe ran")
+ }
+ }
+
+ fn replay_registry(hits: Arc<AtomicUsize>) -> Arc<super::ToolRegistry> {
+ let mut registry = super::ToolRegistry::new();
+ registry.register(Box::new(ReplayProbe {
+ hits,
+ def: super::ToolDef {
+ name: "probe".into(),
+ description: "runtime-local replay probe".into(),
+ input_schema: serde_json::json!({
+ "type": "object",
+ "additionalProperties": false,
+ }),
+ read_only: false,
+ destructive: false,
+ idempotent: true,
+ open_world: false,
+ },
+ }));
+ registry.register_recording_tools();
+ let registry = Arc::new(registry);
+ registry.init_self_weak();
+ registry
+ }
+
+ #[tokio::test]
+ async fn replay_dispatches_only_through_the_owning_registry() {
+ let hits_a = Arc::new(AtomicUsize::new(0));
+ let hits_b = Arc::new(AtomicUsize::new(0));
+ let registry_a = replay_registry(hits_a.clone());
+ let registry_b = replay_registry(hits_b.clone());
+ let context_b = standard_context();
+ let trajectory = tempfile::tempdir().unwrap();
+ let turn = trajectory.path().join("turn-00001");
+ std::fs::create_dir(&turn).unwrap();
+ std::fs::write(
+ turn.join("action.json"),
+ serde_json::json!({"tool": "probe", "arguments": {}}).to_string(),
+ )
+ .unwrap();
+
+ let result = registry_b
+ .invoke_with_context(
+ "replay_trajectory",
+ serde_json::json!({"dir": trajectory.path(), "delay_ms": 0}),
+ context_b,
+ )
+ .await;
+ assert_ne!(result.is_error, Some(true));
+ assert_eq!(result.structured_content.unwrap()["succeeded"], 1);
+ assert_eq!(hits_a.load(Ordering::SeqCst), 0);
+ assert_eq!(hits_b.load(Ordering::SeqCst), 1);
+
+ drop(registry_a);
+ drop(registry_b);
+ }
+
+ #[tokio::test]
+ async fn element_tokens_are_bound_to_the_dispatch_runtime_generation() {
+ let pid = 8_675_309;
+ let token = DISPATCH_RUNTIME_SCOPE
+ .scope("runtime-a".to_owned(), async {
+ let snapshot = crate::element_token::global().register_snapshot(pid, 44, 1);
+ crate::element_token::token_for(snapshot, 0)
+ })
+ .await;
+
+ let cross_runtime = DISPATCH_RUNTIME_SCOPE
+ .scope("runtime-b".to_owned(), async {
+ crate::element_token::global().resolve(pid, &token)
+ })
+ .await;
+ assert_eq!(
+ cross_runtime.unwrap_err(),
+ "element_token belongs to another runtime generation"
+ );
+ let structured = DISPATCH_RUNTIME_SCOPE
+ .scope("runtime-b".to_owned(), async {
+ crate::element_token::resolve_element_args(pid, None, Some(&token), None, "click")
+ .unwrap_err()
+ })
+ .await
+ .structured_content
+ .unwrap();
+ assert_eq!(
+ structured.pointer("/refusal/code"),
+ Some(&serde_json::Value::String("generation_mismatch".into()))
+ );
+
+ let owner = DISPATCH_RUNTIME_SCOPE
+ .scope("runtime-a".to_owned(), async {
+ crate::element_token::global().resolve(pid, &token)
+ })
+ .await;
+ assert_eq!(owner.unwrap(), (44, 0));
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+ async fn physical_desktop_actions_are_admitted_one_at_a_time() {
+ let active = Arc::new(AtomicUsize::new(0));
+ let max_active = Arc::new(AtomicUsize::new(0));
+ let mut tasks = Vec::new();
+ for _ in 0..8 {
+ let active = active.clone();
+ let max_active = max_active.clone();
+ tasks.push(tokio::spawn(async move {
+ let _admission = desktop_action_coordinator().lock().await;
+ let now = active.fetch_add(1, Ordering::SeqCst) + 1;
+ max_active.fetch_max(now, Ordering::SeqCst);
+ tokio::task::yield_now().await;
+ active.fetch_sub(1, Ordering::SeqCst);
+ }));
+ }
+ for task in tasks {
+ task.await.unwrap();
+ }
+ assert_eq!(max_active.load(Ordering::SeqCst), 1);
+ }
+
+ #[test]
+ fn runtime_namespaces_sessions_and_explicit_cursor_ids_without_leaking_them() {
+ let context = standard_context();
+ let mut args = serde_json::json!({
+ "session": "shared-session",
+ "_session_id": "shared-session",
+ "cursor_id": "shared-cursor",
+ });
+ let prefix = namespace_runtime_args(&mut args, context.as_ref());
+ assert_eq!(args["session"], format!("{prefix}shared-session"));
+ assert_eq!(args["_session_id"], format!("{prefix}shared-session"));
+ assert_eq!(args["cursor_id"], format!("{prefix}shared-cursor"));
+
+ let mut result = ToolResult::text(format!("{prefix}shared-session")).with_structured(
+ serde_json::json!({
+ format!("{prefix}shared-session"): {
+ "cursor_id": format!("{prefix}shared-cursor"),
+ }
+ }),
+ );
+ restore_public_runtime_result(&mut result, &prefix);
+ assert!(matches!(
+ &result.content[0],
+ crate::protocol::Content::Text { text, .. } if text == "shared-session"
+ ));
+ assert_eq!(
+ result
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.pointer("/shared-session/cursor_id"))
+ .and_then(serde_json::Value::as_str),
+ Some("shared-cursor")
+ );
+ }
+
+ #[test]
+ fn runtime_namespace_restoration_refuses_duplicate_public_object_keys() {
+ let context = standard_context();
+ let mut args = serde_json::json!({"session": "shared-session"});
+ let prefix = namespace_runtime_args(&mut args, context.as_ref());
+ let mut result = ToolResult::text("ambiguous").with_structured(serde_json::json!({
+ "shared-session": "public",
+ format!("{prefix}shared-session"): "private",
+ }));
+
+ restore_public_runtime_result(&mut result, &prefix);
+
+ assert_eq!(result.is_error, Some(true));
+ assert_eq!(
+ result
+ .structured_content
+ .as_ref()
+ .and_then(|value| { value.get("code").and_then(serde_json::Value::as_str) }),
+ Some("runtime_output_key_collision")
+ );
+ }
+
+ #[test]
+ fn runtime_mints_a_private_ownership_key_for_direct_session_calls() {
+ let context = standard_context();
+ let mut args = serde_json::json!({"session": "direct-session"});
+ let prefix = namespace_runtime_args(&mut args, context.as_ref());
+ assert_eq!(args["session"], format!("{prefix}direct-session"));
+ assert_eq!(args["_session_id"], format!("{prefix}direct-session"));
+ }
+
+ #[test]
+ fn anonymous_default_identity_keeps_its_legacy_process_scope() {
+ let context = standard_context();
+ let mut args = serde_json::json!({
+ "session": "default",
+ "_session_id": "default",
+ "cursor_id": "default",
+ });
+ namespace_runtime_args(&mut args, context.as_ref());
+ assert_eq!(args["session"], "default");
+ assert_eq!(args["_session_id"], "default");
+ assert_eq!(args["cursor_id"], "default");
+ }
+}
+
fn permission_denied_result(message: String) -> ToolResult {
ToolResult::error(message.clone()).with_structured(serde_json::json!({
"status": "refused",
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
index fe56c6041b..fa61b3e1a0 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
@@ -1121,6 +1121,7 @@ impl Drop for OperationGuard {
/// statically linked into the same distribution.
pub(crate) struct NativeAbiDriver {
handle: Mutex<*mut ffi::Handle>,
+ runtime_scope_key: String,
}
pub(crate) struct NativeAbiSession {
@@ -1146,16 +1147,27 @@ impl NativeAbiDriver {
let status =
unsafe { ffi::create(options.as_ptr(), options.len(), &mut handle, &mut error) };
status_result(status, &mut error, "create embedded runtime")?;
+ let runtime_scope_key = unsafe {
+ handle
+ .cast::<CuaDriverHandle>()
+ .as_ref()
+ .expect("successful ABI creation returns a non-null handle")
+ .runtime
+ .runtime_scope_key()
+ };
Ok(Self {
handle: Mutex::new(handle),
+ runtime_scope_key,
})
}
pub(crate) fn create_for_host(options: RuntimeOptions) -> Result<Self, DriverError> {
let runtime = DriverRuntime::create(options).map_err(map_runtime_create_error)?;
+ let runtime_scope_key = runtime.runtime_scope_key();
let handle = Box::into_raw(Box::new(CuaDriverHandle { runtime })).cast::<ffi::Handle>();
Ok(Self {
handle: Mutex::new(handle),
+ runtime_scope_key,
})
}
@@ -1187,6 +1199,10 @@ impl NativeAbiDriver {
*self.handle.lock().unwrap()
}
+ pub(crate) fn runtime_scope_key(&self) -> &str {
+ &self.runtime_scope_key
+ }
+
pub(crate) fn is_available(&self) -> bool {
let mut available = false;
let mut error = CuaDriverBuffer::empty();
@@ -1559,6 +1575,32 @@ mod tests {
assert!(handle.is_null());
}
+ #[test]
+ fn abi_can_own_two_runtime_handles_concurrently() {
+ let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
+ let mut first = ptr::null_mut();
+ let mut second = ptr::null_mut();
+ let mut first_error = CuaDriverBuffer::empty();
+ let mut second_error = CuaDriverBuffer::empty();
+ assert_eq!(
+ unsafe { cua_driver_create_v1(ptr::null(), 0, &mut first, &mut first_error) },
+ CuaDriverStatus::Ok
+ );
+ assert_eq!(
+ unsafe { cua_driver_create_v1(ptr::null(), 0, &mut second, &mut second_error) },
+ CuaDriverStatus::Ok
+ );
+ assert!(!first.is_null());
+ assert!(!second.is_null());
+ assert_ne!(first, second);
+ unsafe {
+ cua_driver_destroy_v1(&mut first);
+ cua_driver_destroy_v1(&mut second);
+ }
+ assert!(first.is_null());
+ assert!(second.is_null());
+ }
+
#[tokio::test]
async fn cancellation_completes_once_and_release_is_idempotent() {
let (sender, receiver) = oneshot::channel();
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs
index f8af40daf9..32b1c6c710 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs
@@ -572,6 +572,18 @@ desktop_tool_methods!(define_exported_tool_names);
#[uniffi::export]
impl CuaDriver {
+ #[doc(hidden)]
+ pub fn runtime_scope_prefix(&self) -> Option<String> {
+ match &self.backend {
+ DriverBackend::Embedded(native) => {
+ Some(format!("__cua_runtime_{}:", native.runtime_scope_key()))
+ }
+ DriverBackend::Daemon(_)
+ | DriverBackend::PrivateWorker(_)
+ | DriverBackend::Remote(_) => None,
+ }
+ }
+
/// Create a same-process driver runtime. This constructor never launches
/// `cua-driver` and never opens daemon IPC.
#[uniffi::constructor]
@@ -1657,38 +1669,218 @@ mod tests {
}
#[tokio::test]
- async fn direct_runtime_is_process_exclusive_and_reusable_after_shutdown() {
+ async fn direct_runtimes_have_independent_sessions_and_shutdown() {
let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
- let first = CuaDriver::create(None).unwrap();
- assert!(matches!(
- CuaDriver::create(None),
- Err(DriverError::RuntimeAlreadyExists)
- ));
- first.shutdown().await.unwrap();
- let replacement = configured_standard_driver();
- let replacement_session = replacement
+ let hook_baseline = cua_driver_core::session::session_end_hook_count();
+ let first = configured_standard_driver();
+ let second = CuaDriver::create_configured(ConfiguredDriverOptions {
+ claude_code_compatibility: false,
+ authorization: RuntimeAuthorizationOptions {
+ allowed_modes: vec![
+ SessionPermissionMode::Standard,
+ SessionPermissionMode::Unrestricted,
+ ],
+ compatibility_mode: SessionPermissionMode::Standard,
+ compatibility_bounded_manifest_path: None,
+ unrestricted_acknowledged: true,
+ max_session_ttl_seconds: 60,
+ max_idle_ttl_seconds: 30,
+ },
+ })
+ .unwrap();
+ let first_session = first
.create_trusted_session(TrustedSessionOptions {
- public_session: "replacement-after-stale-runtime".into(),
+ public_session: "same-public-label".into(),
mode: SessionPermissionMode::Standard,
ttl_seconds: 60,
idle_ttl_seconds: 30,
bounded_manifest_path: None,
})
.unwrap();
+ let second_session = second
+ .create_trusted_session(TrustedSessionOptions {
+ public_session: "same-public-label".into(),
+ mode: SessionPermissionMode::Unrestricted,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ })
+ .unwrap();
- // Dropping the already-shut-down generation must not revoke sessions
- // owned by the replacement runtime.
+ let first_started = first_session
+ .call_tool(
+ "start_session".into(),
+ serde_json::json!({
+ "session": "same-public-label",
+ "capture_scope": "auto"
+ })
+ .to_string(),
+ )
+ .await
+ .unwrap();
+ let second_started = second_session
+ .call_tool(
+ "start_session".into(),
+ serde_json::json!({
+ "session": "same-public-label",
+ "capture_scope": "window"
+ })
+ .to_string(),
+ )
+ .await
+ .unwrap();
+ assert!(first_started.text.contains("'same-public-label'"));
+ assert!(second_started.text.contains("'same-public-label'"));
+ assert!(!first_started.text.contains("__cua_runtime_"));
+ assert!(!second_started.text.contains("__cua_runtime_"));
+ assert!(
+ !cua_driver_core::session::has_session_activity("same-public-label"),
+ "transport-visible labels must never become process-global activity keys"
+ );
+
+ if std::env::var("CUA_REQUIRE_GUI").as_deref() == Ok("1") {
+ for session in [&first_session, &second_session] {
+ let windows = session
+ .call_tool("list_windows".into(), "{}".into())
+ .await
+ .unwrap();
+ assert!(
+ !windows.is_error,
+ "direct runtime could not inspect the GUI: {}",
+ windows.text
+ );
+ }
+ }
+
+ let second_recording_dir = tempfile::tempdir().unwrap();
+ let recording_started = second_session
+ .call_tool(
+ "start_recording".into(),
+ serde_json::json!({
+ "session": "same-public-label",
+ "output_dir": second_recording_dir.path(),
+ "record_video": false
+ })
+ .to_string(),
+ )
+ .await
+ .unwrap();
+ assert!(!recording_started.is_error);
+
+ first_session
+ .call_tool(
+ "end_session".into(),
+ serde_json::json!({"session": "same-public-label"}).to_string(),
+ )
+ .await
+ .unwrap();
+ first.shutdown().await.unwrap();
drop(first);
- let result = replacement_session
+
+ let second_state = second_session
+ .call_tool(
+ "get_session_state".into(),
+ serde_json::json!({"session": "same-public-label"}).to_string(),
+ )
+ .await
+ .unwrap();
+ assert!(!second_state.is_error);
+ let structured: Value =
+ serde_json::from_str(second_state.structured_json.as_deref().unwrap()).unwrap();
+ assert_eq!(structured["session"], "same-public-label");
+ assert_eq!(structured["capture_scope"], "window");
+ let recording_state = second_session
+ .call_tool(
+ "get_recording_state".into(),
+ serde_json::json!({"session": "same-public-label"}).to_string(),
+ )
+ .await
+ .unwrap();
+ let recording: Value =
+ serde_json::from_str(recording_state.structured_json.as_deref().unwrap()).unwrap();
+ assert_eq!(recording["enabled"], true);
+ if std::env::var("CUA_REQUIRE_GUI").as_deref() == Ok("1") {
+ let windows_after_other_shutdown = second_session
+ .call_tool("list_windows".into(), "{}".into())
+ .await
+ .unwrap();
+ assert!(
+ !windows_after_other_shutdown.is_error,
+ "runtime B lost GUI access after runtime A shut down: {}",
+ windows_after_other_shutdown.text
+ );
+ }
+
+ second_session
+ .call_tool(
+ "stop_recording".into(),
+ serde_json::json!({"session": "same-public-label"}).to_string(),
+ )
+ .await
+ .unwrap();
+
+ second_session.close();
+ second.shutdown().await.unwrap();
+ drop(first_session);
+ drop(second_session);
+ drop(second);
+ assert_eq!(
+ cua_driver_core::session::session_end_hook_count(),
+ hook_baseline
+ );
+ }
+
+ #[tokio::test]
+ async fn authorization_expiry_in_one_runtime_does_not_affect_another() {
+ let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
+ let expiring = CuaDriver::create_configured(ConfiguredDriverOptions {
+ claude_code_compatibility: false,
+ authorization: RuntimeAuthorizationOptions {
+ allowed_modes: vec![SessionPermissionMode::Standard],
+ compatibility_mode: SessionPermissionMode::Standard,
+ compatibility_bounded_manifest_path: None,
+ unrestricted_acknowledged: false,
+ max_session_ttl_seconds: 2,
+ max_idle_ttl_seconds: 2,
+ },
+ })
+ .unwrap();
+ let stable = configured_standard_driver();
+ let expiring_session = expiring
+ .create_trusted_session(TrustedSessionOptions {
+ public_session: "expiry-isolation".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 1,
+ idle_ttl_seconds: 1,
+ bounded_manifest_path: None,
+ })
+ .unwrap();
+ let stable_session = stable
+ .create_trusted_session(TrustedSessionOptions {
+ public_session: "expiry-isolation".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ })
+ .unwrap();
+
+ tokio::time::sleep(std::time::Duration::from_millis(1_100)).await;
+ let expired = expiring_session
.call_tool("health_report".into(), "{}".into())
.await
.unwrap();
- assert_ne!(result.error_code.as_deref(), Some("permission_denied"));
+ assert_eq!(expired.error_code.as_deref(), Some("permission_denied"));
+ let live = stable_session
+ .call_tool("health_report".into(), "{}".into())
+ .await
+ .unwrap();
+ assert_ne!(live.error_code.as_deref(), Some("permission_denied"));
- replacement_session.close();
- replacement.shutdown().await.unwrap();
- let after_drop = CuaDriver::create(None).unwrap();
- after_drop.shutdown().await.unwrap();
+ stable_session.close();
+ expiring_session.close();
+ stable.shutdown().await.unwrap();
+ expiring.shutdown().await.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
index b16a489cfa..c8058f13ee 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs
@@ -24,12 +24,12 @@ use std::sync::{
const RECORDING_IDLE_TTL_SECS_DEFAULT: u64 = 300;
const SESSION_IDLE_TTL_SECS_DEFAULT: u64 = 300;
-static DIRECT_RUNTIME_ACTIVE: AtomicBool = AtomicBool::new(false);
#[cfg(test)]
pub(crate) static TEST_RUNTIME_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub(crate) enum RuntimeCreateError {
+ #[allow(dead_code)]
#[error(
"runtime_already_exists: one direct Cua Driver runtime is already active in this process"
)]
@@ -41,33 +41,6 @@ pub(crate) enum RuntimeCreateError {
Unavailable(String),
}
-struct RuntimeOwnershipGuard {
- released: AtomicBool,
-}
-
-impl RuntimeOwnershipGuard {
- fn acquire() -> Result<Self, RuntimeCreateError> {
- DIRECT_RUNTIME_ACTIVE
- .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
- .map_err(|_| RuntimeCreateError::AlreadyExists)?;
- Ok(Self {
- released: AtomicBool::new(false),
- })
- }
-
- fn release(&self) {
- if !self.released.swap(true, Ordering::AcqRel) {
- DIRECT_RUNTIME_ACTIVE.store(false, Ordering::Release);
- }
- }
-}
-
-impl Drop for RuntimeOwnershipGuard {
- fn drop(&mut self) {
- self.release();
- }
-}
-
#[derive(Debug, Clone)]
pub(crate) struct RuntimeOptions {
pub cursor: CursorConfig,
@@ -181,7 +154,6 @@ pub(crate) struct DriverRuntime {
registry: Arc<ToolRegistry>,
authorization_registry: Arc<SessionAuthorizationRegistry>,
compatibility_context: Arc<EffectiveAuthorizationContext>,
- ownership: RuntimeOwnershipGuard,
shutdown: AtomicBool,
last_activity: AtomicU64,
/// Calls hold a read guard; shutdown takes the write guard after closing
@@ -211,15 +183,15 @@ impl DriverRuntime {
.legacy_context()
.map_err(RuntimeCreateError::Authorization)?,
};
- let ownership = RuntimeOwnershipGuard::acquire()?;
- let registry = Arc::new(build_registry(&options));
+ let registry = Arc::new(cua_driver_core::tool::with_runtime_scope(
+ compatibility_context.runtime_scope_key(),
+ || build_registry(&options),
+ ));
registry.init_self_weak();
- register_recording_session_end_hook(&registry);
let runtime = Arc::new(Self {
registry,
authorization_registry,
compatibility_context,
- ownership,
shutdown: AtomicBool::new(false),
last_activity: AtomicU64::new(now_unix_secs()),
lifecycle: tokio::sync::RwLock::new(()),
@@ -232,14 +204,24 @@ impl DriverRuntime {
!self.shutdown.load(Ordering::Acquire)
}
+ pub(crate) fn runtime_scope_key(&self) -> String {
+ self.compatibility_context.runtime_scope_key()
+ }
+
pub(crate) async fn shutdown(&self) {
self.shutdown.store(true, Ordering::Release);
let _drained = self.lifecycle.write().await;
self.authorization_registry.revoke_all();
- cua_driver_core::session::revoke_all_sessions();
+ let runtime_prefix = format!(
+ "__cua_runtime_{}:",
+ self.compatibility_context.runtime_scope_key()
+ );
+ cua_driver_core::session::revoke_sessions_with_prefix(&runtime_prefix);
+ cua_driver_core::session::forget_ended_sessions_with_prefix(&runtime_prefix);
+ cua_driver_core::element_token::global()
+ .clear_runtime_scope(&self.compatibility_context.runtime_scope_key());
let recording = self.registry.recording.clone();
let _ = tokio::task::spawn_blocking(move || recording.stop_owner(None)).await;
- self.ownership.release();
}
pub(crate) fn tools_list(&self) -> Option<Value> {
@@ -269,7 +251,7 @@ impl DriverRuntime {
.then(|| {
args.get("session")
.and_then(Value::as_str)
- .map(str::to_owned)
+ .map(|session| context.runtime_session_key(session))
})
.flatten();
let result = self.registry.invoke_with_context(name, args, context).await;
@@ -315,16 +297,18 @@ impl Drop for DriverRuntime {
fn drop(&mut self) {
self.shutdown.store(true, Ordering::Release);
self.authorization_registry.revoke_all();
- // Explicit `shutdown()` drains work, finalizes recordings, and clears
- // compatibility sessions. Drop can happen later than shutdown in
- // garbage-collected bindings, after a replacement runtime has already
- // acquired process ownership. It must therefore stay runtime-scoped
- // and non-blocking rather than touching process-global session state.
+ let runtime_scope = self.compatibility_context.runtime_scope_key();
+ let runtime_prefix = format!("__cua_runtime_{runtime_scope}:");
+ cua_driver_core::session::revoke_sessions_with_prefix(&runtime_prefix);
+ cua_driver_core::session::forget_ended_sessions_with_prefix(&runtime_prefix);
+ cua_driver_core::element_token::global().clear_runtime_scope(&runtime_scope);
+ // Explicit `shutdown()` drains work and finalizes recordings. Drop is
+ // runtime-scoped and non-blocking so a retained binding cannot affect
+ // another generation.
let recording = self.registry.recording.clone();
std::thread::spawn(move || {
let _ = recording.stop_owner(None);
});
- self.ownership.release();
}
}
@@ -371,11 +355,17 @@ fn spawn_lifecycle_maintenance(runtime: &Arc<DriverRuntime>) {
if !runtime.is_running() {
break;
}
- let ended = cua_driver_core::session::evict_idle(session_ttl);
+ let ended = cua_driver_core::session::evict_idle_with_prefix(
+ session_ttl,
+ &format!(
+ "__cua_runtime_{}:",
+ runtime.compatibility_context.runtime_scope_key()
+ ),
+ );
if !ended.is_empty() {
tracing::info!(
count = ended.len(),
- "idle-TTL reclaimed sessions: {ended:?}"
+ "idle-TTL reclaimed runtime-owned sessions"
);
}
let idle = now_unix_secs().saturating_sub(runtime.last_activity.load(Ordering::Relaxed));
@@ -386,19 +376,6 @@ fn spawn_lifecycle_maintenance(runtime: &Arc<DriverRuntime>) {
});
}
-fn register_recording_session_end_hook(registry: &Arc<ToolRegistry>) {
- let recording = Arc::downgrade(&registry.recording);
- cua_driver_core::session::register_session_end_hook(move |session| {
- let Some(recording) = recording.upgrade() else {
- return;
- };
- let session = session.to_owned();
- std::thread::spawn(move || {
- let _ = recording.stop_owner(Some(&session));
- });
- });
-}
-
/// Build the canonical SDK tool inventory without acquiring runtime ownership.
///
/// This metadata-only path cannot dispatch actions and therefore remains
@@ -448,6 +425,18 @@ fn build_registry(options: &RuntimeOptions) -> ToolRegistry {
if let Some(register_host_tools) = options.register_host_tools {
register_host_tools(&mut registry);
}
+ let recording = Arc::downgrade(&registry.recording);
+ let recording_session_end =
+ cua_driver_core::session::register_scoped_session_end_hook(move |session| {
+ let Some(recording) = recording.upgrade() else {
+ return;
+ };
+ let session = session.to_owned();
+ std::thread::spawn(move || {
+ let _ = recording.stop_owner(Some(&session));
+ });
+ });
+ registry.retain_session_end_hook(recording_session_end);
registry
}
@@ -531,3 +520,113 @@ fn configure_linux_runtime(prepare_desktop_environment: bool) {
));
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::Duration;
+
+ fn standard_options() -> RuntimeOptions {
+ let ceiling = SessionModeCeiling::for_trusted_sessions(
+ [PermissionMode::Standard],
+ false,
+ Duration::from_secs(60),
+ Duration::from_secs(30),
+ )
+ .unwrap();
+ RuntimeOptions::embedded_with_ceiling(false, ceiling, PermissionMode::Standard, None)
+ }
+
+ #[tokio::test]
+ async fn authorized_dispatch_refreshes_only_the_runtime_private_activity_key() {
+ let _runtime_test = TEST_RUNTIME_LOCK.lock().unwrap();
+ let runtime = DriverRuntime::create(standard_options()).unwrap();
+ let public = "runtime-activity-refresh";
+ let internal = runtime.compatibility_context.runtime_session_key(public);
+ let prefix = format!(
+ "__cua_runtime_{}:",
+ runtime.compatibility_context.runtime_scope_key()
+ );
+
+ runtime
+ .invoke(
+ "start_session",
+ serde_json::json!({"session": public, "capture_scope": "auto"}),
+ )
+ .await
+ .unwrap();
+ assert!(cua_driver_core::session::has_session_activity(&internal));
+ assert!(!cua_driver_core::session::has_session_activity(public));
+
+ std::thread::sleep(Duration::from_millis(20));
+ let idle_before_refresh =
+ cua_driver_core::session::session_idle_duration(&internal).unwrap();
+ runtime
+ .invoke("health_report", serde_json::json!({"session": public}))
+ .await
+ .unwrap();
+ let idle_after_refresh =
+ cua_driver_core::session::session_idle_duration(&internal).unwrap();
+ assert!(
+ idle_after_refresh < idle_before_refresh,
+ "authorized traffic must reset the private idle clock: before={idle_before_refresh:?} after={idle_after_refresh:?} ended={}",
+ cua_driver_core::session::is_session_ended(&internal)
+ );
+ let evicted =
+ cua_driver_core::session::evict_idle_with_prefix(idle_before_refresh, &prefix);
+ assert!(
+ !evicted.contains(&internal),
+ "continuous authorized traffic must refresh the private idle clock"
+ );
+
+ runtime.shutdown().await;
+ }
+
+ #[tokio::test]
+ async fn idle_eviction_finalizes_the_owning_runtime_recording() {
+ let _runtime_test = TEST_RUNTIME_LOCK.lock().unwrap();
+ let runtime = DriverRuntime::create(standard_options()).unwrap();
+ let public = "runtime-recording-idle";
+ let internal = runtime.compatibility_context.runtime_session_key(public);
+ let prefix = format!(
+ "__cua_runtime_{}:",
+ runtime.compatibility_context.runtime_scope_key()
+ );
+ runtime
+ .invoke(
+ "start_session",
+ serde_json::json!({"session": public, "capture_scope": "auto"}),
+ )
+ .await
+ .unwrap();
+ let output = tempfile::tempdir().unwrap();
+ let started = runtime
+ .invoke(
+ "start_recording",
+ serde_json::json!({
+ "session": public,
+ "output_dir": output.path(),
+ "record_video": false,
+ }),
+ )
+ .await
+ .unwrap();
+ assert_ne!(started.is_error, Some(true));
+ assert!(runtime.registry.recording.current_state().enabled);
+
+ let evicted = cua_driver_core::session::evict_idle_with_prefix(Duration::ZERO, &prefix);
+ assert!(evicted.contains(&internal));
+ for _ in 0..100 {
+ if !runtime.registry.recording.current_state().enabled {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ assert!(
+ !runtime.registry.recording.current_state().enabled,
+ "session-end hook must finalize recording after idle eviction"
+ );
+
+ runtime.shutdown().await;
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/daemon.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/daemon.rs
index 1ba512b4ce..4f8d07e297 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/daemon.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/daemon.rs
@@ -23,6 +23,23 @@ impl TestDaemon {
binary: &Path,
reaper: &mut ChildReaper,
env: &[(&str, &str)],
+ ) -> Option<Self> {
+ Self::spawn_configured(binary, reaper, env, false)
+ }
+
+ pub(crate) fn spawn_with_overlay(
+ binary: &Path,
+ reaper: &mut ChildReaper,
+ env: &[(&str, &str)],
+ ) -> Option<Self> {
+ Self::spawn_configured(binary, reaper, env, true)
+ }
+
+ fn spawn_configured(
+ binary: &Path,
+ reaper: &mut ChildReaper,
+ env: &[(&str, &str)],
+ overlay_enabled: bool,
) -> Option<Self> {
#[cfg(not(unix))]
let sequence = DAEMON_SEQUENCE.fetch_add(1, Ordering::Relaxed);
@@ -57,17 +74,14 @@ impl TestDaemon {
};
let mut command = Command::new(binary);
command
- .args([
- "serve",
- "--socket",
- &socket,
- "--no-permissions-gate",
- "--no-overlay",
- ])
+ .args(["serve", "--socket", &socket, "--no-permissions-gate"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(stderr)
.env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false");
+ if !overlay_enabled {
+ command.arg("--no-overlay");
+ }
for (key, value) in env {
command.env(key, value);
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs
index 6bce1b81f3..1a45829153 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs
@@ -31,13 +31,28 @@ impl RawDriver {
/// if the binary isn't built — callers early-return so an un-built binary
/// skips rather than fails.
pub fn spawn() -> Option<Self> {
+ Self::spawn_daemon_backed(false)
+ }
+
+ /// Spawn a daemon-backed raw driver with the certified platform overlay
+ /// host enabled. Cursor protocol tests use this deliberately; ordinary
+ /// protocol tests keep the no-overlay daemon so they remain headless.
+ pub fn spawn_with_overlay() -> Option<Self> {
+ Self::spawn_daemon_backed(true)
+ }
+
+ fn spawn_daemon_backed(overlay_enabled: bool) -> Option<Self> {
let bin = driver_binary();
if !bin.exists() {
eprintln!("[testkit] driver binary not built at {bin:?} — skipping");
return None;
}
let mut reaper = ChildReaper::new();
- let daemon = TestDaemon::spawn(&bin, &mut reaper, &[])?;
+ let daemon = if overlay_enabled {
+ TestDaemon::spawn_with_overlay(&bin, &mut reaper, &[])?
+ } else {
+ TestDaemon::spawn(&bin, &mut reaper, &[])?
+ };
let mut command = Command::new(&bin);
command
.args(["mcp", "--socket", &daemon.socket])
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
index 25b3195f0e..38d79235cb 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
@@ -22,9 +22,7 @@ use std::net::SocketAddr;
use std::sync::Arc;
use cua_driver_core::protocol::{Request, Response};
-use cua_driver_core::server::{
- handle_request, session_tool_context, tool_observation_timer, StdioExecutionPath,
-};
+use cua_driver_core::server::{handle_request, tool_observation_timer, StdioExecutionPath};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tracing::{debug, info, warn};
@@ -143,11 +141,14 @@ async fn dispatch(body: &[u8], sdk: &Arc<crate::sdk_adapter::SdkAdapter>) -> Opt
};
req.id.as_ref()?;
let initialize_metadata = req.initialize_metadata();
- let session_context = session_tool_context(
- &req,
- |name| sdk.is_known_tool(name),
- cua_driver_core::session::SessionTransport::McpHttp,
- );
+ let session_context = req.tool_call().ok().and_then(|call| {
+ sdk.begin_tool_call(
+ &call.name,
+ &call.args,
+ cua_driver_core::session::SessionTransport::McpHttp,
+ cua_driver_core::session::SessionClientKind::Mcp,
+ )
+ });
let id = req.id.clone().unwrap_or(serde_json::Value::Null);
apply_session_identity(&mut req);
let timer = http_tool_observation_timer(&req, |name| sdk.is_known_tool(name));
@@ -182,10 +183,9 @@ fn serialize(resp: &Response) -> String {
}
/// Mirror an explicit `session` arg into `_session_id` (the per-session config /
-/// recording key) and refresh its idle-TTL — the HTTP-side equivalent of
-/// `serve.rs::apply_session_identity`. The agent cursor reads `session` directly
-/// (so it already works); this keeps config + recording session-scoping
-/// consistent across transports.
+/// recording key) — the HTTP-side equivalent of
+/// `serve.rs::apply_session_identity`. Runtime-private idle-TTL activity is
+/// refreshed later at the authorized registry boundary.
fn apply_session_identity(req: &mut Request) {
let Some(params) = req.params.as_mut() else {
return;
@@ -201,7 +201,6 @@ fn apply_session_identity(req: &mut Request) {
if let Some(sess) = session {
args.entry("_session_id")
.or_insert_with(|| serde_json::Value::String(sess.clone()));
- cua_driver_core::session::touch_session(&sess);
}
}
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 f2623bbcdd..093ab4d1f5 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
@@ -82,10 +82,9 @@ pub async fn run_direct(driver: Arc<cua_driver_sdk::CuaDriver>) -> anyhow::Resul
.map(|session| {
public_sessions.insert(session);
request.tool_call().ok().and_then(|call| {
- cua_driver_core::session::begin_tool_call(
+ sdk.begin_tool_call(
&call.name,
&call.args,
- sdk.is_known_tool(&call.name),
cua_driver_core::session::SessionTransport::McpStdio,
cua_driver_core::session::SessionClientKind::Mcp,
)
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
index a510270988..2b345bdc68 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
@@ -3,15 +3,56 @@
//! The daemon, MCP transports, and finite CLI inspection commands all consume
//! this adapter. Platform registries remain private to `cua-driver-sdk`.
-use std::sync::Arc;
+use std::{
+ collections::HashMap,
+ sync::{Arc, Mutex},
+};
-use cua_driver_core::server::ToolProvider;
+use cua_driver_core::{server::ToolProvider, CaptureScope};
use cua_driver_sdk::{CuaDriver, CuaDriverSession, TrustedSessionOptions};
use serde_json::{json, Value};
+#[derive(Default)]
+struct PublicSessionState {
+ scopes: HashMap<String, CaptureScope>,
+ ended: HashMap<String, u64>,
+ next_tombstone: u64,
+}
+
+impl PublicSessionState {
+ fn mark_ended(&mut self, session: &str) -> u64 {
+ self.next_tombstone = self.next_tombstone.wrapping_add(1).max(1);
+ let marker = self.next_tombstone;
+ self.ended.insert(session.to_owned(), marker);
+ marker
+ }
+
+ fn rollback_ended(&mut self, session: &str, marker: u64, previous: Option<u64>) {
+ if self.ended.get(session).copied() != Some(marker) {
+ return;
+ }
+ match previous {
+ Some(previous) => {
+ self.ended.insert(session.to_owned(), previous);
+ }
+ None => {
+ self.ended.remove(session);
+ }
+ }
+ }
+}
+
pub struct SdkAdapter {
driver: Arc<CuaDriver>,
tools_list: Value,
+ // Runtime-adapter-local mirror used only for the legacy socket's early
+ // resurrection refusal. Core owns the authoritative runtime-private
+ // tombstone; keeping this mirror on the adapter preserves the loud
+ // transport error without reintroducing process-global public session IDs.
+ public_sessions: Arc<Mutex<PublicSessionState>>,
+ runtime_prefix: String,
+ _session_end_hook: cua_driver_core::session::SessionEndHookRegistration,
+ session_lifecycle: tokio::sync::Mutex<()>,
}
impl SdkAdapter {
@@ -25,7 +66,32 @@ impl SdkAdapter {
if !tools_list.get("tools").is_some_and(Value::is_array) {
anyhow::bail!("SDK tool inventory omitted tools array");
}
- Ok(Arc::new(Self { driver, tools_list }))
+ let runtime_prefix = driver.runtime_scope_prefix().ok_or_else(|| {
+ anyhow::anyhow!("SDK adapter requires a directly owned embedded runtime")
+ })?;
+ let public_sessions = Arc::new(Mutex::new(PublicSessionState::default()));
+ let hook_sessions = public_sessions.clone();
+ let hook_prefix = runtime_prefix.clone();
+ let session_end_hook =
+ cua_driver_core::session::register_scoped_session_end_hook(move |session| {
+ let Some(public) = session.strip_prefix(&hook_prefix) else {
+ return;
+ };
+ if public.is_empty() || public == "default" {
+ return;
+ }
+ let mut sessions = hook_sessions.lock().unwrap();
+ sessions.scopes.entry(public.to_owned()).or_default();
+ sessions.mark_ended(public);
+ });
+ Ok(Arc::new(Self {
+ driver,
+ tools_list,
+ public_sessions,
+ runtime_prefix,
+ _session_end_hook: session_end_hook,
+ session_lifecycle: tokio::sync::Mutex::new(()),
+ }))
}
pub fn tools_list(&self) -> Value {
@@ -66,13 +132,136 @@ impl SdkAdapter {
}
pub async fn invoke_raw(&self, name: &str, arguments: Value) -> Result<Value, String> {
+ let _lifecycle = if matches!(name, "start_session" | "end_session") {
+ Some(self.session_lifecycle.lock().await)
+ } else {
+ None
+ };
+ let public_session = arguments
+ .get("session")
+ .and_then(Value::as_str)
+ .filter(|session| !session.is_empty() && *session != "default")
+ .map(str::to_owned);
+ let ending_session = (name == "end_session")
+ .then_some(public_session.as_deref())
+ .flatten();
+ if let Some(session) = &public_session {
+ self.public_sessions
+ .lock()
+ .unwrap()
+ .scopes
+ .entry(session.clone())
+ .or_default();
+ }
+ let ending_tombstone = ending_session.map(|session| {
+ // Mark before dispatch so a concurrently arriving legacy socket
+ // call cannot slip through after teardown has begun.
+ let mut sessions = self.public_sessions.lock().unwrap();
+ let previous = sessions.ended.get(session).copied();
+ let marker = sessions.mark_ended(session);
+ (session, marker, previous)
+ });
+
let result = self
.driver
.call_tool_from_trusted_adapter(name, arguments)
.await
- .map_err(|error| error.to_string())?;
- serde_json::from_str(&result.raw_json)
- .map_err(|error| format!("{name} returned invalid SDK result JSON: {error}"))
+ .map_err(|error| {
+ if let Some((session, marker, previous)) = ending_tombstone {
+ self.public_sessions
+ .lock()
+ .unwrap()
+ .rollback_ended(session, marker, previous);
+ }
+ error.to_string()
+ })?;
+ let value: Value = serde_json::from_str(&result.raw_json).map_err(|error| {
+ if let Some((session, marker, previous)) = ending_tombstone {
+ self.public_sessions
+ .lock()
+ .unwrap()
+ .rollback_ended(session, marker, previous);
+ }
+ format!("{name} returned invalid SDK result JSON: {error}")
+ })?;
+ let failed = value.get("isError").and_then(Value::as_bool) == Some(true);
+ if failed {
+ if let Some((session, marker, previous)) = ending_tombstone {
+ self.public_sessions
+ .lock()
+ .unwrap()
+ .rollback_ended(session, marker, previous);
+ }
+ } else if let Some(session) = public_session.as_deref() {
+ let capture_scope = value
+ .pointer("/structuredContent/capture_scope")
+ .cloned()
+ .and_then(|scope| serde_json::from_value(scope).ok());
+ let mut sessions = self.public_sessions.lock().unwrap();
+ if name == "start_session" {
+ sessions.ended.remove(session);
+ }
+ if let Some(capture_scope) = capture_scope {
+ sessions.scopes.insert(session.to_owned(), capture_scope);
+ }
+ }
+ Ok(value)
+ }
+
+ pub fn is_session_ended(&self, session: &str) -> bool {
+ self.public_sessions
+ .lock()
+ .unwrap()
+ .ended
+ .contains_key(session)
+ }
+
+ pub fn mark_all_sessions_ended(&self) {
+ let mut sessions = self.public_sessions.lock().unwrap();
+ let known = sessions.scopes.keys().cloned().collect::<Vec<_>>();
+ for session in known {
+ sessions.mark_ended(&session);
+ }
+ }
+
+ pub async fn revoke_all_sessions(&self) -> usize {
+ let _lifecycle = self.session_lifecycle.lock().await;
+ let count = cua_driver_core::session::revoke_sessions_with_prefix(&self.runtime_prefix);
+ self.mark_all_sessions_ended();
+ count
+ }
+
+ pub fn begin_tool_call(
+ &self,
+ name: &str,
+ arguments: &Value,
+ transport: cua_driver_core::session::SessionTransport,
+ client_kind: cua_driver_core::session::SessionClientKind,
+ ) -> Option<cua_driver_core::session::SessionToolContext> {
+ let observed_state = arguments
+ .get("session")
+ .and_then(Value::as_str)
+ .filter(|session| !session.is_empty() && *session != "default")
+ .map(|session| self.public_session_observation_state(session));
+ cua_driver_core::session::begin_tool_call_with_state(
+ name,
+ arguments,
+ self.is_known_tool(name),
+ transport,
+ client_kind,
+ observed_state,
+ )
+ }
+
+ fn public_session_observation_state(
+ &self,
+ session: &str,
+ ) -> cua_driver_core::session::SessionObservationState {
+ let sessions = self.public_sessions.lock().unwrap();
+ cua_driver_core::session::SessionObservationState {
+ ended: sessions.ended.contains_key(session),
+ capture_scope: sessions.scopes.get(session).copied().unwrap_or_default(),
+ }
}
pub async fn end_session(&self, session: &str) -> Result<(), String> {
@@ -143,6 +332,20 @@ impl ToolProvider for SdkAdapter {
mod tests {
use super::*;
+ fn host_driver() -> Arc<cua_driver_sdk::CuaDriver> {
+ cua_driver_sdk::CuaDriver::create_for_host(cua_driver_sdk::DriverHostOptions {
+ cursor: cursor_overlay::CursorConfig {
+ enabled: false,
+ ..cursor_overlay::CursorConfig::default()
+ },
+ host_owns_permission_ux: false,
+ host_bundle_id: None,
+ claude_code_compatibility: false,
+ prepare_desktop_environment: false,
+ register_host_tools: None,
+ })
+ }
+
#[test]
fn daemon_shape_is_derived_from_canonical_mcp_inventory() {
let tools_list = json!({
@@ -175,4 +378,125 @@ mod tests {
);
assert_eq!(daemon["tool_observation_owner"], "daemon");
}
+
+ #[tokio::test]
+ async fn public_observation_mirror_tracks_scope_end_and_revival() {
+ let _runtime_guard = crate::test_runtime_lock().lock().await;
+ let sdk = SdkAdapter::load(host_driver()).await.expect("SDK adapter");
+ let session = "adapter-observation-scope";
+
+ let started = sdk
+ .invoke_raw(
+ "start_session",
+ json!({"session": session, "capture_scope": "window"}),
+ )
+ .await
+ .expect("start session");
+ assert_ne!(started["isError"], true);
+ assert_eq!(
+ sdk.public_session_observation_state(session),
+ cua_driver_core::session::SessionObservationState {
+ ended: false,
+ capture_scope: CaptureScope::Window,
+ }
+ );
+
+ sdk.end_session(session).await.expect("end session");
+ assert!(sdk.public_session_observation_state(session).ended);
+
+ sdk.invoke_raw(
+ "start_session",
+ json!({"session": session, "capture_scope": "window"}),
+ )
+ .await
+ .expect("revive session");
+ assert!(!sdk.public_session_observation_state(session).ended);
+
+ sdk.shutdown().await.expect("shutdown");
+ }
+
+ #[tokio::test]
+ async fn runtime_owned_end_hook_updates_only_its_adapter() {
+ let _runtime_guard = crate::test_runtime_lock().lock().await;
+ let first = SdkAdapter::load(host_driver())
+ .await
+ .expect("first SDK adapter");
+ let second = SdkAdapter::load(host_driver())
+ .await
+ .expect("second SDK adapter");
+ let session = "same-public-label";
+
+ for sdk in [&first, &second] {
+ sdk.invoke_raw(
+ "start_session",
+ json!({"session": session, "capture_scope": "auto"}),
+ )
+ .await
+ .expect("start same-label session");
+ }
+
+ let evicted = cua_driver_core::session::evict_idle_with_prefix(
+ std::time::Duration::ZERO,
+ &first.runtime_prefix,
+ );
+ assert_eq!(evicted, vec![format!("{}{session}", first.runtime_prefix)]);
+ assert!(first.public_session_observation_state(session).ended);
+ assert!(
+ !second.public_session_observation_state(session).ended,
+ "a private end hook must not tombstone another runtime's same public label"
+ );
+
+ first
+ .invoke_raw(
+ "start_session",
+ json!({"session": session, "capture_scope": "auto"}),
+ )
+ .await
+ .expect("revive first session");
+ assert_eq!(first.revoke_all_sessions().await, 1);
+ assert!(first.public_session_observation_state(session).ended);
+ assert!(
+ !second.public_session_observation_state(session).ended,
+ "bulk revoke must remain scoped to the owning runtime"
+ );
+
+ second
+ .invoke_raw(
+ "escalate_session",
+ json!({"session": session, "reason": "no_window_target"}),
+ )
+ .await
+ .expect("escalate second session");
+ assert_eq!(
+ second
+ .public_session_observation_state(session)
+ .capture_scope,
+ CaptureScope::Auto,
+ "capture policy remains auto while its effective scope escalates"
+ );
+
+ first.shutdown().await.expect("shutdown first");
+ second.shutdown().await.expect("shutdown second");
+ }
+
+ #[tokio::test]
+ async fn failed_end_preserves_an_existing_out_of_band_tombstone() {
+ let _runtime_guard = crate::test_runtime_lock().lock().await;
+ let sdk = SdkAdapter::load(host_driver()).await.expect("SDK adapter");
+ let session = "failed-end-preserves-tombstone";
+ sdk.invoke_raw(
+ "start_session",
+ json!({"session": session, "capture_scope": "auto"}),
+ )
+ .await
+ .expect("start session");
+
+ sdk.shutdown().await.expect("shutdown");
+ assert!(sdk.public_session_observation_state(session).ended);
+ assert!(sdk.end_session(session).await.is_err());
+ assert!(
+ sdk.public_session_observation_state(session).ended,
+ "a failed in-band end must not erase an out-of-band tombstone"
+ );
+ }
}
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 602f1f3450..b880b8d021 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -70,9 +70,9 @@ fn inject_browser_approvals(tool_name: &str, args: &mut serde_json::Value, sessi
/// reads the explicit `session`/`cursor_id` arg only, so a cursor appears
/// exactly when a run declares its session (explicit-required).
///
-/// Also refreshes the idle-TTL clock for an explicit session (the minted
-/// fallback is reaped by EOF, not TTL). Returns the effective `_session_id` for
-/// the resurrection guard.
+/// The registry refreshes the runtime-private idle-TTL key after authorization;
+/// this transport helper only returns the effective `_session_id` for the
+/// resurrection guard.
fn apply_session_identity(args: &mut serde_json::Value, minted: &Option<String>) -> Option<String> {
let explicit = args
.as_object()
@@ -93,9 +93,6 @@ fn apply_session_identity(args: &mut serde_json::Value, minted: &Option<String>)
);
}
}
- if let Some(sess) = &explicit {
- cua_driver_core::session::touch_session(sess);
- }
args.as_object()
.and_then(|o| o.get("_session_id"))
.and_then(|v| v.as_str())
@@ -251,8 +248,7 @@ async fn invoke_daemon_tool(
});
if let Some(sid) = &effective_session {
- if !is_session_lifecycle_tool(&tool_name) && cua_driver_core::session::is_session_ended(sid)
- {
+ if !is_session_lifecycle_tool(&tool_name) && sdk.is_session_ended(sid) {
observe_daemon_error(observation, 1);
return DaemonResponse::err(
format!(
@@ -317,7 +313,7 @@ async fn invoke_daemon_tool(
}
},
};
- cua_driver_core::session::begin_tool_call(&tool_name, &args, true, transport, client_kind)
+ sdk.begin_tool_call(&tool_name, &args, transport, client_kind)
});
let result_value = match sdk.invoke_raw(&tool_name, args).await {
@@ -664,7 +660,7 @@ pub async fn run_serve(
.and_then(serde_json::Value::as_str)
.filter(|value| !value.is_empty());
let result: Result<serde_json::Value, String> = if all && session.is_none() {
- let count = cua_driver_core::session::revoke_all_sessions();
+ let count = reg.revoke_all_sessions().await;
Ok(serde_json::json!({"revoked": count, "scope": "all"}))
} else if !all {
match session {
@@ -1295,7 +1291,7 @@ pub async fn run_serve(
.and_then(serde_json::Value::as_str)
.filter(|value| !value.is_empty());
let result: Result<serde_json::Value, String> = if all && session.is_none() {
- let count = cua_driver_core::session::revoke_all_sessions();
+ let count = reg.revoke_all_sessions().await;
Ok(serde_json::json!({"revoked": count, "scope": "all"}))
} else if !all {
match session {
@@ -1993,6 +1989,40 @@ mod gate_tests {
"revived-session call must invoke the tool again"
);
+ // 3d. Bulk revocation must update the adapter-local public tombstone
+ // mirror as well as the runtime-private core tracker.
+ let socket3d = socket.clone();
+ let revoke_all = DaemonRequest {
+ method: "revoke_authorization".into(),
+ name: None,
+ args: Some(serde_json::json!({"all": true})),
+ session_id: None,
+ observation_origin: None,
+ client_kind: None,
+ };
+ let resp = tokio::task::spawn_blocking(move || send_request(&socket3d, &revoke_all))
+ .await
+ .unwrap()
+ .expect("revoke-all response");
+ assert!(resp.ok, "revoke-all should ack ok");
+
+ let socket3e = socket.clone();
+ let s3e = sid.to_owned();
+ let resp =
+ tokio::task::spawn_blocking(move || send_request(&socket3e, &call_req(Some(&s3e))))
+ .await
+ .unwrap()
+ .expect("bulk-revoked call response");
+ assert!(
+ !resp.ok,
+ "bulk-revoked session call must preserve the loud legacy transport refusal"
+ );
+ assert_eq!(
+ PROBE_INVOCATIONS.load(Ordering::SeqCst),
+ 2,
+ "bulk-revoked session call must not invoke the tool"
+ );
+
// 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)))
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs
index ec8cc34288..7c063c2af6 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_media_test.rs
@@ -569,7 +569,9 @@ fn start_recording_record_video_flag_accepted() {
#[test]
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn replay_trajectory() {
- //! Write a minimal trajectory (one move_cursor turn), replay it, verify succeeded=1.
+ //! Write a minimal no-GUI trajectory, replay it, verify succeeded=1.
+ //! The test daemon deliberately starts with `--no-overlay`, so an
+ //! agent-cursor move would correctly refuse before exercising replay.
let Some(mut d) = RawDriver::spawn() else {
return;
};
@@ -580,7 +582,7 @@ fn replay_trajectory() {
std::fs::create_dir_all(&turn_dir).unwrap();
std::fs::write(
turn_dir.join("action.json"),
- r#"{"tool":"move_cursor","arguments":{"x":50.0,"y":60.0}}"#,
+ r#"{"tool":"start_session","arguments":{"session":"replay-protocol","capture_scope":"auto"}}"#,
)
.unwrap();
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs
index 0caba83f31..8044148555 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs
@@ -52,7 +52,7 @@ fn concurrent_clients_with_cursor_moves() {
//! This covers the multi-cursor use case where two Codex agents run simultaneously.
let mut drivers: Vec<RawDriver> = Vec::new();
for _ in 0..2 {
- let Some(d) = RawDriver::spawn() else {
+ let Some(d) = RawDriver::spawn_with_overlay() else {
return;
};
drivers.push(d);
@@ -102,10 +102,10 @@ fn concurrent_multi_driver_isolation() {
//! Two cua-driver processes running simultaneously with different cursor IDs.
//! Verifies that concurrent sessions don't interfere — each tracks its own
//! cursor state and the overlay stays alive under concurrent load.
- let Some(mut child_a) = RawDriver::spawn() else {
+ let Some(mut child_a) = RawDriver::spawn_with_overlay() else {
return;
};
- let Some(mut child_b) = RawDriver::spawn() else {
+ let Some(mut child_b) = RawDriver::spawn_with_overlay() else {
return;
};
@@ -215,7 +215,7 @@ fn concurrent_multi_driver_isolation() {
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn multi_cursor_instance_state() {
//! Two cursor instances can be created with different IDs; each has independent state.
- let Some(mut d) = RawDriver::spawn() else {
+ let Some(mut d) = RawDriver::spawn_with_overlay() else {
return;
};
@@ -352,7 +352,7 @@ fn overlay_move_cursor_stays_alive() {
//! sends commands via the global channel. Any crash in the render thread (e.g. wrong
//! GCD queue pointer, bad CGImage argument types) would cause this test to fail with
//! an early EOF or a non-zero exit code.
- let Some(mut d) = RawDriver::spawn() else {
+ let Some(mut d) = RawDriver::spawn_with_overlay() else {
return;
};
@@ -412,7 +412,7 @@ fn overlay_move_cursor_stays_alive() {
fn set_agent_cursor_motion_bezier_knobs() {
//! set_agent_cursor_motion with Bezier/timing knobs — verifies schema accepts them
//! and returns a non-error response with the updated values in the response text.
- let Some(mut d) = RawDriver::spawn() else {
+ let Some(mut d) = RawDriver::spawn_with_overlay() else {
return;
};
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs b/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
index 7d2b90bb04..563a784121 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
@@ -106,19 +106,24 @@ fn apply_msg(map: &mut RenderMap, msg: OverlayMsg) -> Option<CursorKey> {
}
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);
- *ARRIVAL_TX.lock().unwrap() = Some(HashMap::new());
- let mut cursors = HashMap::new();
- cursors.insert("default".to_owned(), RenderState::new(cfg.clone()));
- *RENDER.lock().unwrap() = Some(RenderMap {
- cursors,
- scr_w: 1920,
- scr_h: 1080,
- template: cfg,
- ended: HashSet::new(),
- last_active: None,
+ static INITIALIZED: OnceLock<()> = OnceLock::new();
+ INITIALIZED.get_or_init(|| {
+ let (tx, rx) = std::sync::mpsc::sync_channel(4096);
+ CMD_TX
+ .set(tx)
+ .expect("cursor overlay sender is initialized exactly once");
+ *CMD_RX_CELL.lock().unwrap() = Some(rx);
+ *ARRIVAL_TX.lock().unwrap() = Some(HashMap::new());
+ let mut cursors = HashMap::new();
+ cursors.insert("default".to_owned(), RenderState::new(cfg.clone()));
+ *RENDER.lock().unwrap() = Some(RenderMap {
+ cursors,
+ scr_w: 1920,
+ scr_h: 1080,
+ template: cfg,
+ ended: HashSet::new(),
+ last_active: None,
+ });
});
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
index fb790a9377..6fb4d9b6a3 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
@@ -6959,9 +6959,9 @@ impl Tool for BringToFrontTool {
pub fn build_registry(compat: bool) -> ToolRegistry {
let state = ToolState::new();
- {
+ let cursor_outcome_reader = {
let cursor_registry = state.cursor_registry.clone();
- let _ = cua_driver_core::session::set_cursor_outcome_reader(std::sync::Arc::new(
+ cua_driver_core::session::register_scoped_cursor_outcome_reader(std::sync::Arc::new(
move |session_id| {
let state = cursor_registry.get(session_id);
let motion_customized = state.is_some()
@@ -6994,12 +6994,12 @@ pub fn build_registry(compat: bool) -> ToolRegistry {
),
}
},
- ));
- }
- {
+ ))
+ };
+ let session_end_hook = {
let cursor_registry = state.cursor_registry.clone();
let state_for_session_end = state.clone();
- cua_driver_core::session::register_session_end_hook(move |session_id| {
+ cua_driver_core::session::register_scoped_session_end_hook(move |session_id| {
cursor_registry.remove(session_id);
crate::overlay::remove_cursor(session_id.to_owned());
state_for_session_end
@@ -7008,9 +7008,25 @@ pub fn build_registry(compat: bool) -> ToolRegistry {
.unwrap()
.remove(session_id);
crate::input::forget_master_pointer(session_id);
+ })
+ };
+ let mut r = ToolRegistry::new();
+ r.retain_cursor_outcome_reader(cursor_outcome_reader);
+ r.retain_session_end_hook(session_end_hook);
+ if let Some(runtime_scope) = cua_driver_core::tool::current_dispatch_runtime_scope() {
+ let prefix = format!("__cua_runtime_{runtime_scope}:");
+ let cursor_registry = state.cursor_registry.clone();
+ r.retain_runtime_cleanup(move || {
+ for cursor in cursor_registry
+ .all_states()
+ .into_iter()
+ .filter(|cursor| cursor.config.cursor_id.starts_with(&prefix))
+ {
+ cursor_registry.remove(&cursor.config.cursor_id);
+ crate::overlay::remove_cursor(cursor.config.cursor_id);
+ }
});
}
- let mut r = ToolRegistry::new();
r.register(Box::new(ListAppsTool));
r.register(Box::new(ListWindowsTool));
r.register(Box::new(GetWindowStateTool {
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 2edaea50be..59e8710f7b 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
@@ -157,19 +157,24 @@ fn apply_msg(map: &mut RenderMap, msg: OverlayMsg) -> Option<CursorKey> {
/// 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);
- *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,
- backing_scale: 1.0, // overwritten in run_appkit() once the NSScreen is known
- template: cfg,
- ended: std::collections::HashSet::new(),
+ static INITIALIZED: OnceLock<()> = OnceLock::new();
+ INITIALIZED.get_or_init(|| {
+ let (tx, rx) = std::sync::mpsc::sync_channel(4096);
+ CMD_TX
+ .set(tx)
+ .expect("cursor overlay sender is initialized exactly once");
+ *CMD_RX_CELL.lock().unwrap() = Some(rx);
+ *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,
+ backing_scale: 1.0, // overwritten in run_appkit() once the NSScreen is known
+ template: cfg,
+ ended: std::collections::HashSet::new(),
+ });
});
}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/recording_hooks.rs b/libs/cua-driver/rust/crates/platform-macos/src/recording_hooks.rs
index 09b635ec85..b1a28e7d85 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/recording_hooks.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/recording_hooks.rs
@@ -10,15 +10,25 @@
//! which lives in `ToolState`. `tools::register_all` shares the active cache
//! here via `set_element_cache` at startup.
-use std::sync::{Arc, OnceLock};
+use std::{
+ collections::HashMap,
+ sync::{Arc, Mutex, OnceLock, Weak},
+};
use crate::ax::bindings::{element_screen_center, AXUIElementRef};
use crate::ax::cache::ElementCache;
-static ELEMENT_CACHE: OnceLock<Arc<ElementCache>> = OnceLock::new();
+static ELEMENT_CACHES: OnceLock<Mutex<HashMap<String, Weak<ElementCache>>>> = OnceLock::new();
pub fn set_element_cache(cache: Arc<ElementCache>) {
- let _ = ELEMENT_CACHE.set(cache);
+ let runtime_scope =
+ cua_driver_core::tool::current_dispatch_runtime_scope().unwrap_or_else(|| "legacy".into());
+ let mut caches = ELEMENT_CACHES
+ .get_or_init(|| Mutex::new(HashMap::new()))
+ .lock()
+ .unwrap();
+ caches.retain(|_, cache| cache.strong_count() > 0);
+ caches.insert(runtime_scope, Arc::downgrade(&cache));
}
/// Build `app_state.json` bytes for the turn folder. Walks the AX tree for
@@ -50,7 +60,14 @@ pub fn app_state_json_for(window_id: Option<u64>, pid: Option<i64>) -> Option<Ve
/// by subtracting the window's screen origin and multiplying by the
/// screenshot's pixels-per-point scale.
pub fn element_window_local_xy(window_id: u64, pid: i64, element_index: u32) -> Option<(f64, f64)> {
- let cache = ELEMENT_CACHE.get()?;
+ let runtime_scope =
+ cua_driver_core::tool::current_dispatch_runtime_scope().unwrap_or_else(|| "legacy".into());
+ let cache = ELEMENT_CACHES
+ .get()?
+ .lock()
+ .unwrap()
+ .get(&runtime_scope)?
+ .upgrade()?;
let pid_i32 = i32::try_from(pid).ok()?;
let window_id_u32 = u32::try_from(window_id).ok()?;
// Retain so a concurrent get_window_state can't free the element between
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 a472fb3f0e..8a8c09b0c9 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
@@ -529,9 +529,9 @@ pub fn register_all(
host_owns_permission_ux,
host_bundle_id,
));
- {
+ let cursor_outcome_reader = {
let cursor_registry = state.cursor_registry.clone();
- let _ = cua_driver_core::session::set_cursor_outcome_reader(std::sync::Arc::new(
+ cua_driver_core::session::register_scoped_cursor_outcome_reader(std::sync::Arc::new(
move |session_id| {
let state = cursor_registry.get(session_id);
let motion_customized = state.is_some()
@@ -564,7 +564,22 @@ pub fn register_all(
),
}
},
- ));
+ ))
+ };
+ registry.retain_cursor_outcome_reader(cursor_outcome_reader);
+ if let Some(runtime_scope) = cua_driver_core::tool::current_dispatch_runtime_scope() {
+ let prefix = format!("__cua_runtime_{runtime_scope}:");
+ let cursor_registry = state.cursor_registry.clone();
+ registry.retain_runtime_cleanup(move || {
+ for cursor in cursor_registry
+ .all_states()
+ .into_iter()
+ .filter(|cursor| cursor.config.cursor_id.starts_with(&prefix))
+ {
+ cursor_registry.remove(&cursor.config.cursor_id);
+ crate::cursor::overlay::remove_cursor(cursor.config.cursor_id);
+ }
+ });
}
// Share the element cache with the recording-hook layer so it can
// resolve element_index → window-local screenshot coords for click.png.
@@ -576,17 +591,19 @@ pub fn register_all(
{
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());
- });
+ let registration =
+ cua_driver_core::session::register_scoped_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());
+ });
+ registry.retain_session_end_hook(registration);
}
registry.register(Box::new(list_apps::ListAppsTool));
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
index f51e8ee270..b5ce2f9dda 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
@@ -167,22 +167,27 @@ fn apply_msg(map: &mut RenderMap, msg: OverlayMsg) -> Option<CursorKey> {
}
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);
- *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,
- virt_x: 0,
- virt_y: 0,
- virt_w: 1920,
- virt_h: 1080,
- last_tick: Instant::now(),
- template: cfg,
- ended: HashSet::new(),
- last_active: None,
+ static INITIALIZED: OnceLock<()> = OnceLock::new();
+ INITIALIZED.get_or_init(|| {
+ let (tx, rx) = std::sync::mpsc::sync_channel(4096);
+ CMD_TX
+ .set(tx)
+ .expect("cursor overlay sender is initialized exactly once");
+ *CMD_RX_CELL.lock().unwrap() = Some(rx);
+ *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,
+ virt_x: 0,
+ virt_y: 0,
+ virt_w: 1920,
+ virt_h: 1080,
+ last_tick: Instant::now(),
+ template: cfg,
+ ended: HashSet::new(),
+ last_active: None,
+ });
});
}
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs b/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs
index f6e4cbb5a9..aa29319b4e 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs
@@ -7,7 +7,10 @@
//! on UIA/MSAA-indexed clicks (not just pixel-addressed ones).
#[cfg(target_os = "windows")]
-use std::sync::{Arc, OnceLock};
+use std::{
+ collections::HashMap,
+ sync::{Arc, Mutex, OnceLock, Weak},
+};
#[cfg(target_os = "windows")]
use crate::uia::ElementCache;
@@ -26,11 +29,18 @@ use windows::Win32::UI::WindowsAndMessaging::{
};
#[cfg(target_os = "windows")]
-static ELEMENT_CACHE: OnceLock<Arc<ElementCache>> = OnceLock::new();
+static ELEMENT_CACHES: OnceLock<Mutex<HashMap<String, Weak<ElementCache>>>> = OnceLock::new();
#[cfg(target_os = "windows")]
pub fn set_element_cache(cache: Arc<ElementCache>) {
- let _ = ELEMENT_CACHE.set(cache);
+ let runtime_scope =
+ cua_driver_core::tool::current_dispatch_runtime_scope().unwrap_or_else(|| "legacy".into());
+ let mut caches = ELEMENT_CACHES
+ .get_or_init(|| Mutex::new(HashMap::new()))
+ .lock()
+ .unwrap();
+ caches.retain(|_, cache| cache.strong_count() > 0);
+ caches.insert(runtime_scope, Arc::downgrade(&cache));
}
/// Resolve the window whose application evidence should be captured. Keep a
@@ -104,7 +114,14 @@ pub fn app_state_json_for(window_id: Option<u64>, pid: Option<i64>) -> Option<Ve
#[cfg(target_os = "windows")]
pub fn element_window_local_xy(window_id: u64, pid: i64, element_index: u32) -> Option<(f64, f64)> {
- let cache = ELEMENT_CACHE.get()?;
+ let runtime_scope =
+ cua_driver_core::tool::current_dispatch_runtime_scope().unwrap_or_else(|| "legacy".into());
+ let cache = ELEMENT_CACHES
+ .get()?
+ .lock()
+ .unwrap()
+ .get(&runtime_scope)?
+ .upgrade()?;
let pid_u32 = u32::try_from(pid).ok()?;
let (sx, sy) = cache.get_element_center(pid_u32, window_id, element_index as usize)?;
// The cached center is in SCREEN coords. Convert to window-local pixel
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
index 1e59dbe411..95d0d5318c 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
@@ -8538,9 +8538,9 @@ impl Tool for DebugWindowInfoTool {
pub fn build_registry(compat: bool) -> ToolRegistry {
let state = ToolState::new();
- {
+ let cursor_outcome_reader = {
let cursor_registry = state.cursor_registry.clone();
- let _ = cua_driver_core::session::set_cursor_outcome_reader(std::sync::Arc::new(
+ cua_driver_core::session::register_scoped_cursor_outcome_reader(std::sync::Arc::new(
move |session_id| {
let state = cursor_registry.get(session_id);
let motion_customized = state.is_some()
@@ -8573,8 +8573,8 @@ pub fn build_registry(compat: bool) -> ToolRegistry {
),
}
},
- ));
- }
+ ))
+ };
// Share the element cache with the recording-hook layer so it can
// resolve element_index → window-local screenshot coords for click.png.
crate::recording_hooks::set_element_cache(state.element_cache.clone());
@@ -8583,22 +8583,34 @@ pub fn build_registry(compat: bool) -> ToolRegistry {
// CLI `session end` verb, or the daemon idle-TTL sweep). The session id IS
// the cursor key (caller-declared `session`), so this prunes the metadata
// registry AND stops the overlay painting that session's cursor. Both paths
- // guard "default" so the anonymous / one-shot cursor survives. Registering
- // once per process (build_registry runs once in the daemon) is guarded so a
- // repeated build in tests can't accumulate duplicate hooks. Mirrors the
- // macOS `register_all` session_end hook (platform-macos/src/tools/mod.rs).
- {
- static HOOK_ONCE: std::sync::OnceLock<()> = std::sync::OnceLock::new();
- if HOOK_ONCE.set(()).is_ok() {
- let cursor_registry = state.cursor_registry.clone();
- cua_driver_core::session::register_session_end_hook(move |session_id| {
- cursor_registry.remove(session_id);
- crate::overlay::remove_cursor(session_id.to_owned());
- });
- }
- }
+ // guard "default" so the anonymous / one-shot cursor survives. The scoped
+ // registration lets each direct runtime clean up its own cursor state and
+ // deregisters when that runtime's registry is dropped. Mirrors the macOS
+ // `register_all` session_end hook (platform-macos/src/tools/mod.rs).
+ let cursor_registry = state.cursor_registry.clone();
+ let session_end_hook =
+ cua_driver_core::session::register_scoped_session_end_hook(move |session_id| {
+ cursor_registry.remove(session_id);
+ crate::overlay::remove_cursor(session_id.to_owned());
+ });
let mut r = ToolRegistry::new();
+ r.retain_cursor_outcome_reader(cursor_outcome_reader);
+ r.retain_session_end_hook(session_end_hook);
+ if let Some(runtime_scope) = cua_driver_core::tool::current_dispatch_runtime_scope() {
+ let prefix = format!("__cua_runtime_{runtime_scope}:");
+ let cursor_registry = state.cursor_registry.clone();
+ r.retain_runtime_cleanup(move || {
+ for cursor in cursor_registry
+ .all_states()
+ .into_iter()
+ .filter(|cursor| cursor.config.cursor_id.starts_with(&prefix))
+ {
+ cursor_registry.remove(&cursor.config.cursor_id);
+ crate::overlay::remove_cursor(cursor.config.cursor_id);
+ }
+ });
+ }
r.register(Box::new(ListAppsTool));
r.register(Box::new(ListWindowsTool));
r.register(Box::new(GetWindowStateTool {
diff --git a/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts b/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts
index 6ad84b8e3b..b3578f6118 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts
@@ -433,6 +433,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_fn_method_cuadriver_runtime_scope_prefix": {
+ args: [FfiType.Handle],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_driver_sdk_fn_method_cuadriver_scroll": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -723,6 +728,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_method_cuadriver_runtime_scope_prefix": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_method_cuadriver_scroll": {
args: [],
ret: FfiType.UInt16,
@@ -972,6 +982,7 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_method_cuadriver_metadata(uniffiSelf: bigint): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_move_cursor(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_press_key(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriver_runtime_scope_prefix(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_method_cuadriver_scroll(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_shutdown(uniffiSelf: bigint): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_socket_path(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
@@ -1030,6 +1041,7 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriver_runtime_scope_prefix(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_scroll(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_shutdown(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_socket_path(): number;
diff --git a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
index 3800e00588..b4a158f0da 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
@@ -2163,6 +2163,7 @@ export interface CuaDriverLike {
metadata(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<DriverMetadata>;
moveCursor(input: MoveCursorInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
pressKey(input: PressKeyInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ runtimeScopePrefix(): string | undefined;
scroll(input: ScrollInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
/**
* Stop accepting new embedded operations. Repeated calls are harmless;
@@ -2817,6 +2818,23 @@ private constructor(pointer: UniffiHandle) {
}
}
+ runtimeScopePrefix(): string | undefined {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterOptionalString.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_runtime_scope_prefix(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
async scroll(input: ScrollInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
@@ -4091,6 +4109,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key() !== 63712) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_runtime_scope_prefix() !== 2453) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_runtime_scope_prefix");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_scroll() !== 52290) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_scroll");
}