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): let the core say whether its reconnect loop is running
Shanucf90752f27af
diff --git a/app/src/components/__tests__/ConnectionIndicator.test.tsx b/app/src/components/__tests__/ConnectionIndicator.test.tsxindex 80ba507fe4..d06b5de7d6 100644--- a/app/src/components/__tests__/ConnectionIndicator.test.tsx+++ b/app/src/components/__tests__/ConnectionIndicator.test.tsx@@ -111,6 +111,23 @@ describe('ConnectionIndicator', () => {expect(container.querySelector('.animate-pulse')).toBeNull();});+ it('stays green on a server error event, which leaves the hosted link live', () => {+ const { container } = renderWithProviders(<ConnectionIndicator />, {+ preloadedState: {+ connectivity: {+ internet: 'online',+ core: 'reachable',+ backend: 'connected',+ hosted: 'error',+ lastError: { hosted: 'boom' },+ },+ socket: { byUser: {} },+ },+ });+ expect(screen.getByText('Connected')).toBeInTheDocument();+ expect(container.querySelector('.bg-sage-500')).not.toBeNull();+ });+it("stays green when the core's hosted link is simply not running (signed out / local)", () => {const { container } = renderWithProviders(<ConnectionIndicator />, {preloadedState: {diff --git a/app/src/services/__tests__/coreHealthMonitor.test.ts b/app/src/services/__tests__/coreHealthMonitor.test.tsindex 1394201124..d35c7189de 100644--- a/app/src/services/__tests__/coreHealthMonitor.test.ts+++ b/app/src/services/__tests__/coreHealthMonitor.test.ts@@ -279,9 +279,29 @@ describe('hostedStateFromDiag', () => {const { hostedStateFromDiag } = await import('../coreHealthMonitor');for (const socket_state of ['connected', 'connecting', 'reconnecting', 'error']) {expect(hostedStateFromDiag({ socket_state })).toEqual({ value: socket_state });+ expect(hostedStateFromDiag({ socket_state, socket_loop_active: true })).toEqual({+ value: socket_state,+ });}});+ it('lets the core decide who is retrying via socket_loop_active (#6256)', async () => {+ const { hostedStateFromDiag } = await import('../coreHealthMonitor');+ // Loop alive + namespace closed by the server: an outage worth showing.+ expect(hostedStateFromDiag({ socket_state: 'disconnected', socket_loop_active: true })).toEqual(+ { value: 'disconnected' }+ );+ // Loop not running: nobody is retrying, whatever the last status said.+ expect(+ hostedStateFromDiag({ socket_state: 'disconnected', socket_loop_active: false })+ ).toEqual({ value: 'unknown' });+ expect(hostedStateFromDiag({ socket_state: 'connected', socket_loop_active: false })).toEqual({+ value: 'unknown',+ });+ // A core that predates the flag: `disconnected` stays `unknown` (legacy inference).+ expect(hostedStateFromDiag({ socket_state: 'disconnected' })).toEqual({ value: 'unknown' });+ });+it('peels the handler envelope and the log envelope the RPC layer adds (#6080)', async () => {const { hostedStateFromDiag } = await import('../coreHealthMonitor');// Bare handler answer.diff --git a/app/src/services/coreHealthMonitor.ts b/app/src/services/coreHealthMonitor.tsindex 411f697638..61311f29d6 100644--- a/app/src/services/coreHealthMonitor.ts+++ b/app/src/services/coreHealthMonitor.ts@@ -33,6 +33,7 @@ const HOSTED_STATES: ReadonlySet<string> = new Set<HostedState>(['connected','connecting','reconnecting',+ 'disconnected','error',]);@@ -58,21 +59,35 @@ function unwrapDiag(reply: unknown): Record<string, unknown> {}/**- * Map a `connectivity_diag` reply onto the hosted channel. `disconnected` and- * `uninitialized` both mean the core's reconnect loop is not running (signed- * out, local session, early boot), which is not an outage — they land on- * `unknown`, as does a reply that carries no `socket_state` at all. The core- * reports `reconnecting` between retries, so a link that is down but being- * retried never collapses into that bucket.+ * Map a `connectivity_diag` reply onto the hosted channel.+ *+ * The core says whether anyone is retrying: `socket_loop_active` is `false`+ * when its reconnect loop is not running (never connected, signed out, local+ * session, stopped after a terminal failure), and that is `unknown` here — not+ * an outage — whatever `socket_state` says. While the loop is alive the status+ * passes through verbatim, including `disconnected`, which then means the+ * server closed the Socket.IO namespace on a transport it left open. A reply+ * with no `socket_state` is `unknown` too.+ *+ * A core that predates `socket_loop_active` cannot say who is retrying, so+ * its `disconnected` — most often a loop that is not running — stays+ * `unknown` rather than raising a false outage; every other status is taken+ * as is, because the loop reports `reconnecting` between retries.*/export function hostedStateFromDiag(reply: unknown): { value: HostedState; error?: string } {const record = unwrapDiag(reply);const socketState = record.socket_state;+ const loopActive = record.socket_loop_active;const lastError = record.last_ws_error;- const value: HostedState =- typeof socketState === 'string' && HOSTED_STATES.has(socketState)- ? (socketState as HostedState)- : 'unknown';+ let value: HostedState = 'unknown';+ if (+ loopActive !== false &&+ typeof socketState === 'string' &&+ HOSTED_STATES.has(socketState) &&+ !(loopActive === undefined && socketState === 'disconnected')+ ) {+ value = socketState as HostedState;+ }return typeof lastError === 'string' && lastError.length > 0? { value, error: lastError }: { value };@@ -107,6 +122,7 @@ function schedule(): void {// (addresses @coderabbitai on coreHealthMonitor.ts:46)// A degraded hosted link selects the fast cadence too, so its recovery is// reflected within seconds rather than at the next 30s heartbeat (#6256).+ // `error` is not degraded (live transport), so it never pins the fast poll.const { core, hosted } = store.getState().connectivity;const isDegraded = consecutiveFails > 0 || core !== 'reachable' || isHostedDegraded(hosted);const interval = isDegraded ? DEGRADED_INTERVAL_MS : HEALTHY_INTERVAL_MS;diff --git a/app/src/store/__tests__/connectivitySelectors.test.ts b/app/src/store/__tests__/connectivitySelectors.test.tsindex 7de6e1cfd3..2a47e57413 100644--- a/app/src/store/__tests__/connectivitySelectors.test.ts+++ b/app/src/store/__tests__/connectivitySelectors.test.ts@@ -40,10 +40,17 @@ describe('selectBlockingState', () => {expect(selectBlockingState(make({ backend: 'connecting' }))).toBe('backend-only');});- it("returns hosted-degraded when only the core's hosted link is down and retrying (#6256)", () => {+ it("returns hosted-degraded when only the core's hosted link is down while its loop is alive (#6256)", () => {expect(selectBlockingState(make({ hosted: 'connecting' }))).toBe('hosted-degraded');expect(selectBlockingState(make({ hosted: 'reconnecting' }))).toBe('hosted-degraded');- expect(selectBlockingState(make({ hosted: 'error' }))).toBe('hosted-degraded');+ // Server closed the namespace on a transport it left open: no events flow.+ expect(selectBlockingState(make({ hosted: 'disconnected' }))).toBe('hosted-degraded');+ });++ it('does not read a server error event on a live link as an outage', () => {+ // The core keeps the transport open and emits keep working after a server+ // `error` event, so "reconnecting" copy would be wrong here.+ expect(selectBlockingState(make({ hosted: 'error' }))).toBe('ok');});it('treats a hosted link that is not running as healthy, not degraded', () => {@@ -72,7 +79,8 @@ describe('isHostedDegraded', () => {it('is true only for a link that is down and being retried', () => {expect(isHostedDegraded('connecting')).toBe(true);expect(isHostedDegraded('reconnecting')).toBe(true);- expect(isHostedDegraded('error')).toBe(true);+ expect(isHostedDegraded('disconnected')).toBe(true);+ expect(isHostedDegraded('error')).toBe(false);expect(isHostedDegraded('connected')).toBe(false);expect(isHostedDegraded('unknown')).toBe(false);expect(isHostedDegraded(undefined)).toBe(false);diff --git a/app/src/store/__tests__/connectivitySlice.test.ts b/app/src/store/__tests__/connectivitySlice.test.tsindex b1eb038c7a..0afdd1e827 100644--- a/app/src/store/__tests__/connectivitySlice.test.ts+++ b/app/src/store/__tests__/connectivitySlice.test.ts@@ -80,6 +80,15 @@ describe('connectivitySlice', () => {state = connectivityReducer(state, setHosted({ value: 'error', error: 'server error' }));expect(state.lastError.hosted).toBe('server error');+ // Namespace closed by the server on a live transport: stored like any+ // other degraded reading.+ state = connectivityReducer(+ state,+ setHosted({ value: 'disconnected', error: 'io server disconnect' })+ );+ expect(state.hosted).toBe('disconnected');+ expect(state.lastError.hosted).toBe('io server disconnect');+// Recovery clears it…state = connectivityReducer(state, setHosted({ value: 'connected' }));expect(state.hosted).toBe('connected');diff --git a/app/src/store/connectivitySelectors.ts b/app/src/store/connectivitySelectors.tsindex 1b285aa594..37507b8a42 100644--- a/app/src/store/connectivitySelectors.ts+++ b/app/src/store/connectivitySelectors.ts@@ -10,11 +10,12 @@ import { RootState } from './index';* - `backend-only` : the renderer's Socket.IO link to the core is down but* the core is alive — the app stays usable, we just* show a soft banner.- * - `hosted-degraded` : the core's own link to the hosted backend is down and- * being retried. Chat keeps working (it rides the local- * core bridge); webhooks, Composio triggers, managed-DM- * routing and hosted-brain runs pause until it heals.- * Soft chip only (#6256).+ * - `hosted-degraded` : the core's own link to the hosted backend is down+ * while its loop is alive — being retried, or its+ * namespace closed by the server. Chat keeps working+ * (it rides the local core bridge); webhooks, Composio+ * triggers, managed-DM routing and hosted-brain runs+ * pause until it heals. Soft chip only (#6256).* - `ok` : everything healthy.*/type BlockingState =@@ -25,12 +26,16 @@ type BlockingState =| 'ok';/**- * A hosted link that is down *and being retried*. `unknown` — the core's- * reconnect loop is not running (signed out, local session, early boot) — is- * deliberately excluded: it is the absence of a link, not an outage.+ * A hosted link that is down while the core's loop is alive: being retried+ * (`connecting` / `reconnecting`), or its Socket.IO namespace closed by the+ * server (`disconnected`). Two states are deliberately excluded: `unknown`,+ * the loop not running at all (signed out, local session, early boot) — the+ * absence of a link, not an outage — and `error`, a server `error` event on a+ * transport that stays live and keeps emitting, which is not a reconnect and+ * must not read as one.*/export const isHostedDegraded = (hosted: HostedState | undefined): boolean =>- hosted === 'connecting' || hosted === 'reconnecting' || hosted === 'error';+ hosted === 'connecting' || hosted === 'reconnecting' || hosted === 'disconnected';export const selectBlockingState = (s: RootState): BlockingState => {if (s.connectivity.internet === 'offline') return 'internet-offline';diff --git a/app/src/store/connectivitySlice.ts b/app/src/store/connectivitySlice.tsindex f365d0ae5b..4afe3c0a0f 100644--- a/app/src/store/connectivitySlice.ts+++ b/app/src/store/connectivitySlice.ts@@ -27,11 +27,25 @@ export type CoreState = 'reachable' | 'unreachable' | 'unknown';export type BackendState = 'connected' | 'disconnected' | 'connecting';/*** Mirrors the core's `ConnectionStatus` as reported by- * `connectivity_diag.socket_state`, minus `disconnected`, which — like an- * uninitialised manager — collapses to `unknown` because it means the- * reconnect loop is not running.+ * `connectivity_diag.socket_state` while its reconnect loop is running+ * (`socket_loop_active`); `unknown` is the loop not running at all.+ *+ * - `connecting` / `reconnecting` — down and being retried (degraded).+ * - `disconnected` — the loop is alive but the server closed the Socket.IO+ * namespace without closing the transport, so no events flow and no+ * automatic reconnect happens (degraded). Never reported by a core that+ * predates `socket_loop_active`: there it collapses to `unknown`.+ * - `error` — the server sent an `error` event on a transport that stays+ * live and keeps emitting; not an outage, so it gets no chip until it has+ * its own presentation. Stored so the state is observable.*/-export type HostedState = 'connected' | 'connecting' | 'reconnecting' | 'error' | 'unknown';+export type HostedState =+ | 'connected'+ | 'connecting'+ | 'reconnecting'+ | 'disconnected'+ | 'error'+ | 'unknown';export interface ConnectivityState {internet: InternetState;diff --git a/crates/openhuman-core/src/platform/connectivity/rpc.rs b/crates/openhuman-core/src/platform/connectivity/rpc.rsindex b659e8f92e..1b0cb01c4a 100644--- a/crates/openhuman-core/src/platform/connectivity/rpc.rs+++ b/crates/openhuman-core/src/platform/connectivity/rpc.rs@@ -36,6 +36,14 @@ pub struct ConnectivityDiagResponse {/// Last user-visible socket error surfaced via `SocketManager`'s/// `SharedState.error` slot. `None` when no error pending.pub last_ws_error: Option<String>,+ /// Whether the core's backend reconnect loop is running. `false` means+ /// nobody is retrying — never connected, signed out, a local session, or+ /// stopped after a terminal failure — and the frontend shows no outage+ /// for it. `true` with any `socket_state` other than `connected` is a+ /// link that is down and being retried, or a live transport whose+ /// Socket.IO namespace the server closed (#6256). `false` when the+ /// SocketManager is not bootstrapped.+ pub socket_loop_active: bool,/// Sidecar process id — i.e. the PID of *this* core binary handling the/// RPC. The frontend matches this against the PID it started so it can/// detect a stale-process scenario where the bound port belongs to an@@ -460,10 +468,10 @@ fn resolve_listen_port() -> u16 {DEFAULT_CORE_PORT}-/// Snapshot the backend socket state. Returns `("uninitialized", None)`-/// when the SocketManager singleton hasn't been registered yet — typical-/// during early startup or in unit tests.-fn snapshot_socket_state() -> (String, Option<String>) {+/// Snapshot the backend socket state as `(status, last error, loop active)`.+/// Returns `("uninitialized", None, false)` when the SocketManager singleton+/// hasn't been registered yet — typical during early startup or in unit tests.+fn snapshot_socket_state() -> (String, Option<String>, bool) {match global_socket_manager() {Some(mgr) => {let state = mgr.get_state();@@ -475,9 +483,9 @@ fn snapshot_socket_state() -> (String, Option<String>) {.ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_else(|| "unknown".to_string());- (status_value, state.error)+ (status_value, state.error, mgr.is_loop_active())}- None => ("uninitialized".to_string(), None),+ None => ("uninitialized".to_string(), None, false),}}@@ -486,12 +494,13 @@ fn snapshot_socket_state() -> (String, Option<String>) {pub fn snapshot() -> ConnectivityDiagResponse {let listen_port = resolve_listen_port();let listen_port_in_use = is_port_in_use(listen_port);- let (socket_state, last_ws_error) = snapshot_socket_state();+ let (socket_state, last_ws_error, socket_loop_active) = snapshot_socket_state();let sidecar_pid = Some(std::process::id());ConnectivityDiagResponse {socket_state,last_ws_error,+ socket_loop_active,sidecar_pid,listen_port,listen_port_in_use,diff --git a/crates/openhuman-core/src/platform/connectivity/rpc_tests.rs b/crates/openhuman-core/src/platform/connectivity/rpc_tests.rsindex 5a7217a098..259066b9f8 100644--- a/crates/openhuman-core/src/platform/connectivity/rpc_tests.rs+++ b/crates/openhuman-core/src/platform/connectivity/rpc_tests.rs@@ -323,9 +323,10 @@ fn snapshot_socket_state_is_uninitialized_without_manager() {);return;}- let (state, err) = snapshot_socket_state();+ let (state, err, loop_active) = snapshot_socket_state();assert_eq!(state, "uninitialized");assert!(err.is_none());+ assert!(!loop_active, "no manager means nobody is retrying");}#[test]@@ -431,6 +432,11 @@ fn snapshot_populates_all_fields() {!snap.socket_state.is_empty(),"socket_state should be non-empty");+ // A manager that was never connected (or no manager at all) cannot have a+ // live loop behind it; `connected` without a loop would be a contradiction.+ if snap.socket_state == "uninitialized" || snap.socket_state == "disconnected" {+ assert!(!snap.socket_loop_active || snap.socket_state == "disconnected");+ }}#[tokio::test]@@ -446,6 +452,12 @@ async fn diag_returns_serializable_payload() {let result = json.get("result").expect("result envelope key present");let diag = result.get("diag").expect("diag key present under result");assert!(diag.get("socket_state").is_some());+ assert!(+ diag.get("socket_loop_active")+ .and_then(|v| v.as_bool())+ .is_some(),+ "socket_loop_active must be a bool on the wire (#6256)"+ );assert!(diag.get("listen_port").is_some());assert!(diag.get("listen_port_in_use").is_some());}diff --git a/crates/openhuman-core/src/platform/socket/README.md b/crates/openhuman-core/src/platform/socket/README.mdindex 3213956704..78fa3d46f0 100644--- a/crates/openhuman-core/src/platform/socket/README.md+++ b/crates/openhuman-core/src/platform/socket/README.md@@ -9,7 +9,7 @@ Persistent, Rust-native Socket.IO client to the OpenHuman backend. The `socket`- Follow HTTP 3xx redirects during the upgrade (up to 3 hops) so a `http://`-configured `BACKEND_URL` behind a TLS-forcing edge connects cleanly; pin the resolved URL for subsequent reconnects and surface a one-shot "stale BACKEND_URL" warning for permanent redirects.- Refresh the session token before every reconnect via a `TokenProvider` callback (live re-read of the profile store) instead of caching a single token — fixes the "Invalid token" retry storm (#2892 / TAURI-RUST-9C).- Fast-fail on a definitively dead token (server "Invalid token" + no fresher token available) rather than burning the whole backoff budget.-- Track connection status / socket id / last user-visible error in shared state and expose it via RPC. Between attempts the loop reports `Reconnecting`; `Disconnected` means the loop is not running (signed out, session expired, shutdown), which is what the frontend's connectivity chip relies on to show "down, retrying" and stay quiet for "never wanted" (#6256).+- Track connection status / socket id / last user-visible error / loop liveness (`SharedState::loop_active`, `SocketManager::is_loop_active`, surfaced as `connectivity_diag.socket_loop_active`) in shared state and expose it via RPC. Between attempts the loop reports `Reconnecting`; `Disconnected` means the loop is not running (signed out, session expired, shutdown), which is what the frontend's connectivity chip relies on to show "down, retrying" and stay quiet for "never wanted" (#6256).- Parse inbound Socket.IO EVENT frames and publish them as `DomainEvent`s for other domains to consume; emit outbound events.- Suppress reconnect-storm Sentry noise: route only the 5th consecutive failure through the observability classifier (which demotes offline/transport shapes to a breadcrumb), keep all other retries at `warn`.diff --git a/crates/openhuman-core/src/platform/socket/event_handlers_tests.rs b/crates/openhuman-core/src/platform/socket/event_handlers_tests.rsindex 5ede145042..7f8fb3bad5 100644--- a/crates/openhuman-core/src/platform/socket/event_handlers_tests.rs+++ b/crates/openhuman-core/src/platform/socket/event_handlers_tests.rs@@ -10,6 +10,7 @@ fn make_shared() -> Arc<SharedState> {socket_id: RwLock::new(None),error: RwLock::new(None),connection_identity: RwLock::new(None),+ loop_active: std::sync::atomic::AtomicBool::new(false),})}diff --git a/crates/openhuman-core/src/platform/socket/manager.rs b/crates/openhuman-core/src/platform/socket/manager.rsindex 0874eae9bb..b5a1cf6d8c 100644--- a/crates/openhuman-core/src/platform/socket/manager.rs+++ b/crates/openhuman-core/src/platform/socket/manager.rs@@ -11,7 +11,7 @@use std::collections::HashMap;use std::sync::{- atomic::{AtomicU64, Ordering},+ atomic::{AtomicBool, AtomicU64, Ordering},Arc, OnceLock,};@@ -69,6 +69,14 @@ pub(super) struct SharedState {/// 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)>>,+ /// Whether the background `ws_loop` task is running. Set by `spawn_loop`+ /// before the task starts, cleared by the loop itself on every exit path+ /// (a drop guard, so an abort counts too) and by `disconnect`. This is the+ /// explicit "is anyone retrying?" signal the frontend's connectivity chip+ /// reads through `connectivity_diag`, so it never infers loop liveness+ /// from `status`: `Disconnected` alone cannot tell a stopped loop from a+ /// live transport whose Socket.IO namespace the server closed (#6256).+ pub(super) loop_active: AtomicBool,}/// The connection's readiness flag, guarded by a lock so a reader can hold the@@ -191,6 +199,7 @@ impl SocketManager {socket_id: RwLock::new(None),error: RwLock::new(None),connection_identity: RwLock::new(None),+ loop_active: AtomicBool::new(false),}),emit_tx: tokio::sync::Mutex::new(None),shutdown_tx: tokio::sync::Mutex::new(None),@@ -229,6 +238,14 @@ impl SocketManager {*self.shared.status.read() == ConnectionStatus::Connected}+ /// Whether the background reconnect loop is running — reported by+ /// `connectivity_diag` as `socket_loop_active` (#6256). `false` means+ /// nobody is retrying: never connected, signed out, or stopped after a+ /// terminal failure such as an expired session.+ pub fn is_loop_active(&self) -> bool {+ self.shared.loop_active.load(Ordering::Acquire)+ }+/// True when a **live** connection is already serving exactly this `url`/// under exactly this session token.///@@ -377,6 +394,9 @@ impl SocketManager {let url = url.to_string();let shared = Arc::clone(&self.shared);+ // Raised here rather than inside the task so a `connectivity_diag`+ // read racing the spawn cannot see `Connecting` with no loop behind it.+ self.shared.loop_active.store(true, Ordering::Release);let handle = tokio::spawn(async move {ws_loop(@@ -406,6 +426,7 @@ impl SocketManager {if let Some(handle) = self.loop_handle.lock().await.take() {terminate_loop(handle, Duration::from_secs(5)).await;}+ self.shared.loop_active.store(false, Ordering::Release);*self.shared.status.write() = ConnectionStatus::Disconnected;*self.shared.socket_id.write() = None;*self.shared.error.write() = None;diff --git a/crates/openhuman-core/src/platform/socket/manager_tests.rs b/crates/openhuman-core/src/platform/socket/manager_tests.rsindex 03c6187926..b8207d5af9 100644--- a/crates/openhuman-core/src/platform/socket/manager_tests.rs+++ b/crates/openhuman-core/src/platform/socket/manager_tests.rs@@ -384,6 +384,7 @@ fn emit_state_change_is_safe_to_call_on_empty_shared() {socket_id: RwLock::new(None),error: RwLock::new(None),connection_identity: RwLock::new(None),+ loop_active: std::sync::atomic::AtomicBool::new(false),};// Must not panic even with all default state.emit_state_change(&shared);@@ -398,6 +399,7 @@ fn emit_server_event_is_safe_without_subscribers() {socket_id: RwLock::new(Some("x".into())),error: RwLock::new(None),connection_identity: RwLock::new(None),+ loop_active: std::sync::atomic::AtomicBool::new(false),};// Pure logging — must not touch state or panic.emit_server_event(&shared, "any.event", json!({}));diff --git a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rsindex 258e2e2112..60f9900c3a 100644--- a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs+++ b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs@@ -2,6 +2,7 @@//! invalid-token retry decision, and the emit-queue drain used on shutdown.use crate::platform::socket::medulla::workflows;+use std::sync::atomic::Ordering;use std::sync::Arc;use parking_lot::Mutex;@@ -34,6 +35,17 @@ use crate::platform::socket::types::ConnectionOutcome;/// Sentry events because every retry was logged at `error`.pub(super) const FAIL_ESCALATE_THRESHOLD: u32 = 5;+/// Clears `SharedState::loop_active` when the loop task ends, whatever the+/// exit path — a `return`, a `break`, or an abort from `terminate_loop`+/// (dropping the future drops this guard too).+struct LoopActiveGuard<'a>(&'a SharedState);++impl Drop for LoopActiveGuard<'_> {+ fn drop(&mut self) {+ self.0.loop_active.store(false, Ordering::Release);+ }+}+/// Background loop that manages the WebSocket connection and reconnection.////// `token_provider` is called before **each** connection attempt, so a@@ -55,6 +67,11 @@ pub(crate) async fn ws_loop(internal_tx: mpsc::UnboundedSender<String>,emit_ready: Arc<Mutex<bool>>,) {+ // `spawn_loop` raises the flag before the task starts; a direct caller+ // (tests) gets the same contract from here. The guard lowers it on exit.+ shared.loop_active.store(true, Ordering::Release);+ let _loop_active = LoopActiveGuard(&shared);+let mut backoff = Duration::from_millis(1000);let max_backoff = Duration::from_secs(30);let mut consecutive_failures: u32 = 0;diff --git a/crates/openhuman-core/src/platform/socket/ws_loop_deadline_tests.rs b/crates/openhuman-core/src/platform/socket/ws_loop_deadline_tests.rsindex 5081718ce7..8968e7ae8f 100644--- a/crates/openhuman-core/src/platform/socket/ws_loop_deadline_tests.rs+++ b/crates/openhuman-core/src/platform/socket/ws_loop_deadline_tests.rs@@ -102,6 +102,14 @@ async fn ws_loop_reports_reconnecting_between_attempts() {let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(5);loop {if *shared.status.read() == ConnectionStatus::Reconnecting {+ // The loop is alive and retrying: that is what `connectivity_diag`+ // reports as `socket_loop_active` so the chip can show an outage.+ assert!(+ shared+ .loop_active+ .load(std::sync::atomic::Ordering::Acquire),+ "loop_active must be raised while the loop is retrying"+ );break;}assert!(@@ -114,8 +122,15 @@ async fn ws_loop_reports_reconnecting_between_attempts() {let _ = shutdown_tx.send(true);let _ = tokio::time::timeout(tokio::time::Duration::from_secs(5), handle).await;- // Once the loop is gone the status is `Disconnected` again — stopped, not retrying.+ // Once the loop is gone the status is `Disconnected` again — stopped, not+ // retrying — and the liveness flag is lowered by the loop's drop guard.assert_eq!(*shared.status.read(), ConnectionStatus::Disconnected);+ assert!(+ !shared+ .loop_active+ .load(std::sync::atomic::Ordering::Acquire),+ "loop_active must be lowered once the loop task has exited"+ );}/// Spawn an EIO server that answers two connections and reports each clientdiff --git a/crates/openhuman-core/src/platform/socket/ws_loop_tests.rs b/crates/openhuman-core/src/platform/socket/ws_loop_tests.rsindex cb955e8920..4ce6104a72 100644--- a/crates/openhuman-core/src/platform/socket/ws_loop_tests.rs+++ b/crates/openhuman-core/src/platform/socket/ws_loop_tests.rs@@ -19,6 +19,7 @@ fn make_shared() -> Arc<SharedState> {socket_id: RwLock::new(None),error: RwLock::new(None),connection_identity: RwLock::new(None),+ loop_active: std::sync::atomic::AtomicBool::new(false),})}diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.mdindex f09ca79b5d..f3810845a7 100644--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@ -312,7 +312,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an| 7.2.4 | Exa BYOK search (direct API) | RU+RI+VU | `crates/openhuman-core/src/search/tools/exa_tests.rs`, `crates/openhuman-core/src/search/registry.rs`, `crates/openhuman-core/src/config/schema/tools/search.rs`, `tests/config_auth_app_state_connectivity_e2e.rs`, `app/src/components/settings/panels/SearchPanel.test.tsx` (#5137) | ✅ | `exa_search` / `exa_find_similar` / `exa_get_contents` post straight to api.exa.ai against a local stand-in; missing and 401 keys give distinct errors without echoing the response body; keyless Exa falls back to managed; key round-trips through the config RPC, secret encryption, and env overlay; panel asserts the needs-key badge and the exa.ai key link || 7.2.5 | Tavily BYOK search + extract (direct API) | RU+RI+VU | `crates/openhuman-core/src/search/tools/tavily_tests.rs`, `crates/openhuman-core/src/search/registry.rs`, `crates/openhuman-core/src/config/schema/tools/search.rs`, `crates/openhuman-core/src/config/ops_tests.rs` (`apply_search_settings_stores_and_clears_tavily_key`), `tests/config_auth_app_state_connectivity_e2e.rs`, `app/src/components/settings/panels/SearchPanel.test.tsx`, `app/src/utils/__tests__/toolTimelineFormatting.test.ts` | ✅ | `web_search_tool` / `tavily_search` / `tavily_extract` post straight to api.tavily.com with a Bearer key against a local stand-in; raw content, images, and the LLM answer render in markdown; missing and 401 keys give distinct errors without echoing the response body; batches over 20 URLs and keyless Tavily are rejected/fall back to managed; the `(via Tavily)` timeline marker is pinned; the panel asserts the needs-key badge and the tavily.com key link || 7.2.6 | Backend socket connect deadline + reconnect diagnostics | RU | `crates/openhuman-core/src/platform/socket/ws_loop_deadline_tests.rs` (`connect_with_redirects_times_out_when_upgrade_never_answers`, `connect_timeout_is_not_tighter_than_a_handshake_read`, `ws_loop_reports_reconnecting_between_attempts`, `ws_loop_reconnects_after_ping_deadline_on_a_silent_server`), `crates/openhuman-core/src/core/observability_error_classification_network_tests.rs` (`classifies_socket_connect_deadline_as_network_unreachable`) (#6256) | ✅ | One connect attempt (DNS + TCP + TLS + upgrade) is bounded at 10 s per redirect hop and fails as the `operation timed out` transport shape the Sentry classifier demotes; the loop reports `reconnecting` between attempts and `disconnected` only when stopped; the ping-timeout warning carries connection age / EIO pings received / frames sent, and a handshake after an outage logs `Reconnected after …` |-| 7.2.7 | Connectivity chip — core↔hosted backend link | VU | `app/src/services/__tests__/coreHealthMonitor.test.ts`, `app/src/store/__tests__/connectivitySlice.test.ts`, `app/src/store/__tests__/connectivitySelectors.test.ts`, `app/src/components/__tests__/ConnectionIndicator.test.tsx` (#6256) | ✅ | `connectivity_diag.socket_state` is mirrored into `connectivity.hosted` by the health poll; `connecting` / `reconnecting` / `error` render the amber `hosted-degraded` chip, ranked below every other channel; `disconnected` / `uninitialized` collapse to `unknown` (no chip: signed out, local session, boot); a degraded link selects the 5 s poll so recovery shows within seconds |+| 7.2.7 | Connectivity chip — core↔hosted backend link | VU | `app/src/services/__tests__/coreHealthMonitor.test.ts`, `app/src/store/__tests__/connectivitySlice.test.ts`, `app/src/store/__tests__/connectivitySelectors.test.ts`, `app/src/components/__tests__/ConnectionIndicator.test.tsx` (#6256) | ✅ | `connectivity_diag.socket_state` + `socket_loop_active` are mirrored into `connectivity.hosted` by the health poll; with the loop alive, `connecting` / `reconnecting` / `disconnected` (server closed the namespace) render the amber `hosted-degraded` chip, ranked below every other channel; `socket_loop_active=false` or `uninitialized` collapse to `unknown` (no chip: signed out, local session, boot); `error` (server error event on a live transport) is stored but is not a chip state; a degraded link selects the 5 s poll so recovery shows within seconds |---