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): restore the workflow bridge on the reuse path, track token refresh
M3gA-Mind75df1921fb15
diff --git a/src/core/runtime/services.rs b/src/core/runtime/services.rsindex d240b5e59e..40df77b94e 100644--- a/src/core/runtime/services.rs+++ b/src/core/runtime/services.rs@@ -533,8 +533,18 @@ pub fn spawn_socket_auto_connect(// 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) {+ // The socket is reusable, the bridge is not: it is pinned to the+ // `Config` resolved above, which a workspace switch invalidates.+ // `set_workflow_bridge` re-advertises over a live socket by+ // design, so reinstall and skip only the handshake.+ #[cfg(feature = "flows")]+ if _flows_enabled {+ crate::openhuman::flows::medulla_bridge::install(std::sync::Arc::clone(+ &config,+ ));+ }log::info!(- "[socket] Auto-connect: {api_url} already connected with this session — nothing to do"+ "[socket] Auto-connect: {api_url} already connected with this session — refreshed the workflow bridge, kept the socket");return;}diff --git a/src/openhuman/platform/socket/event_handlers_tests.rs b/src/openhuman/platform/socket/event_handlers_tests.rsindex 9c19726851..5ede145042 100644--- a/src/openhuman/platform/socket/event_handlers_tests.rs+++ b/src/openhuman/platform/socket/event_handlers_tests.rs@@ -9,6 +9,7 @@ fn make_shared() -> Arc<SharedState> {status: RwLock::new(ConnectionStatus::Disconnected),socket_id: RwLock::new(None),error: RwLock::new(None),+ connection_identity: RwLock::new(None),})}diff --git a/src/openhuman/platform/socket/manager.rs b/src/openhuman/platform/socket/manager.rsindex 176eedb7c7..9db56a997b 100644--- a/src/openhuman/platform/socket/manager.rs+++ b/src/openhuman/platform/socket/manager.rs@@ -62,6 +62,13 @@ pub(super) struct SharedState {/// (e.g. "backend redirected ws→wss; update BACKEND_URL"). Cleared on every/// successful handshake and on disconnect.pub(super) error: RwLock<Option<String>>,+ /// `(url, token)` the background loop is currently authenticating with, and+ /// the reason it lives here rather than on the handle: `ws_loop` re-reads the+ /// token provider before **every** attempt, so a refresh mid-session would+ /// leave a manager-side copy naming a credential this socket no longer uses.+ /// Seeded by `spawn_loop` and rewritten by the loop on each attempt; cleared+ /// on disconnect. Read by [`SocketManager::is_live_for`].+ pub(super) connection_identity: RwLock<Option<(String, String)>>,}/// The connection's readiness flag, guarded by a lock so a reader can hold the@@ -170,13 +177,6 @@ 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 {@@ -190,12 +190,12 @@ impl SocketManager {status: RwLock::new(ConnectionStatus::Disconnected),socket_id: RwLock::new(None),error: RwLock::new(None),+ connection_identity: RwLock::new(None),}),emit_tx: tokio::sync::Mutex::new(None),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),}}@@ -242,10 +242,14 @@ impl SocketManager {/// 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.+ /// socket is still replaced. The token compared against is the one+ /// `ws_loop` used for its most recent attempt, not the one this manager was+ /// handed at spawn — a provider that refreshes the session mid-loop keeps+ /// matching instead of forcing a pointless reconnect.pub fn is_live_for(&self, url: &str, token: &str) -> bool {self.is_connected()&& self+ .shared.connection_identity.read().as_ref()@@ -338,12 +342,13 @@ impl SocketManager {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));+ // Seed 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. `ws_loop` rewrites it before every attempt, so a token refreshed+ // mid-session replaces this seed rather than going stale behind it.+ *self.shared.connection_identity.write() = Some((url.to_string(), token));log::info!("[socket] Connecting to {}", url);@@ -404,7 +409,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;+ *self.shared.connection_identity.write() = None;emit_state_change(&self.shared);log::debug!("[socket] Disconnected");Ok(())diff --git a/src/openhuman/platform/socket/manager_tests.rs b/src/openhuman/platform/socket/manager_tests.rsindex 41ab5b8814..03c6187926 100644--- a/src/openhuman/platform/socket/manager_tests.rs+++ b/src/openhuman/platform/socket/manager_tests.rs@@ -383,6 +383,7 @@ fn emit_state_change_is_safe_to_call_on_empty_shared() {status: RwLock::new(ConnectionStatus::Connecting),socket_id: RwLock::new(None),error: RwLock::new(None),+ connection_identity: RwLock::new(None),};// Must not panic even with all default state.emit_state_change(&shared);@@ -396,6 +397,7 @@ fn emit_server_event_is_safe_without_subscribers() {status: RwLock::new(ConnectionStatus::Connected),socket_id: RwLock::new(Some("x".into())),error: RwLock::new(None),+ connection_identity: RwLock::new(None),};// Pure logging — must not touch state or panic.emit_server_event(&shared, "any.event", json!({}));diff --git a/src/openhuman/platform/socket/ops.rs b/src/openhuman/platform/socket/ops.rsindex 72392ab34d..9e5d8fe8c5 100644--- a/src/openhuman/platform/socket/ops.rs+++ b/src/openhuman/platform/socket/ops.rs@@ -45,7 +45,15 @@ pub async fn disconnect(manager: &SocketManager) -> Result<SocketState, String>/// 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.+/// no second EIO session to open.+///+/// The socket is reusable; the workflow bridge is not. It is pinned to a+/// `Config` that a workspace switch invalidates, and `connect_static` clears it+/// outright while leaving a matching connection identity behind — so skipping+/// `install_bridge` on the reuse path would leave the workflow plane pointing at+/// a stale workspace, or disabled entirely. `set_workflow_bridge` re-advertises+/// over an already-`ready` socket by design, so the install runs on both paths+/// and only the handshake is skipped.async fn connect_with_session_using(manager: &SocketManager,url: &str,@@ -55,6 +63,7 @@ async fn connect_with_session_using() -> Result<SocketState, String> {let _rebind = manager.lock_identity_rebind().await;if manager.is_live_for(url, token) {+ install_bridge();log::info!("[socket:rpc] connect_with_session — {url} already connected with this session; reusing the live socket");diff --git a/src/openhuman/platform/socket/ops_tests.rs b/src/openhuman/platform/socket/ops_tests.rsindex 98058cb45a..3b0fa42ae2 100644--- a/src/openhuman/platform/socket/ops_tests.rs+++ b/src/openhuman/platform/socket/ops_tests.rs@@ -26,7 +26,7 @@ async fn static_token_connection_clears_identity_state_after_disconnect() {use std::sync::atomic::AtomicUsize;use std::sync::Arc;-use crate::openhuman::platform::socket::token_provider::static_token_provider;+use crate::openhuman::platform::socket::token_provider::{static_token_provider, TokenProvider};use crate::openhuman::platform::socket::types::ConnectionStatus;const TOKEN_A: &str = "session-token-a";@@ -66,6 +66,50 @@ async fn spawn_accept_counting_eio_server() -> (Arc<AtomicUsize>, std::net::Sock(accepts, addr)}+/// EIO v4 mock that completes one handshake and then holds the connection open+/// until the returned sender says to hang up, so a test can decide exactly when+/// the loop is forced to reconnect. Later connections are held indefinitely.+async fn spawn_server_that_hangs_up_on_cue(+) -> (std::net::SocketAddr, tokio::sync::watch::Sender<bool>) {+ 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 (hang_up, rx) = tokio::sync::watch::channel(false);+ tokio::spawn(async move {+ let mut first = true;+ while let Ok((stream, _)) = listener.accept().await {+ let mut rx = rx.clone();+ let hang_up_this_one = std::mem::take(&mut first);+ tokio::spawn(async move {+ let Ok(ws) = accept_async(stream).await else {+ return;+ };+ let (mut write, mut read) = ws.split();+ 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;+ if hang_up_this_one {+ while rx.changed().await.is_ok() {+ if *rx.borrow() {+ break;+ }+ }+ let _ = write.close().await;+ return;+ }+ while let Some(Ok(_)) = read.next().await {}+ });+ }+ });+ (addr, hang_up)+}+async fn wait_for_connected(manager: &SocketManager) {for _ in 0..200 {if manager.is_connected() {@@ -113,13 +157,13 @@ async fn a_redundant_session_connect_reuses_the_live_socket() {bootstrap_auto_connect(&manager, &url, TOKEN_A).await;- let rebound = AtomicBool::new(false);+ let bridge_installed = 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),+ || bridge_installed.store(true, Ordering::SeqCst),).await.unwrap();@@ -130,13 +174,98 @@ async fn a_redundant_session_connect_reuses_the_live_socket() {1,"a redundant connect for an identical identity opened a duplicate EIO session");+ // The caller 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);+ // Reusing the socket must not skip the bridge: it is pinned to a `Config`,+ // and `connect_static` can have cleared it while leaving a matching identity+ // behind, so the workflow plane would be left stale or disabled.assert!(- !rebound.load(Ordering::SeqCst),- "identity rebind ran for a session that was already live"+ bridge_installed.load(Ordering::SeqCst),+ "reusing the socket skipped the workflow-bridge install");- // 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 bridge half of the reuse path, end to end through the operation that+/// clears it: `openhuman.socket_connect` disables the identity-bound workflow+/// plane and leaves a matching connection identity behind, so a following+/// `connect_with_session` for the same url+token must still restore it.+#[tokio::test]+async fn a_reused_socket_still_restores_a_bridge_a_static_connect_cleared() {+ let (accepts, addr) = spawn_accept_counting_eio_server().await;+ let url = format!("http://{addr}");+ let manager = SocketManager::new();++ let cleared = AtomicBool::new(false);+ connect_static_using(&manager, &url, TOKEN_A, || {+ cleared.store(true, Ordering::SeqCst)+ })+ .await+ .unwrap();+ wait_for_connected(&manager).await;+ assert!(cleared.load(Ordering::SeqCst));++ let bridge_installed = AtomicBool::new(false);+ connect_with_session_using(+ &manager,+ &url,+ TOKEN_A,+ static_token_provider(TOKEN_A.to_string()),+ || bridge_installed.store(true, Ordering::SeqCst),+ )+ .await+ .unwrap();++ settle_for_a_second_accept(&accepts).await;+ assert!(+ bridge_installed.load(Ordering::SeqCst),+ "the workflow plane stayed disabled after a static connect cleared it"+ );+ assert_eq!(+ accepts.load(Ordering::SeqCst),+ 1,+ "restoring the bridge should not cost a fresh EIO session"+ );+}++/// `ws_loop` re-reads the token provider before every attempt, so a session+/// refreshed mid-loop leaves the socket authenticated with a token the manager+/// was never handed. The recorded identity has to follow, or the next session+/// connect tears down a perfectly healthy socket.+#[tokio::test]+async fn a_token_refreshed_mid_loop_updates_the_recorded_identity() {+ let (addr, hang_up) = spawn_server_that_hangs_up_on_cue().await;+ let url = format!("http://{addr}");+ let manager = SocketManager::new();++ // A provider whose answer changes under the loop, exactly as a live session+ // refresh does.+ let refreshed = Arc::new(AtomicBool::new(false));+ let seen = Arc::clone(&refreshed);+ let provider: TokenProvider = Arc::new(move || {+ Ok(if seen.load(Ordering::SeqCst) {+ TOKEN_B.to_string()+ } else {+ TOKEN_A.to_string()+ })+ });++ manager.connect_with_provider(&url, provider).await.unwrap();+ wait_for_connected(&manager).await;+ assert!(manager.is_live_for(&url, TOKEN_A));++ // Refresh the session, then drop the socket so the loop reconnects with the+ // new token.+ refreshed.store(true, Ordering::SeqCst);+ let _ = hang_up.send(true);++ for _ in 0..200 {+ if manager.is_live_for(&url, TOKEN_B) {+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;+ }+ panic!("the recorded identity still names the pre-refresh token after a reconnect");}/// The other half of the guard: an account switch keeps the same backend URL but@@ -150,20 +279,20 @@ async fn a_session_connect_with_a_different_token_still_rebinds() {bootstrap_auto_connect(&manager, &url, TOKEN_A).await;- let rebound = AtomicBool::new(false);+ let bridge_installed = AtomicBool::new(false);connect_with_session_using(&manager,&url,TOKEN_B,static_token_provider(TOKEN_B.to_string()),- || rebound.store(true, Ordering::SeqCst),+ || bridge_installed.store(true, Ordering::SeqCst),).await.unwrap();wait_for_connected(&manager).await;assert!(- rebound.load(Ordering::SeqCst),+ bridge_installed.load(Ordering::SeqCst),"a new session token must still rebind the identity-bound workflow plane");assert_eq!(diff --git a/src/openhuman/platform/socket/ws_loop_part_01.rs b/src/openhuman/platform/socket/ws_loop_part_01.rsindex b1ce3cf8a3..fb8e1cd13e 100644--- a/src/openhuman/platform/socket/ws_loop_part_01.rs+++ b/src/openhuman/platform/socket/ws_loop_part_01.rs@@ -145,6 +145,12 @@ pub(super) async fn ws_loop("[socket] Attempting connection (token_len={})...",token.len());+ // Record the credential this attempt actually authenticates with. The+ // provider is re-read every iteration, so a session refreshed mid-loop+ // would otherwise leave `SocketManager::is_live_for` comparing against+ // the token this loop was spawned with and tearing down a healthy socket+ // on the next connect (#6181).+ *shared.connection_identity.write() = Some((url.clone(), token.clone()));*shared.status.write() = ConnectionStatus::Connecting;emit_state_change(&shared);diff --git a/src/openhuman/platform/socket/ws_loop_tests.rs b/src/openhuman/platform/socket/ws_loop_tests.rsindex d85a28c7da..357f3115f6 100644--- a/src/openhuman/platform/socket/ws_loop_tests.rs+++ b/src/openhuman/platform/socket/ws_loop_tests.rs@@ -14,6 +14,7 @@ fn make_shared() -> Arc<SharedState> {status: RwLock::new(ConnectionStatus::Connected),socket_id: RwLock::new(None),error: RwLock::new(None),+ connection_identity: RwLock::new(None),})}