The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(socket): skip the redundant startup connect that opened a second EIO session
M3gA-Minde006558651f4
diff --git a/src/core/runtime/services.rs b/src/core/runtime/services.rsindex 3c5b9083cf..d240b5e59e 100644--- a/src/core/runtime/services.rs+++ b/src/core/runtime/services.rs@@ -505,7 +505,7 @@ pub fn spawn_socket_auto_connect(}};let api_url = crate::api::config::effective_backend_api_url(&config.api_url);- let _initial_token = match crate::api::jwt::get_session_token(&config) {+ let initial_token = match crate::api::jwt::get_session_token(&config) {Ok(Some(t)) => t,Ok(None) => {log::info!(@@ -527,6 +527,17 @@ pub fn spawn_socket_auto_connect(// changed since CoreRuntime::build(), so the build-time Config is// not authoritative here.let _rebind = socket_mgr.lock_identity_rebind().await;+ // The renderer's `socket_connect_with_session` RPC connects the same+ // core to the same backend with the same token. Whichever path runs+ // second used to tear the other's live socket down and redo the+ // handshake (#6181); if it is already up for this identity there is+ // nothing to rebind.+ if socket_mgr.is_live_for(&api_url, &initial_token) {+ log::info!(+ "[socket] Auto-connect: {api_url} already connected with this session — nothing to do"+ );+ return;+ }if let Err(e) = socket_mgr.disconnect().await {log::error!("[socket] Auto-connect could not stop the prior connection: {e}");return;diff --git a/src/openhuman/platform/socket/manager.rs b/src/openhuman/platform/socket/manager.rsindex 093bb41d3c..176eedb7c7 100644--- a/src/openhuman/platform/socket/manager.rs+++ b/src/openhuman/platform/socket/manager.rs@@ -170,6 +170,13 @@ pub struct SocketManager {/// Serializes identity-sensitive disconnect → bridge bind → connect/// transactions while still allowing ordinary emits and state reads.identity_rebind: tokio::sync::Mutex<()>,+ /// `(url, token)` the background loop is currently serving, recorded when a+ /// loop is spawned and cleared on disconnect. Read by [`is_live_for`] so a+ /// redundant connect for the identity that is already live can be skipped+ /// instead of re-running the whole handshake (#6181).+ ///+ /// [`is_live_for`]: SocketManager::is_live_for+ connection_identity: RwLock<Option<(String, String)>>,}impl SocketManager {@@ -188,6 +195,7 @@ impl SocketManager {shutdown_tx: tokio::sync::Mutex::new(None),loop_handle: tokio::sync::Mutex::new(None),identity_rebind: tokio::sync::Mutex::new(()),+ connection_identity: RwLock::new(None),}}@@ -221,6 +229,29 @@ impl SocketManager {*self.shared.status.read() == ConnectionStatus::Connected}+ /// True when a **live** connection is already serving exactly this `url`+ /// under exactly this session token.+ ///+ /// Startup has two independent connect paths — the core's bootstrap+ /// auto-connect and the renderer's `socket_connect_with_session` RPC — and+ /// each unconditionally tore the other's socket down and redid the whole+ /// Engine.IO/Socket.IO handshake, so a cold start opened two EIO sessions a+ /// couple of seconds apart (#6181). Callers consult this before starting an+ /// identity rebind so the second path becomes a no-op.+ ///+ /// Deliberately conservative: a different URL, a different token, or any+ /// status other than `Connected` all report `false`, so an account switch+ /// (same URL, new token) still forces a real reconnect and an unhealthy+ /// socket is still replaced.+ pub fn is_live_for(&self, url: &str, token: &str) -> bool {+ self.is_connected()+ && self+ .connection_identity+ .read()+ .as_ref()+ .is_some_and(|(u, t)| u == url && t == token)+ }+// -----------------------------------------------------------------------// Connection lifecycle// -----------------------------------------------------------------------@@ -246,7 +277,7 @@ impl SocketManager {// live-session refresh, callers should use `connect_with_session` which// builds a provider via `token_provider_from_config`.let provider = static_token_provider(token.to_string());- self.spawn_loop(url, provider).await+ self.spawn_loop(url, provider, token.to_string()).await}/// Connect using a **live-refresh token provider**.@@ -268,8 +299,8 @@ impl SocketManager {// Validate that a token is available right now before spawning. This// mirrors the empty-token guard in `connect()` and ensures callers// see an immediate error if the session store is empty.- match token_provider() {- Ok(t) if !t.trim().is_empty() => {}+ let token = match token_provider() {+ Ok(t) if !t.trim().is_empty() => t,Ok(_) => {log::error!("[socket] connect_with_provider: refusing to start — provider returned empty token"@@ -282,23 +313,38 @@ impl SocketManager {);return Err(e);}- }- self.spawn_loop(url, token_provider).await+ };+ self.spawn_loop(url, token_provider, token).await}/// Shared spawn path used by both [`connect`] and [`connect_with_provider`].////// Installs the rustls crypto provider, tears down any existing connection,- /// constructs the channel pair, and spawns the background `ws_loop` task.- /// Entry-point-specific validation (empty-token guard, provider pre-check)- /// is done by the callers before this is called.- async fn spawn_loop(&self, url: &str, provider: TokenProvider) -> Result<(), String> {+ /// records the connection's identity, constructs the channel pair, and+ /// spawns the background `ws_loop` task. Entry-point-specific validation+ /// (empty-token guard, provider pre-check) is done by the callers before this+ /// is called, and `token` is the value they validated — it is recorded, not+ /// sent, so `is_live_for` compares against the credential this connection was+ /// actually started with.+ async fn spawn_loop(+ &self,+ url: &str,+ provider: TokenProvider,+ token: String,+ ) -> Result<(), String> {// Ensure the rustls crypto provider is installed (needed for wss:// TLS).// This is a no-op if already installed.let _ = rustls::crypto::ring::default_provider().install_default();self.disconnect().await?;+ // Record the identity this loop will serve so a redundant connect for+ // the same url+token can be skipped (see `is_live_for`). This is the+ // token the caller already validated, not a fresh provider call: the two+ // must agree, or the guard could match on a credential this connection+ // never used.+ *self.connection_identity.write() = Some((url.to_string(), token));+log::info!("[socket] Connecting to {}", url);*self.shared.status.write() = ConnectionStatus::Connecting;@@ -358,6 +404,7 @@ impl SocketManager {*self.shared.status.write() = ConnectionStatus::Disconnected;*self.shared.socket_id.write() = None;*self.shared.error.write() = None;+ *self.connection_identity.write() = None;emit_state_change(&self.shared);log::debug!("[socket] Disconnected");Ok(())diff --git a/src/openhuman/platform/socket/ops.rs b/src/openhuman/platform/socket/ops.rsindex fd98be49bb..72392ab34d 100644--- a/src/openhuman/platform/socket/ops.rs+++ b/src/openhuman/platform/socket/ops.rs@@ -37,26 +37,55 @@ pub async fn disconnect(manager: &SocketManager) -> Result<SocketState, String>Ok(manager.get_state())}+/// Shared body of [`connect_with_session`], with the credential lookup and the+/// workflow-bridge install lifted out so the transaction can be driven directly+/// from tests.+///+/// The `manager.is_live_for` short-circuit is the fix for #6181: the core's+/// bootstrap auto-connect and this RPC both fire on a cold start, roughly two+/// seconds apart, and each used to tear the other's freshly handshaked socket+/// down. When the live connection already serves this exact url+token there is+/// nothing to rebind — no disconnect, no bridge swap, no second EIO session.+async fn connect_with_session_using(+ manager: &SocketManager,+ url: &str,+ token: &str,+ provider: super::token_provider::TokenProvider,+ install_bridge: impl FnOnce(),+) -> Result<SocketState, String> {+ let _rebind = manager.lock_identity_rebind().await;+ if manager.is_live_for(url, token) {+ log::info!(+ "[socket:rpc] connect_with_session — {url} already connected with this session; reusing the live socket"+ );+ return Ok(manager.get_state());+ }+ manager.disconnect().await?;+ install_bridge();+ manager.connect_with_provider(url, provider).await?;+ Ok(manager.get_state())+}+pub async fn connect_with_session(manager: &SocketManager) -> Result<SocketState, String> {log::info!("[socket:rpc] connect_with_session — resolving credentials");let config =std::sync::Arc::new(crate::openhuman::config::rpc::load_config_with_timeout().await?);let api_url = crate::api::config::effective_backend_api_url(&config.api_url);- crate::api::jwt::get_session_token(&config)+ let token = crate::api::jwt::get_session_token(&config).map_err(|e| format!("failed to read session token: {e}"))?.ok_or("no session token stored — user must log in first")?;- let _rebind = manager.lock_identity_rebind().await;- manager.disconnect().await?;- #[cfg(feature = "flows")]- if crate::core::runtime::context::CoreContext::current()- .is_some_and(|context| context.domains().flows)- {- crate::openhuman::flows::medulla_bridge::install(std::sync::Arc::clone(&config));- }- let provider = super::token_provider::token_provider_from_config(config);- manager.connect_with_provider(&api_url, provider).await?;- Ok(manager.get_state())+ let provider =+ super::token_provider::token_provider_from_config(std::sync::Arc::clone(&config));+ connect_with_session_using(manager, &api_url, &token, provider, move || {+ #[cfg(feature = "flows")]+ if crate::core::runtime::context::CoreContext::current()+ .is_some_and(|context| context.domains().flows)+ {+ crate::openhuman::flows::medulla_bridge::install(config);+ }+ })+ .await}#[cfg(test)]diff --git a/src/openhuman/platform/socket/ops_tests.rs b/src/openhuman/platform/socket/ops_tests.rsindex 44eeea60d9..98058cb45a 100644--- a/src/openhuman/platform/socket/ops_tests.rs+++ b/src/openhuman/platform/socket/ops_tests.rs@@ -21,3 +21,173 @@ async fn static_token_connection_clears_identity_state_after_disconnect() {.unwrap();assert!(cleared.load(Ordering::SeqCst));}++// ── Redundant-connect suppression (#6181) ──────────────────────────+use std::sync::atomic::AtomicUsize;+use std::sync::Arc;++use crate::openhuman::platform::socket::token_provider::static_token_provider;+use crate::openhuman::platform::socket::types::ConnectionStatus;++const TOKEN_A: &str = "session-token-a";+const TOKEN_B: &str = "session-token-b";++/// EIO v4 mock that counts accepts and completes enough of the handshake for+/// `SocketManager` to reach `Connected`, then idles. Accepting in a loop is the+/// point: a duplicate connect shows up as a second accept.+async fn spawn_accept_counting_eio_server() -> (Arc<AtomicUsize>, std::net::SocketAddr) {+ use futures_util::{SinkExt, StreamExt};+ use tokio::net::TcpListener;+ use tokio_tungstenite::{accept_async, tungstenite::Message as WsMessage};++ let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");+ let addr = listener.local_addr().expect("addr");+ let accepts = Arc::new(AtomicUsize::new(0));+ let counter = Arc::clone(&accepts);+ tokio::spawn(async move {+ while let Ok((stream, _)) = listener.accept().await {+ counter.fetch_add(1, Ordering::SeqCst);+ tokio::spawn(async move {+ let Ok(ws) = accept_async(stream).await else {+ return;+ };+ let (mut write, mut read) = ws.split();+ // Long ping intervals so nothing reconnects on its own mid-test.+ let open = r#"0{"sid":"mock-eio-sid","upgrades":[],"pingInterval":30000,"pingTimeout":30000}"#;+ let _ = write.send(WsMessage::Text(open.into())).await;+ let _ = read.next().await; // client SIO CONNECT+ let _ = write+ .send(WsMessage::Text(r#"40{"sid":"mock-sio-sid"}"#.into()))+ .await;+ while let Some(Ok(_)) = read.next().await {}+ });+ }+ });+ (accepts, addr)+}++async fn wait_for_connected(manager: &SocketManager) {+ for _ in 0..200 {+ if manager.is_connected() {+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;+ }+ panic!("socket never reached Connected");+}++/// Wait out the window in which a duplicate connect would reach the server.+///+/// `connect_with_provider` returns as soon as the background loop is spawned, so+/// reading the accept counter straight afterwards would pass even when a second+/// session is on its way — a vacuous assertion. Returns early the moment a+/// second accept does show up, so the fix's happy path is the only one that pays+/// the full wait.+async fn settle_for_a_second_accept(accepts: &AtomicUsize) {+ for _ in 0..40 {+ if accepts.load(Ordering::SeqCst) > 1 {+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;+ }+}++/// Stand-in for the core's bootstrap auto-connect (`spawn_socket_auto_connect`).+async fn bootstrap_auto_connect(manager: &SocketManager, url: &str, token: &str) {+ manager+ .connect_with_provider(url, static_token_provider(token.to_string()))+ .await+ .unwrap();+ wait_for_connected(manager).await;+}++/// #6181: on a cold start the core auto-connects and the renderer's+/// `socket_connect_with_session` RPC follows a couple of seconds later with the+/// same backend URL and the same stored token. The second one must reuse the+/// live socket rather than tear it down and open a fresh EIO session.+#[tokio::test]+async fn a_redundant_session_connect_reuses_the_live_socket() {+ let (accepts, addr) = spawn_accept_counting_eio_server().await;+ let url = format!("http://{addr}");+ let manager = SocketManager::new();++ bootstrap_auto_connect(&manager, &url, TOKEN_A).await;++ let rebound = AtomicBool::new(false);+ let state = connect_with_session_using(+ &manager,+ &url,+ TOKEN_A,+ static_token_provider(TOKEN_A.to_string()),+ || rebound.store(true, Ordering::SeqCst),+ )+ .await+ .unwrap();++ settle_for_a_second_accept(&accepts).await;+ assert_eq!(+ accepts.load(Ordering::SeqCst),+ 1,+ "a redundant connect for an identical identity opened a duplicate EIO session"+ );+ assert!(+ !rebound.load(Ordering::SeqCst),+ "identity rebind ran for a session that was already live"+ );+ // The caller also gets the live socket's state back, not the `Connecting`+ // of a handshake that has only just been kicked off.+ assert_eq!(state.status, ConnectionStatus::Connected);+}++/// The other half of the guard: an account switch keeps the same backend URL but+/// arrives with a different token, and must still disconnect, rebind the+/// identity-bound workflow plane, and reconnect.+#[tokio::test]+async fn a_session_connect_with_a_different_token_still_rebinds() {+ let (accepts, addr) = spawn_accept_counting_eio_server().await;+ let url = format!("http://{addr}");+ let manager = SocketManager::new();++ bootstrap_auto_connect(&manager, &url, TOKEN_A).await;++ let rebound = AtomicBool::new(false);+ connect_with_session_using(+ &manager,+ &url,+ TOKEN_B,+ static_token_provider(TOKEN_B.to_string()),+ || rebound.store(true, Ordering::SeqCst),+ )+ .await+ .unwrap();+ wait_for_connected(&manager).await;++ assert!(+ rebound.load(Ordering::SeqCst),+ "a new session token must still rebind the identity-bound workflow plane"+ );+ assert_eq!(+ accepts.load(Ordering::SeqCst),+ 2,+ "a new session token must open a fresh EIO session"+ );+}++/// `is_live_for` is identity-scoped, not merely "am I connected": a different+/// backend URL is a different identity, and a disconnect clears the record so a+/// later connect is never skipped against a dead socket.+#[tokio::test]+async fn is_live_for_is_scoped_to_url_and_token_and_cleared_on_disconnect() {+ let (_accepts, addr) = spawn_accept_counting_eio_server().await;+ let url = format!("http://{addr}");+ let manager = SocketManager::new();++ bootstrap_auto_connect(&manager, &url, TOKEN_A).await;++ assert!(manager.is_live_for(&url, TOKEN_A));+ assert!(!manager.is_live_for(&url, TOKEN_B));+ assert!(!manager.is_live_for("http://127.0.0.1:1", TOKEN_A));++ manager.disconnect().await.unwrap();+ assert!(!manager.is_live_for(&url, TOKEN_A));+}