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.

fix(cua-driver): recreate an idle-reclaimed unnamed session on its next call (#4283)

Francesco Bonaccib0842f526655
diff --git a/docs/content/docs/reference/cua-driver/contracts.mdx b/docs/content/docs/reference/cua-driver/contracts.mdx
index e03c6c6cf7..06dd324e8d 100644
--- a/docs/content/docs/reference/cua-driver/contracts.mdx
+++ b/docs/content/docs/reference/cua-driver/contracts.mdx
@@ -47,6 +47,13 @@ visibility only. A call in flight cannot expire, and a completed call refreshes
the lifecycle timer once. Transport close, explicit end, revocation, and idle
expiry use the same cleanup hooks.
+When idle expiry ends a transport's implicit session, the next unnamed stateful
+call on that transport starts a new implicit session. Cleanup has already run,
+so element tokens and snapshots from the ended session stay invalid; take a new
+snapshot before acting. Other ended sessions stay ended and refuse calls with
+`session_ended` until `start_session` restarts them: pass the label for a named
+session, or omit `session` for the implicit one.
+
For multi-call work, prefer a short public `session` label and pass the same
value on every call that accepts it. Passing it once is not sticky: a later call
that omits the field uses the transport's implicit session instead. Use
diff --git a/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx b/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx
index 853c57d285..bca35f8e61 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx
@@ -30,7 +30,10 @@ The first admitted stateful call creates the transport's implicit lifecycle
session. Repeated unnamed clicks on the same MCP connection belong to that one
session; they do not create one session per click. The default idle TTL is five
minutes, separate from the cursor's visibility timeout. Transport close,
-explicit end, or idle expiry runs the same cleanup path.
+explicit end, or idle expiry runs the same cleanup path. After idle expiry, the
+next unnamed call starts a new implicit session, while earlier element tokens
+stay stale. A named session that expires stays ended until `start_session`
+restarts it by name.
### PID-only window targets
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rs
index c42a79d86a..6d71353910 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rs
@@ -973,6 +973,51 @@ mod tests {
);
}
+ #[test]
+ fn recreating_an_idle_reclaimed_implicit_session_keeps_its_old_tokens_stale() {
+ use crate::session::{
+ begin_session_dispatch, evict_idle_with_prefix, register_scoped_session_end_hook,
+ SessionClientKind, SessionTransport,
+ };
+ let session = format!("element-cache-idle-implicit-{}", std::process::id());
+ let cache = Arc::new(ElementCacheCore::<Payload>::new());
+ let retiring = cache.clone();
+ let _hook = register_scoped_session_end_hook(move |ended| {
+ retiring.retire_session_screenshots(ended);
+ });
+ let begin = || {
+ begin_session_dispatch(
+ &session,
+ None,
+ &session,
+ true,
+ SessionTransport::McpStdio,
+ SessionClientKind::Mcp,
+ )
+ };
+
+ let guard = begin().expect("first unnamed call starts the session");
+ let snapshot = cache
+ .publish_for_session(10, 20, Payload(vec![0, 1]), Some(&session), Some(1.0))
+ .expect("live session publishes");
+ let token = token_for(snapshot, 1);
+ drop(guard);
+ assert_eq!(
+ evict_idle_with_prefix(std::time::Duration::ZERO, &session),
+ [session.clone()]
+ );
+
+ let guard = begin().expect("next unnamed call recreates the session");
+ assert_eq!(resolve(&cache, 10, &token), Err(STALE_TOKEN_ERROR.into()));
+ let fresh = cache
+ .publish_for_session(10, 20, Payload(vec![0, 1]), Some(&session), Some(1.0))
+ .expect("recreated session publishes again");
+ assert_eq!(resolve(&cache, 10, &token_for(fresh, 1)), Ok((20, 1)));
+ drop(guard);
+ crate::session::end_session(&session);
+ crate::session::revive_session(&session);
+ }
+
#[test]
fn session_retirement_removes_only_snapshots_owned_by_that_session() {
let cache = ElementCacheCore::new();
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 727d30574f..44c331e5c4 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
@@ -456,14 +456,30 @@ fn begin_session_dispatch_inner(
if !is_trackable(session_id) {
return Err("session has ended");
}
+ // An unnamed transport session reclaimed by the idle sweep starts a new
+ // lifecycle episode on its owner's next call instead of refusing every
+ // later call. Its cleanup must have finished first, so snapshots, element
+ // tokens, grants, and recordings from the ended episode stay retired.
+ let recreate = recreates_on_next_call(session_id, owner_transport);
+ if recreate && !retry_session_cleanup(session_id).complete {
+ return Err("session cleanup is incomplete; retry the call");
+ }
let now = Instant::now();
- {
+ let recreated = {
// Keep tombstone admission and live-record insertion in one critical
// section. Otherwise an end could land between the old pre-check and
// insertion, leaving a tombstoned record that was silently recreated
// by a racing first action.
- let ended = ended_sessions().lock().unwrap();
- if ended.contains_key(session_id) {
+ let mut ended = ended_sessions().lock().unwrap();
+ let mut idle_ended = idle_ended_implicit_sessions().lock().unwrap();
+ let recreated = ended.contains_key(session_id);
+ if recreated
+ && !(recreate
+ && idle_ended.contains(session_id)
+ && ended
+ .get(session_id)
+ .is_some_and(|owner| owner.as_deref() == Some(owner_transport)))
+ {
return Err("session has ended");
}
let mut records = lifecycle_records().lock().unwrap();
@@ -490,11 +506,21 @@ fn begin_session_dispatch_inner(
record.idle_ttl = idle_ttl;
}
record.in_flight += 1;
- }
+ if recreated {
+ ended.remove(session_id);
+ idle_ended.remove(session_id);
+ }
+ recreated
+ };
activity()
.lock()
.unwrap()
.insert(session_id.to_owned(), now);
+ if recreated {
+ // Platform overlays keep their own late-command tombstones; clear
+ // them exactly as an explicit start_session revival would.
+ fire_session_revive_for_owner(session_id, owner_transport);
+ }
Ok(SessionDispatchGuard {
session_id: session_id.to_owned(),
})
@@ -666,6 +692,10 @@ pub fn activate_or_revive_session_for_owner(
}
if revived {
ended.remove(session_id);
+ idle_ended_implicit_sessions()
+ .lock()
+ .unwrap()
+ .remove(session_id);
}
revived
};
@@ -936,6 +966,10 @@ fn capture_modality_for(tool_name: &str, args: &serde_json::Value) -> Option<Cap
/// once. Growth is bounded (one short string per ended session over the
/// daemon's lifetime); eviction is a deliberate non-blocking follow-up.
static ENDED_SESSIONS: OnceLock<Mutex<HashMap<String, Option<String>>>> = OnceLock::new();
+/// Tombstoned unnamed transport sessions whose episode ended only because the
+/// idle sweep reclaimed it. Mutated only while holding the `ENDED_SESSIONS`
+/// lock, and meaningful only while the matching tombstone exists.
+static IDLE_ENDED_IMPLICIT_SESSIONS: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
/// Runtime generations that have received terminal revoke-all.
///
/// This latch is intentionally independent of grants and public session
@@ -959,6 +993,10 @@ fn ended_sessions() -> &'static Mutex<HashMap<String, Option<String>>> {
ENDED_SESSIONS.get_or_init(|| Mutex::new(HashMap::new()))
}
+fn idle_ended_implicit_sessions() -> &'static Mutex<HashSet<String>> {
+ IDLE_ENDED_IMPLICIT_SESSIONS.get_or_init(|| Mutex::new(HashSet::new()))
+}
+
fn suspended_runtime_scopes() -> &'static Mutex<HashSet<String>> {
SUSPENDED_RUNTIME_SCOPES.get_or_init(|| Mutex::new(HashSet::new()))
}
@@ -1164,6 +1202,11 @@ pub fn release_process_state_for_shutdown() {
let mut ended = ended.lock().unwrap();
ended.clear();
ended.shrink_to_fit();
+ if let Some(idle_ended) = IDLE_ENDED_IMPLICIT_SESSIONS.get() {
+ let mut idle_ended = idle_ended.lock().unwrap();
+ idle_ended.clear();
+ idle_ended.shrink_to_fit();
+ }
}
if let Some(scopes) = SUSPENDED_RUNTIME_SCOPES.get() {
let mut scopes = scopes.lock().unwrap();
@@ -1185,7 +1228,7 @@ pub fn fire_session_end(session_id: &str) -> bool {
}
fn fire_session_end_for_owner(session_id: &str, owner_transport: Option<&str>) -> bool {
- let first_fire = mark_session_ended(session_id, owner_transport);
+ let first_fire = mark_session_ended(session_id, owner_transport, SessionEndReason::Unknown);
if first_fire {
initialize_session_cleanup(session_id);
}
@@ -1198,21 +1241,40 @@ fn fire_session_end_for_owner(session_id: &str, owner_transport: Option<&str>) -
/// Hooks run after this short critical section. Keeping this transition under
/// the same lock order as dispatch admission prevents a racing first action
/// from recreating a record immediately before or after termination.
-fn mark_session_ended(session_id: &str, owner_transport: Option<&str>) -> bool {
+fn mark_session_ended(
+ session_id: &str,
+ owner_transport: Option<&str>,
+ reason: SessionEndReason,
+) -> bool {
activity().lock().unwrap().remove(session_id);
let mut ended = ended_sessions().lock().unwrap();
- let record_owner = lifecycle_records()
- .lock()
- .unwrap()
- .remove(session_id)
- .map(|record| record.owner_transport);
+ let record = lifecycle_records().lock().unwrap().remove(session_id);
+ // Only the transport's own unnamed session, reclaimed for inactivity, is
+ // recreated on its next call. Named sessions and every other end reason
+ // keep the resurrection guard until an explicit start_session.
+ let idle_implicit = reason == SessionEndReason::IdleTimeout
+ && record
+ .as_ref()
+ .is_some_and(|record| record.implicit && record.owner_transport == session_id);
+ let mut idle_ended = idle_ended_implicit_sessions().lock().unwrap();
if ended.contains_key(session_id) {
+ // A later explicit or transport end makes an idle end terminal.
+ if reason != SessionEndReason::IdleTimeout {
+ idle_ended.remove(session_id);
+ }
false
} else {
ended.insert(
session_id.to_owned(),
- owner_transport.map(str::to_owned).or(record_owner),
+ owner_transport
+ .map(str::to_owned)
+ .or(record.map(|record| record.owner_transport)),
);
+ if idle_implicit {
+ idle_ended.insert(session_id.to_owned());
+ } else {
+ idle_ended.remove(session_id);
+ }
true
}
}
@@ -1363,6 +1425,10 @@ pub fn forget_ended_sessions_with_prefix(prefix: &str) -> usize {
let before = ended.len();
ended.retain(|session, _| !session.starts_with(prefix));
let forgotten = before - ended.len();
+ idle_ended_implicit_sessions()
+ .lock()
+ .unwrap()
+ .retain(|session| !session.starts_with(prefix));
drop(ended);
cleanup_progress()
.lock()
@@ -1379,6 +1445,24 @@ pub fn is_session_ended(session_id: &str) -> bool {
ended_sessions().lock().unwrap().contains_key(session_id)
}
+/// Whether an ended lifecycle id is the owner transport's unnamed session,
+/// reclaimed only by the idle sweep, so that transport's next
+/// session-requiring call recreates it instead of being refused. Named
+/// sessions, explicit ends, and transport exits always return `false`.
+pub fn recreates_on_next_call(session_id: &str, owner_transport: &str) -> bool {
+ if session_id != owner_transport {
+ return false;
+ }
+ let ended = ended_sessions().lock().unwrap();
+ ended
+ .get(session_id)
+ .is_some_and(|owner| owner.as_deref() == Some(owner_transport))
+ && idle_ended_implicit_sessions()
+ .lock()
+ .unwrap()
+ .contains(session_id)
+}
+
/// Whether termination has been requested for a runtime-private lifecycle.
///
/// Long-running adapters may use this to relinquish held input before their
@@ -1414,11 +1498,12 @@ pub fn revive_session(session_id: &str) -> bool {
if !retry_session_cleanup(session_id).complete {
return false;
}
- ended_sessions()
+ let mut ended = ended_sessions().lock().unwrap();
+ idle_ended_implicit_sessions()
.lock()
.unwrap()
- .remove(session_id)
- .is_some()
+ .remove(session_id);
+ ended.remove(session_id).is_some()
}
/// Owner-checked revival used by the public `start_session` tool. A public
@@ -1472,6 +1557,10 @@ pub fn revive_session_for_owner(
None if owner_transport != session_id => Err("session is not available to this transport"),
_ => {
ended.remove(session_id);
+ idle_ended_implicit_sessions()
+ .lock()
+ .unwrap()
+ .remove(session_id);
Ok(true)
}
}
@@ -1536,7 +1625,7 @@ fn end_session_with_reason(session_id: &str, reason: SessionEndReason) {
}
fn finish_session_end(session_id: &str, reason: SessionEndReason) {
- let first_fire = mark_session_ended(session_id, None);
+ let first_fire = mark_session_ended(session_id, None, reason);
let mut cursor_readers = CURSOR_OUTCOME_READERS
.get()
.map(|readers| {
@@ -2112,6 +2201,86 @@ mod tests {
assert!(revive_session(sid));
}
+ #[test]
+ fn only_the_owners_unnamed_session_is_recreated_after_an_idle_end() {
+ let pid = std::process::id();
+ let implicit = format!("idle-recreate-implicit-{pid}");
+ let named = format!("idle-recreate-named-{pid}");
+ let named_owner = format!("idle-recreate-named-owner-{pid}");
+ let begin = |id: &str, label: Option<&str>, owner: &str| {
+ begin_session_dispatch(
+ id,
+ label,
+ owner,
+ label.is_none(),
+ SessionTransport::McpStdio,
+ SessionClientKind::Mcp,
+ )
+ };
+ // Fail at the idle end and at the first recreation attempt.
+ let failures = Arc::new(AtomicUsize::new(2));
+ let failures_for_hook = failures.clone();
+ let observed = implicit.clone();
+ let _hook = register_scoped_fallible_session_end_hook("idle-recreate-test", move |id| {
+ if id == observed
+ && failures_for_hook
+ .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| {
+ left.checked_sub(1)
+ })
+ .is_ok()
+ {
+ return Err("synthetic cleanup failure".into());
+ }
+ Ok(())
+ });
+
+ drop(begin(&implicit, None, &implicit).unwrap());
+ drop(begin(&named, Some("named"), &named_owner).unwrap());
+ assert_eq!(
+ evict_idle_with_prefix(Duration::ZERO, &implicit),
+ [implicit.clone()]
+ );
+ assert_eq!(
+ evict_idle_with_prefix(Duration::ZERO, &named),
+ [named.clone()]
+ );
+
+ // A named episode keeps its resurrection guard.
+ assert!(!recreates_on_next_call(&named, &named_owner));
+ assert_eq!(
+ begin(&named, Some("named"), &named_owner).err(),
+ Some("session has ended")
+ );
+ // Another transport cannot claim the unnamed id.
+ assert_eq!(
+ begin(&implicit, None, "another-transport").err(),
+ Some("session has ended")
+ );
+ // Unfinished cleanup is retried by the call and blocks recreation.
+ assert!(recreates_on_next_call(&implicit, &implicit));
+ assert_eq!(
+ begin(&implicit, None, &implicit).err(),
+ Some("session cleanup is incomplete; retry the call")
+ );
+ let guard = begin(&implicit, None, &implicit).expect("recreated after cleanup");
+ assert!(!is_session_ended(&implicit));
+ assert!(
+ session_snapshot(&implicit, &implicit, DEFAULT_SESSION_IDLE_TTL)
+ .is_some_and(|snapshot| snapshot.implicit)
+ );
+ drop(guard);
+
+ // An explicit end stays terminal until start_session.
+ end_session(&implicit);
+ assert!(!recreates_on_next_call(&implicit, &implicit));
+ assert_eq!(
+ begin(&implicit, None, &implicit).err(),
+ Some("session has ended")
+ );
+ assert!(revive_session(&implicit));
+ assert!(revive_session(&named));
+ }
+
#[test]
fn revive_clears_the_tombstone_for_an_ended_id() {
let sid = "test-revive-session-445566";
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 298d85b622..47b56e7134 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
@@ -1173,13 +1173,21 @@ impl ToolRegistry {
.and_then(Value::as_str)
.map(str::to_owned);
if let Some(session) = runtime_session.as_deref() {
+ let owner = args
+ .get("_transport_session_id")
+ .and_then(Value::as_str)
+ .unwrap_or(session);
+ // An unnamed session reclaimed by the idle sweep is recreated at
+ // lifecycle admission below; every other ended episode refuses
+ // with the recovery that actually applies to its identity.
if !matches!(resolved_name, "start_session" | "end_session")
&& crate::session::is_session_ended(session)
+ && !crate::session::recreates_on_next_call(session, owner)
{
- let mut result = protected_refusal(
- "session_ended",
- "this session has ended; call start_session explicitly to reuse its label",
+ let message = ended_session_refusal_message(
+ args.get("_public_session_label").and_then(Value::as_str),
);
+ let mut result = protected_refusal("session_ended", &message);
restore_public_runtime_result(&mut result, &runtime_prefix);
return result;
}
@@ -3591,6 +3599,106 @@ resources:
.any(|content| matches!(content, crate::protocol::Content::Text { text, .. } if text.contains("idle timeout"))));
}
+ #[tokio::test]
+ async fn idle_reclaimed_unnamed_session_recreates_and_ended_sessions_name_a_working_recovery() {
+ let hits = Arc::new(AtomicUsize::new(0));
+ let mut registry = super::ToolRegistry::new_with_protected_consent_provider(None);
+ registry.register(Box::new(ObservationProbe {
+ hits: hits.clone(),
+ def: super::ToolDef {
+ name: "get_window_state".into(),
+ description: "test observation".into(),
+ input_schema: serde_json::json!({"type": "object"}),
+ read_only: true,
+ destructive: false,
+ idempotent: true,
+ open_world: false,
+ },
+ }));
+ registry.register(Box::new(crate::session_tools::StartSessionTool));
+ registry.register(Box::new(crate::session_tools::EndSessionTool));
+ let context = standard_context();
+ let prefix = format!("__cua_runtime_{}:", context.runtime_scope_key());
+ let call = |args: serde_json::Value| {
+ let registry = &registry;
+ let context = context.clone();
+ async move {
+ let mut args = args;
+ args["pid"] = 42.into();
+ args["window_id"] = 7.into();
+ registry
+ .invoke_with_context("get_window_state", args, context)
+ .await
+ }
+ };
+ let refusal = |result: &ToolResult| {
+ let refusal = &result.structured_content.as_ref().unwrap()["refusal"];
+ (
+ refusal["code"].as_str().unwrap().to_owned(),
+ refusal["message"].as_str().unwrap().to_owned(),
+ )
+ };
+
+ assert_ne!(call(serde_json::json!({})).await.is_error, Some(true));
+ assert_ne!(
+ call(serde_json::json!({"session": "named"})).await.is_error,
+ Some(true)
+ );
+ assert_eq!(
+ crate::session::evict_idle_with_prefix(Duration::ZERO, &prefix).len(),
+ 2
+ );
+
+ // The unnamed session comes back on its next call.
+ assert_ne!(call(serde_json::json!({})).await.is_error, Some(true));
+ assert_eq!(hits.load(Ordering::SeqCst), 3);
+
+ // A named session stays refused, and the named recovery works.
+ let named = call(serde_json::json!({"session": "named"})).await;
+ assert_eq!(
+ refusal(&named),
+ (
+ "session_ended".to_owned(),
+ "session 'named' has ended; call start_session with session 'named' to start it again, or use a new session label".to_owned()
+ )
+ );
+ let started = registry
+ .invoke_with_context(
+ "start_session",
+ serde_json::json!({"session": "named"}),
+ context.clone(),
+ )
+ .await;
+ assert_ne!(started.is_error, Some(true), "{started:?}");
+ assert_ne!(
+ call(serde_json::json!({"session": "named"})).await.is_error,
+ Some(true)
+ );
+
+ // An explicitly ended unnamed session names the unlabeled recovery.
+ let ended = registry
+ .invoke_with_context("end_session", serde_json::json!({}), context.clone())
+ .await;
+ assert_ne!(ended.is_error, Some(true), "{ended:?}");
+ let unnamed = call(serde_json::json!({})).await;
+ assert_eq!(
+ refusal(&unnamed),
+ (
+ "session_ended".to_owned(),
+ "this transport's unnamed session has ended; call start_session without a session label to start a new one".to_owned()
+ )
+ );
+ let restarted = registry
+ .invoke_with_context("start_session", serde_json::json!({}), context.clone())
+ .await;
+ assert_ne!(restarted.is_error, Some(true), "{restarted:?}");
+ assert_ne!(call(serde_json::json!({})).await.is_error, Some(true));
+ assert_eq!(hits.load(Ordering::SeqCst), 5);
+
+ crate::session::revoke_sessions_with_prefix(&prefix);
+ crate::session::forget_ended_sessions_with_prefix(&prefix);
+ }
+
#[tokio::test]
async fn ended_session_and_runtime_suspend_latches_fail_closed_at_dispatch() {
let ended_hits = Arc::new(AtomicUsize::new(0));
@@ -5045,6 +5153,18 @@ fn protected_scope_refusal(message: &str) -> ToolResult {
protected_refusal("protected_resource_scope_invalid", message)
}
+/// Recovery text for a call on an ended lifecycle episode. A named session is
+/// restarted by name from its own transport; an unnamed one has no label to
+/// pass, so naming one would only start an unrelated session.
+fn ended_session_refusal_message(public_label: Option<&str>) -> String {
+ match public_label {
+ Some(label) => format!(
+ "session '{label}' has ended; call start_session with session '{label}' to start it again, or use a new session label"
+ ),
+ None => "this transport's unnamed session has ended; call start_session without a session label to start a new one".to_owned(),
+ }
+}
+
fn protected_refusal(code: &str, message: &str) -> ToolResult {
ToolResult::error(message).with_structured(serde_json::json!({
"status": "refused",
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 a26a6bfe95..e5f36053c8 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
@@ -53,6 +53,7 @@ pub struct SdkAdapter {
runtime_prefix: String,
runtime_scope: String,
_session_end_hook: cua_driver_core::session::SessionEndHookRegistration,
+ _session_revive_hook: cua_driver_core::session::SessionReviveHookRegistration,
session_lifecycle: tokio::sync::Mutex<()>,
}
@@ -120,6 +121,16 @@ impl SdkAdapter {
sessions.scopes.entry(public.to_owned()).or_default();
sessions.mark_ended(public);
});
+ // Core also revives an idle-reclaimed unnamed session on its next
+ // call, not only through start_session, so follow every revival.
+ let revive_sessions = public_sessions.clone();
+ let revive_prefix = runtime_prefix.clone();
+ let session_revive_hook =
+ cua_driver_core::session::register_scoped_session_revive_hook(move |session| {
+ if let Some(public) = session.strip_prefix(&revive_prefix) {
+ revive_sessions.lock().unwrap().ended.remove(public);
+ }
+ });
Ok(Arc::new(Self {
driver,
tools_list,
@@ -127,6 +138,7 @@ impl SdkAdapter {
runtime_prefix,
runtime_scope,
_session_end_hook: session_end_hook,
+ _session_revive_hook: session_revive_hook,
session_lifecycle: tokio::sync::Mutex::new(()),
}))
}
@@ -260,12 +272,21 @@ impl SdkAdapter {
Ok(value)
}
+ /// Whether the legacy socket must refuse a call on this ended session.
+ /// An unnamed transport session reclaimed by the idle sweep is not
+ /// refused: core recreates it on the call.
pub fn is_session_ended(&self, session: &str) -> bool {
- self.public_sessions
+ if !self
+ .public_sessions
.lock()
.unwrap()
.ended
.contains_key(session)
+ {
+ return false;
+ }
+ let internal = format!("{}{session}", self.runtime_prefix);
+ !cua_driver_core::session::recreates_on_next_call(&internal, &internal)
}
pub fn mark_all_sessions_ended(&self) {
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 f4ba70bcfc..b963748979 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -469,12 +469,18 @@ async fn invoke_daemon_tool(
if let Some(sid) = &effective_session {
if !is_session_lifecycle_tool(&tool_name) && sdk.is_session_ended(sid) {
observe_daemon_error(observation, 1);
- return DaemonResponse::err(
+ // An unnamed call's lifecycle id is the transport session, which
+ // is not a label the caller can pass back to start_session.
+ let recovery = if req.session_id.as_deref() == Some(sid.as_str()) {
+ "Call start_session without a session label to start a new unnamed session."
+ .to_owned()
+ } else {
format!(
- "session '{sid}' has ended; tool call '{tool_name}' was rejected. \
- Call start_session with this id to revive it before issuing further \
- actions, or use a new session id."
- ),
+ "Call start_session with session '{sid}' to start it again, or use a new session label."
+ )
+ };
+ return DaemonResponse::err(
+ format!("session has ended; tool call '{tool_name}' was rejected. {recovery}"),
1,
);
}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_proxy_recovery_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_proxy_recovery_test.rs
index 326b407062..9741e03315 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_proxy_recovery_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_proxy_recovery_test.rs
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Cua AI, Inc.
-//! Real stdio proxies and a real daemon, with selective control-channel loss.
+//! Real stdio proxies and a real daemon, with selective control-channel loss
+//! and with the idle-TTL sweep reclaiming sessions.
//! Set CUA_PROXY_RECOVERY_IDLE_SECONDS=1200 for a long-idle diagnostic replay.
//! This injects a known transport failure; it does not reproduce an unknown trigger.
@@ -117,8 +118,12 @@ struct Process(Child, #[allow(dead_code)] tempfile::TempDir);
impl Process {
fn spawn(args: &[&str]) -> Self {
+ // This isolates transport lifetime from intentional session expiry.
+ Self::spawn_with_session_ttl(args, (recovery_idle_seconds() + 60).max(300))
+ }
+
+ fn spawn_with_session_ttl(args: &[&str], session_ttl_seconds: u64) -> Self {
let driver_home = tempfile::tempdir().expect("isolated driver state");
- let idle_seconds = recovery_idle_seconds();
let mut command = Command::new(env!("CARGO_BIN_EXE_cua-driver"));
command
.args(args)
@@ -126,10 +131,9 @@ impl Process {
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")
- // This test isolates transport lifetime from intentional session expiry.
.env(
"CUA_DRIVER_RS_SESSION_IDLE_TTL_SECS",
- (idle_seconds + 60).max(300).to_string(),
+ session_ttl_seconds.to_string(),
)
.env("HOME", driver_home.path())
.env("USERPROFILE", driver_home.path())
@@ -430,3 +434,67 @@ async fn real_proxies_recover_from_control_loss_without_waiting_for_stdin() {
survivor.call("get_config", json!({"session":"survivor"}));
relay_task.abort();
}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn idle_reclaimed_unnamed_session_is_recreated_through_the_daemon() {
+ #[cfg(unix)]
+ let directory = tempfile::Builder::new()
+ .prefix("cua-idle-")
+ .tempdir_in("/tmp")
+ .unwrap();
+ #[cfg(unix)]
+ let endpoint = directory.path().join("d.sock").display().to_string();
+ #[cfg(target_os = "windows")]
+ let endpoint = format!(r"\\.\pipe\cua-idle-{}-daemon", std::process::id());
+ let mut daemon = Process::spawn_with_session_ttl(
+ &[
+ "serve",
+ "--socket",
+ &endpoint,
+ "--no-overlay",
+ "--no-permissions-gate",
+ "--dangerously-bypass-approvals",
+ ],
+ 1,
+ );
+ let deadline = Instant::now() + BOUND;
+ while connect(&endpoint).await.is_err() {
+ assert!(
+ daemon.0.try_wait().unwrap().is_none(),
+ "daemon exited during startup"
+ );
+ assert!(Instant::now() < deadline, "daemon readiness timeout");
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ let mut client = Client::spawn(&endpoint);
+ client.call("get_config", json!({}));
+ client.call("get_config", json!({"session": "named-idle"}));
+
+ // The runtime sweeps every 30 seconds; wait for it to reclaim both.
+ let deadline = Instant::now() + Duration::from_secs(75);
+ loop {
+ let listed = daemon_request(&endpoint, json!({"method": "sessions_list"})).await;
+ if listed["sessions"].as_array().is_some_and(Vec::is_empty) {
+ break;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "idle sweep did not end the sessions: {listed}"
+ );
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ }
+
+ client.call("get_config", json!({}));
+ let named = client.request(
+ "tools/call",
+ json!({"name": "get_config", "arguments": {"session": "named-idle"}}),
+ );
+ assert_eq!(named["result"]["isError"], true, "{named}");
+ let text = named["result"]["content"][0]["text"].as_str().unwrap_or("");
+ assert!(
+ text.contains("start_session with session 'named-idle'"),
+ "named refusal must name its working recovery: {named}"
+ );
+ client.call("start_session", json!({"session": "named-idle"}));
+ client.call("get_config", json!({"session": "named-idle"}));
+}