Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(socket): bound the backend connect attempt and surface the hosted link

Shanu0a33016437b2
diff --git a/app/src/components/ConnectionIndicator.tsx b/app/src/components/ConnectionIndicator.tsx
index ce9b3b3c22..c4a8ca9bfb 100644
--- a/app/src/components/ConnectionIndicator.tsx
+++ b/app/src/components/ConnectionIndicator.tsx
@@ -21,12 +21,13 @@ interface StatusConfig {
}
/**
- * 3-channel connectivity chip (#1527).
+ * 4-channel connectivity chip (#1527, #6256).
*
* Reads `selectBlockingState`, which encodes the user-visible precedence:
- * internet > core > backend. The legacy `status` prop and `selectSocketStatus`
- * fallback are retained so existing call sites that pre-date the split keep
- * rendering correctly during rollout.
+ * internet > core > backend (renderer↔core socket) > hosted (the core's own
+ * link to the hosted backend). The legacy `status` prop and
+ * `selectSocketStatus` fallback are retained so existing call sites that
+ * pre-date the split keep rendering correctly during rollout.
*/
const ConnectionIndicator = ({
status: overrideStatus,
@@ -35,6 +36,7 @@ const ConnectionIndicator = ({
const { t } = useT();
const blocking = useAppSelector(selectBlockingState);
const legacyStatus = useAppSelector(selectSocketStatus);
+ const hosted = useAppSelector(state => state.connectivity.hosted);
const config: StatusConfig = (() => {
if (overrideStatus) {
@@ -72,6 +74,18 @@ const ConnectionIndicator = ({
: t('app.connectionIndicator.reconnecting'),
pulse: false,
};
+ case 'hosted-degraded':
+ // Soft state, same treatment as `backend-only`: chat still works, the
+ // core is retrying its hosted link and the chip says so (#6256).
+ return {
+ color: 'bg-amber-500',
+ textColor: 'text-amber-500',
+ text:
+ hosted === 'connecting'
+ ? t('app.connectionIndicator.connecting')
+ : t('app.connectionIndicator.reconnecting'),
+ pulse: false,
+ };
}
})();
diff --git a/app/src/components/__tests__/ConnectionIndicator.test.tsx b/app/src/components/__tests__/ConnectionIndicator.test.tsx
index 512d5aaf36..80ba507fe4 100644
--- a/app/src/components/__tests__/ConnectionIndicator.test.tsx
+++ b/app/src/components/__tests__/ConnectionIndicator.test.tsx
@@ -93,6 +93,41 @@ describe('ConnectionIndicator', () => {
expect(screen.getByText('Disconnected')).toBeInTheDocument();
});
+ it("shows an amber dot and 'Disconnected' while the core's hosted link is retrying (#6256)", () => {
+ const { container } = renderWithProviders(<ConnectionIndicator />, {
+ preloadedState: {
+ connectivity: {
+ internet: 'online',
+ core: 'reachable',
+ backend: 'connected',
+ hosted: 'reconnecting',
+ lastError: {},
+ },
+ socket: { byUser: {} },
+ },
+ });
+ expect(screen.getByText('Disconnected')).toBeInTheDocument();
+ expect(container.querySelector('.bg-amber-500')).not.toBeNull();
+ expect(container.querySelector('.animate-pulse')).toBeNull();
+ });
+
+ it("stays green when the core's hosted link is simply not running (signed out / local)", () => {
+ const { container } = renderWithProviders(<ConnectionIndicator />, {
+ preloadedState: {
+ connectivity: {
+ internet: 'online',
+ core: 'reachable',
+ backend: 'connected',
+ hosted: 'unknown',
+ lastError: {},
+ },
+ socket: { byUser: {} },
+ },
+ });
+ expect(screen.getByText('Connected')).toBeInTheDocument();
+ expect(container.querySelector('.bg-sage-500')).not.toBeNull();
+ });
+
it('shows "Connecting" when blocking=backend-only and legacy socket status is connecting (line 67)', () => {
renderWithProviders(<ConnectionIndicator />, {
preloadedState: {
diff --git a/app/src/components/chat/ChatNewWindowHero.tsx b/app/src/components/chat/ChatNewWindowHero.tsx
index df3a2a80a8..18dd61d447 100644
--- a/app/src/components/chat/ChatNewWindowHero.tsx
+++ b/app/src/components/chat/ChatNewWindowHero.tsx
@@ -47,6 +47,7 @@ export default function ChatNewWindowHero() {
const statusCopy = {
ok: t('home.statusOk'),
'backend-only': t('home.statusBackendOnly'),
+ 'hosted-degraded': t('home.statusHostedDegraded'),
'core-unreachable': t('home.statusCoreUnreachable'),
'internet-offline': t('home.statusInternetOffline'),
}[blocking];
diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts
index b093286139..9168a13794 100644
--- a/app/src/lib/i18n/ar.ts
+++ b/app/src/lib/i18n/ar.ts
@@ -637,6 +637,8 @@ const messages: TranslationMap = {
'home.askAssistant': 'اسأل مساعدك أي شيء...',
'home.statusOk': 'مساعدك جاهز متى كنت مستعدًا. اكتب شيئًا في الأسفل للبدء.',
'home.statusBackendOnly': 'جارٍ إعادة الاتصال بالخادم… سيتوفر وكيلك قريبًا.',
+ 'home.statusHostedDegraded':
+ 'جارٍ إعادة الاتصال بالسحابة… تستمر المحادثة في العمل؛ وستُستأنف عمليات التكامل والقنوات فور عودة الاتصال.',
'home.statusCoreUnreachable':
'العملية الأساسية المحلية لا تستجيب. قد تكون عملية OpenHuman في الخلفية قد تعطلت أو فشلت في البدء.',
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts
index 46ef31f09e..671092163a 100644
--- a/app/src/lib/i18n/bn.ts
+++ b/app/src/lib/i18n/bn.ts
@@ -652,6 +652,8 @@ const messages: TranslationMap = {
'home.askAssistant': 'আপনার অ্যাসিস্ট্যান্টকে যেকোনো কিছু জিজ্ঞেস করুন...',
'home.statusOk': 'আপনার সহকারী প্রস্তুত। শুরু করতে নিচে কিছু লিখুন।',
'home.statusBackendOnly': 'ব্যাকএন্ডে পুনরায় সংযোগ হচ্ছে… আপনার এজেন্ট শীঘ্রই আবার পাওয়া যাবে।',
+ 'home.statusHostedDegraded':
+ 'ক্লাউডের সাথে পুনরায় সংযোগ করা হচ্ছে… চ্যাট চালু থাকবে; সংযোগ ফিরে এলেই ইন্টিগ্রেশন ও চ্যানেল আবার কাজ করবে।',
'home.statusCoreUnreachable':
'লোকাল কোর সাইডকার সাড়া দিচ্ছে না। OpenHuman ব্যাকগ্রাউন্ড প্রসেস ক্র্যাশ হয়েছে বা শুরু হয়নি।',
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts
index 4ed788ef74..6828524270 100644
--- a/app/src/lib/i18n/de.ts
+++ b/app/src/lib/i18n/de.ts
@@ -683,6 +683,8 @@ const messages: TranslationMap = {
'Dein Assistent ist bereit, wenn du es bist. Schreib unten etwas, um loszulegen.',
'home.statusBackendOnly':
'Verbindung zum Backend wird wiederhergestellt. Dein Agent wird in Kürze wieder verfügbar sein.',
+ 'home.statusHostedDegraded':
+ 'Verbindung zur Cloud wird wiederhergestellt… Der Chat funktioniert weiter; Integrationen und Kanäle laufen weiter, sobald sie wieder da ist.',
'home.statusCoreUnreachable':
'Der lokale Core-Sidecar reagiert nicht. Der Hintergrundprozess OpenHuman ist möglicherweise abgestürzt oder konnte nicht gestartet werden.',
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts
index 94683cb8ab..bd3283da16 100644
--- a/app/src/lib/i18n/en.ts
+++ b/app/src/lib/i18n/en.ts
@@ -476,6 +476,8 @@ const en: TranslationMap = {
'home.askAssistant': 'Ask your assistant anything...',
'home.statusOk': 'Your assistant is ready when you are. Type something below to get started.',
'home.statusBackendOnly': 'Reconnecting to backend… your agent will be available again shortly.',
+ 'home.statusHostedDegraded':
+ "Reconnecting to the cloud… chat keeps working; integrations and channels resume once it's back.",
'home.statusCoreUnreachable':
"The OpenHuman core isn't responding. The background process may have crashed or failed to start.",
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts
index 0b17424dba..d505d57247 100644
--- a/app/src/lib/i18n/es.ts
+++ b/app/src/lib/i18n/es.ts
@@ -672,6 +672,8 @@ const messages: TranslationMap = {
'home.statusOk': 'Tu asistente está listo cuando tú lo estés. Escribe algo abajo para empezar.',
'home.statusBackendOnly':
'Reconectando al backend… tu agente estará disponible nuevamente en breve.',
+ 'home.statusHostedDegraded':
+ 'Reconectando con la nube… el chat sigue funcionando; las integraciones y los canales se reanudarán en cuanto vuelva.',
'home.statusCoreUnreachable':
'El proceso en segundo plano de OpenHuman no responde. Es posible que haya fallado o no haya podido iniciarse.',
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts
index c02a28feac..0e88135a90 100644
--- a/app/src/lib/i18n/fr.ts
+++ b/app/src/lib/i18n/fr.ts
@@ -683,6 +683,8 @@ const messages: TranslationMap = {
'Ton assistant est prêt quand tu veux. Écris quelque chose ci-dessous pour commencer.',
'home.statusBackendOnly':
'Reconnexion au backend… ton agent sera de nouveau disponible dans quelques instants.',
+ 'home.statusHostedDegraded':
+ 'Reconnexion au cloud… le chat continue de fonctionner ; les intégrations et les canaux reprendront dès son retour.',
'home.statusCoreUnreachable':
"Le processus local OpenHuman ne répond pas. Il a peut-être planté ou n'a pas démarré correctement.",
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts
index 5491cd8420..8554b472ae 100644
--- a/app/src/lib/i18n/hi.ts
+++ b/app/src/lib/i18n/hi.ts
@@ -653,6 +653,8 @@ const messages: TranslationMap = {
'home.askAssistant': 'असिस्टेंट से कुछ भी पूछें...',
'home.statusOk': 'आपका सहायक तैयार है। शुरू करने के लिए नीचे कुछ लिखें।',
'home.statusBackendOnly': 'बैकएंड से फिर से जुड़ रहे हैं… आपका एजेंट जल्द ही उपलब्ध होगा।',
+ 'home.statusHostedDegraded':
+ 'क्लाउड से दोबारा कनेक्ट हो रहा है… चैट काम करती रहेगी; कनेक्शन लौटते ही इंटीग्रेशन और चैनल फिर से चालू हो जाएंगे।',
'home.statusCoreUnreachable':
'लोकल कोर साइडकार रिस्पॉन्ड नहीं कर रहा। OpenHuman का बैकग्राउंड प्रोसेस क्रैश हो गया होगा या शुरू नहीं हो पाया।',
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts
index be61314dd6..9c8c856c41 100644
--- a/app/src/lib/i18n/id.ts
+++ b/app/src/lib/i18n/id.ts
@@ -662,6 +662,8 @@ const messages: TranslationMap = {
'home.statusOk': 'Asistenmu siap kapan pun kamu siap. Ketik sesuatu di bawah untuk memulai.',
'home.statusBackendOnly':
'Menghubungkan ulang ke backend... agen Anda akan segera tersedia lagi.',
+ 'home.statusHostedDegraded':
+ 'Menyambung kembali ke cloud… obrolan tetap berjalan; integrasi dan kanal akan berlanjut begitu koneksi kembali.',
'home.statusCoreUnreachable':
'Core sidecar lokal tidak merespons. Proses latar OpenHuman mungkin crash atau gagal dimulai.',
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts
index b1e888c849..c7c57f55e4 100644
--- a/app/src/lib/i18n/it.ts
+++ b/app/src/lib/i18n/it.ts
@@ -674,6 +674,8 @@ const messages: TranslationMap = {
'home.statusOk':
'Il tuo assistente è pronto quando lo sei tu. Scrivi qualcosa qui sotto per iniziare.',
'home.statusBackendOnly': 'Riconnessione al backend… il tuo agente sarà disponibile a breve.',
+ 'home.statusHostedDegraded':
+ 'Riconnessione al cloud… la chat continua a funzionare; integrazioni e canali riprenderanno appena tornerà disponibile.',
'home.statusCoreUnreachable':
'Il sidecar core locale non risponde. Il processo in background di OpenHuman potrebbe essersi bloccato o non essere partito.',
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts
index d153bfdad5..b49b128f1f 100644
--- a/app/src/lib/i18n/ko.ts
+++ b/app/src/lib/i18n/ko.ts
@@ -646,6 +646,8 @@ const messages: TranslationMap = {
'home.statusOk': '어시스턴트가 준비되어 있어요. 아래에 무언가 입력해 시작하세요.',
'home.statusBackendOnly':
'백엔드에 다시 연결하는 중입니다… 곧 에이전트를 다시 사용할 수 있습니다.',
+ 'home.statusHostedDegraded':
+ '클라우드에 다시 연결하는 중… 채팅은 계속 사용할 수 있으며, 연결이 복구되면 통합과 채널이 다시 동작합니다.',
'home.statusCoreUnreachable':
'로컬 코어 사이드카가 응답하지 않습니다. OpenHuman 백그라운드 프로세스가 중단되었거나 시작하지 못했을 수 있습니다.',
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts
index e04c88a3b4..166689bd1a 100644
--- a/app/src/lib/i18n/pl.ts
+++ b/app/src/lib/i18n/pl.ts
@@ -668,6 +668,8 @@ const messages: TranslationMap = {
'home.statusOk': 'Twój asystent jest gotowy, gdy tylko zechcesz. Napisz coś poniżej, aby zacząć.',
'home.statusBackendOnly':
'Ponowne łączenie z backendem… Twój agent będzie dostępny ponownie za chwilę.',
+ 'home.statusHostedDegraded':
+ 'Ponowne łączenie z chmurą… czat nadal działa; integracje i kanały wznowią się, gdy tylko połączenie wróci.',
'home.statusCoreUnreachable':
'Rdzeń OpenHuman nie odpowiada. Proces w tle mógł ulec awarii lub nie uruchomić się.',
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts
index a087052ba9..62a97e1e38 100644
--- a/app/src/lib/i18n/pt.ts
+++ b/app/src/lib/i18n/pt.ts
@@ -670,6 +670,8 @@ const messages: TranslationMap = {
'Seu assistente está pronto quando você estiver. Escreva algo abaixo para começar.',
'home.statusBackendOnly':
'Reconectando ao backend… seu agente estará disponível novamente em breve.',
+ 'home.statusHostedDegraded':
+ 'Reconectando à nuvem… o chat continua funcionando; integrações e canais voltam assim que ela retornar.',
'home.statusCoreUnreachable':
'O processo em segundo plano do OpenHuman não está respondendo. Ele pode ter travado ou falhado ao iniciar.',
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts
index a9967fce18..e35d06be55 100644
--- a/app/src/lib/i18n/ru.ts
+++ b/app/src/lib/i18n/ru.ts
@@ -662,6 +662,8 @@ const messages: TranslationMap = {
'home.statusOk':
'Ваш ассистент готов, когда вы будете готовы. Напишите что-нибудь ниже, чтобы начать.',
'home.statusBackendOnly': 'Переподключение к серверу… агент скоро снова будет доступен.',
+ 'home.statusHostedDegraded':
+ 'Переподключение к облаку… чат продолжает работать; интеграции и каналы возобновятся, как только связь восстановится.',
'home.statusCoreUnreachable':
'Локальный процесс OpenHuman не отвечает. Возможно, он завис или не запустился.',
'home.statusInternetOffline':
diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts
index 2d7bf33316..2701564712 100644
--- a/app/src/lib/i18n/zh-CN.ts
+++ b/app/src/lib/i18n/zh-CN.ts
@@ -610,6 +610,8 @@ const messages: TranslationMap = {
'home.askAssistant': '向你的助手提问...',
'home.statusOk': '你的助手已准备就绪。在下方输入内容即可开始。',
'home.statusBackendOnly': '正在重新连接后端…你的智能体很快将再次可用。',
+ 'home.statusHostedDegraded':
+ '正在重新连接云端…聊天仍可正常使用;连接恢复后,集成和频道将继续工作。',
'home.statusCoreUnreachable': '本地核心 sidecar 无响应。OpenHuman 后台进程可能已崩溃或未能启动。',
'home.statusInternetOffline': '你的设备当前处于离线状态。请检查网络或重启应用以重新连接。',
'home.restartCore': '重启核心',
diff --git a/app/src/pages/Home.tsx b/app/src/pages/Home.tsx
index f4d170a404..e7fa823f2d 100644
--- a/app/src/pages/Home.tsx
+++ b/app/src/pages/Home.tsx
@@ -64,6 +64,7 @@ const Home = () => {
const statusCopy = {
ok: t('home.statusOk'),
'backend-only': t('home.statusBackendOnly'),
+ 'hosted-degraded': t('home.statusHostedDegraded'),
'core-unreachable': t('home.statusCoreUnreachable'),
'internet-offline': t('home.statusInternetOffline'),
}[blocking];
diff --git a/app/src/services/__tests__/coreHealthMonitor.test.ts b/app/src/services/__tests__/coreHealthMonitor.test.ts
index db555514ce..1394201124 100644
--- a/app/src/services/__tests__/coreHealthMonitor.test.ts
+++ b/app/src/services/__tests__/coreHealthMonitor.test.ts
@@ -6,12 +6,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
// Mock store and connectivitySlice first.
const dispatchMock = vi.fn();
+const connectivityState: { core: string; hosted?: string } = { core: 'reachable' };
vi.mock('../../store/index', () => ({
- store: { dispatch: dispatchMock, getState: () => ({ connectivity: { core: 'reachable' } }) },
+ store: { dispatch: dispatchMock, getState: () => ({ connectivity: connectivityState }) },
}));
const setCoreMock = vi.fn((payload: unknown) => ({ type: 'connectivity/setCore', payload }));
-vi.mock('../../store/connectivitySlice', () => ({ setCore: (p: unknown) => setCoreMock(p) }));
+const setHostedMock = vi.fn((payload: unknown) => ({ type: 'connectivity/setHosted', payload }));
+vi.mock('../../store/connectivitySlice', () => ({
+ setCore: (p: unknown) => setCoreMock(p),
+ setHosted: (p: unknown) => setHostedMock(p),
+}));
const callCoreRpcMock = vi.fn();
vi.mock('../coreRpcClient', () => ({ callCoreRpc: callCoreRpcMock }));
@@ -28,8 +33,11 @@ describe('coreHealthMonitor', () => {
beforeEach(() => {
vi.useFakeTimers();
vi.resetModules();
+ connectivityState.core = 'reachable';
+ delete connectivityState.hosted;
dispatchMock.mockClear();
setCoreMock.mockClear();
+ setHostedMock.mockClear();
callCoreRpcMock.mockClear();
});
@@ -170,6 +178,81 @@ describe('coreHealthMonitor', () => {
stopCoreHealthMonitor();
});
+ it("mirrors the core's hosted link from the diag reply (#6256)", async () => {
+ // Real wire shape: the handler answers `{ diag: … }` and the RPC layer's
+ // log envelope wraps it as `{ result, logs }` (#6080).
+ callCoreRpcMock.mockResolvedValueOnce({
+ result: {
+ diag: {
+ socket_state: 'reconnecting',
+ last_ws_error: 'Ping timeout',
+ sidecar_pid: 42,
+ listen_port: 7788,
+ listen_port_in_use: true,
+ },
+ },
+ logs: ['connectivity diag returned'],
+ });
+
+ const { startCoreHealthMonitor, stopCoreHealthMonitor } = await import('../coreHealthMonitor');
+ startCoreHealthMonitor();
+ await flushPromises();
+
+ expect(setHostedMock).toHaveBeenCalledWith({ value: 'reconnecting', error: 'Ping timeout' });
+ stopCoreHealthMonitor();
+ });
+
+ it('reports the hosted link as unknown when the diag reply carries no socket state', async () => {
+ callCoreRpcMock.mockResolvedValueOnce({});
+
+ const { startCoreHealthMonitor, stopCoreHealthMonitor } = await import('../coreHealthMonitor');
+ startCoreHealthMonitor();
+ await flushPromises();
+
+ expect(setHostedMock).toHaveBeenCalledWith({ value: 'unknown' });
+ stopCoreHealthMonitor();
+ });
+
+ it('polls at the degraded cadence while the hosted link is retrying (#6256)', async () => {
+ callCoreRpcMock.mockResolvedValue({
+ result: { diag: { socket_state: 'reconnecting' } },
+ logs: ['connectivity diag returned'],
+ });
+ // The mocked store never applies the dispatch, so mirror what the reducer
+ // would have stored before the monitor picks its next interval.
+ connectivityState.hosted = 'reconnecting';
+
+ const { startCoreHealthMonitor, stopCoreHealthMonitor } = await import('../coreHealthMonitor');
+ startCoreHealthMonitor();
+ await flushPromises();
+ expect(callCoreRpcMock).toHaveBeenCalledTimes(1);
+
+ // Core is reachable and never failed: without the hosted rule this would
+ // be a 30s heartbeat and nothing would fire at 5s.
+ vi.advanceTimersByTime(5_001);
+ await flushPromises();
+ expect(callCoreRpcMock).toHaveBeenCalledTimes(2);
+ stopCoreHealthMonitor();
+ });
+
+ it('keeps the healthy cadence when the hosted link is simply not running', async () => {
+ callCoreRpcMock.mockResolvedValue({
+ result: { diag: { socket_state: 'disconnected' } },
+ logs: ['connectivity diag returned'],
+ });
+ connectivityState.hosted = 'unknown';
+
+ const { startCoreHealthMonitor, stopCoreHealthMonitor } = await import('../coreHealthMonitor');
+ startCoreHealthMonitor();
+ await flushPromises();
+ expect(setHostedMock).toHaveBeenCalledWith({ value: 'unknown' });
+
+ vi.advanceTimersByTime(5_001);
+ await flushPromises();
+ expect(callCoreRpcMock).toHaveBeenCalledTimes(1);
+ stopCoreHealthMonitor();
+ });
+
it('error message falls back to String(err) when not an Error instance (lines 31-34)', async () => {
callCoreRpcMock
.mockRejectedValueOnce('plain string error')
@@ -190,3 +273,54 @@ describe('coreHealthMonitor', () => {
stopCoreHealthMonitor();
});
});
+
+describe('hostedStateFromDiag', () => {
+ it('passes the live-loop statuses through verbatim', async () => {
+ const { hostedStateFromDiag } = await import('../coreHealthMonitor');
+ for (const socket_state of ['connected', 'connecting', 'reconnecting', 'error']) {
+ expect(hostedStateFromDiag({ socket_state })).toEqual({ value: socket_state });
+ }
+ });
+
+ it('peels the handler envelope and the log envelope the RPC layer adds (#6080)', async () => {
+ const { hostedStateFromDiag } = await import('../coreHealthMonitor');
+ // Bare handler answer.
+ expect(hostedStateFromDiag({ diag: { socket_state: 'connected' } })).toEqual({
+ value: 'connected',
+ });
+ // What actually crosses the wire today: `single_log` wraps as `{ result, logs }`.
+ expect(
+ hostedStateFromDiag({
+ result: { diag: { socket_state: 'error', last_ws_error: 'boom' } },
+ logs: ['connectivity diag returned'],
+ })
+ ).toEqual({ value: 'error', error: 'boom' });
+ // An envelope with nothing usable inside is still `unknown`, never a throw.
+ expect(hostedStateFromDiag({ result: null, logs: [] })).toEqual({ value: 'unknown' });
+ expect(hostedStateFromDiag({ result: { diag: 'nope' } })).toEqual({ value: 'unknown' });
+ });
+
+ it('collapses a loop that is not running, and anything unrecognised, to unknown', async () => {
+ const { hostedStateFromDiag } = await import('../coreHealthMonitor');
+ expect(hostedStateFromDiag({ socket_state: 'disconnected' })).toEqual({ value: 'unknown' });
+ expect(hostedStateFromDiag({ socket_state: 'uninitialized' })).toEqual({ value: 'unknown' });
+ expect(hostedStateFromDiag({ socket_state: 42 })).toEqual({ value: 'unknown' });
+ expect(hostedStateFromDiag({})).toEqual({ value: 'unknown' });
+ expect(hostedStateFromDiag(null)).toEqual({ value: 'unknown' });
+ expect(hostedStateFromDiag('nope')).toEqual({ value: 'unknown' });
+ });
+
+ it('carries a non-empty last_ws_error and drops an empty or non-string one', async () => {
+ const { hostedStateFromDiag } = await import('../coreHealthMonitor');
+ expect(hostedStateFromDiag({ socket_state: 'error', last_ws_error: 'boom' })).toEqual({
+ value: 'error',
+ error: 'boom',
+ });
+ expect(hostedStateFromDiag({ socket_state: 'connected', last_ws_error: '' })).toEqual({
+ value: 'connected',
+ });
+ expect(hostedStateFromDiag({ socket_state: 'connected', last_ws_error: null })).toEqual({
+ value: 'connected',
+ });
+ });
+});
diff --git a/app/src/services/coreHealthMonitor.ts b/app/src/services/coreHealthMonitor.ts
index c1295f7632..411f697638 100644
--- a/app/src/services/coreHealthMonitor.ts
+++ b/app/src/services/coreHealthMonitor.ts
@@ -2,6 +2,15 @@
* coreHealthMonitor — polls the local Rust sidecar's `openhuman.connectivity_diag`
* endpoint and dispatches `setCore` to the connectivitySlice (#1527).
*
+ * The same reply carries the core's own link to the hosted backend
+ * (`socket_state`), which is mirrored into the `hosted` channel so the
+ * connectivity chip can show an outage of that link (#6256). It is a poll, so
+ * a drop that heals within one healthy interval is never shown — deliberately:
+ * a two-second blip is not actionable and a flapping chip would be noise. A
+ * drop that persists appears within one healthy interval and clears within
+ * one degraded interval, because a degraded hosted link also selects the fast
+ * cadence.
+ *
* Polling cadence is adaptive:
* - healthy : 30s (cheap heartbeat)
* - degraded : 5s (fast recovery detection)
@@ -10,7 +19,8 @@
* `FAIL_THRESHOLD` consecutive failures to mark `unreachable` so a single
* dropped TCP packet doesn't pop a scary blocking screen.
*/
-import { setCore } from '../store/connectivitySlice';
+import { isHostedDegraded } from '../store/connectivitySelectors';
+import { type HostedState, setCore, setHosted } from '../store/connectivitySlice';
import { store } from '../store/index';
import { callCoreRpc } from './coreRpcClient';
@@ -18,15 +28,66 @@ const HEALTHY_INTERVAL_MS = 30_000;
const DEGRADED_INTERVAL_MS = 5_000;
const FAIL_THRESHOLD = 2;
+/** The core's `ConnectionStatus` values the hosted channel mirrors verbatim. */
+const HOSTED_STATES: ReadonlySet<string> = new Set<HostedState>([
+ 'connected',
+ 'connecting',
+ 'reconnecting',
+ 'error',
+]);
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' ? (value as Record<string, unknown>) : null;
+}
+
+/**
+ * Peel a `connectivity_diag` reply down to the diag payload. The handler
+ * answers `{ diag: { socket_state, … } }`, and because it attaches a log line
+ * the RPC layer wraps that again as `{ result: { diag }, logs }` (the
+ * log-envelope rule, #6080). Both layers are removed here and a bare payload
+ * is accepted too, so a future normalisation of that rule cannot silently
+ * turn every reading into `unknown`.
+ */
+function unwrapDiag(reply: unknown): Record<string, unknown> {
+ let record = asRecord(reply) ?? {};
+ const result = asRecord(record.result);
+ if (result) record = result;
+ const diag = asRecord(record.diag);
+ if (diag) record = diag;
+ return record;
+}
+
+/**
+ * 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.
+ */
+export function hostedStateFromDiag(reply: unknown): { value: HostedState; error?: string } {
+ const record = unwrapDiag(reply);
+ const socketState = record.socket_state;
+ const lastError = record.last_ws_error;
+ const value: HostedState =
+ typeof socketState === 'string' && HOSTED_STATES.has(socketState)
+ ? (socketState as HostedState)
+ : 'unknown';
+ return typeof lastError === 'string' && lastError.length > 0
+ ? { value, error: lastError }
+ : { value };
+}
+
let timer: ReturnType<typeof setTimeout> | null = null;
let consecutiveFails = 0;
let stopped = true;
async function probe(): Promise<void> {
try {
- await callCoreRpc({ method: 'openhuman.connectivity_diag', params: {} });
+ const diag = await callCoreRpc<unknown>({ method: 'openhuman.connectivity_diag', params: {} });
consecutiveFails = 0;
store.dispatch(setCore({ value: 'reachable' }));
+ store.dispatch(setHosted(hostedStateFromDiag(diag)));
} catch (err) {
consecutiveFails += 1;
const message = err instanceof Error ? err.message : String(err);
@@ -44,8 +105,10 @@ function schedule(): void {
// 5s polling on the *first* miss — before the threshold flips `core` to
// `unreachable`. Without this, first-failure retries stayed at 30s.
// (addresses @coderabbitai on coreHealthMonitor.ts:46)
- const state = store.getState().connectivity.core;
- const isDegraded = consecutiveFails > 0 || state !== 'reachable';
+ // A degraded hosted link selects the fast cadence too, so its recovery is
+ // reflected within seconds rather than at the next 30s heartbeat (#6256).
+ const { core, hosted } = store.getState().connectivity;
+ const isDegraded = consecutiveFails > 0 || core !== 'reachable' || isHostedDegraded(hosted);
const interval = isDegraded ? DEGRADED_INTERVAL_MS : HEALTHY_INTERVAL_MS;
timer = setTimeout(() => void probe(), interval);
}
diff --git a/app/src/store/__tests__/connectivitySelectors.test.ts b/app/src/store/__tests__/connectivitySelectors.test.ts
index 4e71d558b2..7de6e1cfd3 100644
--- a/app/src/store/__tests__/connectivitySelectors.test.ts
+++ b/app/src/store/__tests__/connectivitySelectors.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { selectBlockingState } from '../connectivitySelectors';
+import { isHostedDegraded, selectBlockingState } from '../connectivitySelectors';
import type { ConnectivityState } from '../connectivitySlice';
import type { RootState } from '../index';
@@ -12,6 +12,7 @@ const make = (over: Partial<ConnectivityState>): RootState =>
internet: 'online',
core: 'reachable',
backend: 'connected',
+ hosted: 'connected',
lastError: {},
...over,
},
@@ -38,4 +39,42 @@ describe('selectBlockingState', () => {
expect(selectBlockingState(make({ backend: 'disconnected' }))).toBe('backend-only');
expect(selectBlockingState(make({ backend: 'connecting' }))).toBe('backend-only');
});
+
+ it("returns hosted-degraded when only the core's hosted link is down and retrying (#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');
+ });
+
+ it('treats a hosted link that is not running as healthy, not degraded', () => {
+ // Signed out, local session, early boot: no link was ever wanted.
+ expect(selectBlockingState(make({ hosted: 'unknown' }))).toBe('ok');
+ // A store hydrated before the channel existed reads the same way.
+ expect(
+ selectBlockingState(make({ hosted: undefined as unknown as ConnectivityState['hosted'] }))
+ ).toBe('ok');
+ });
+
+ it('ranks the hosted link below every other channel', () => {
+ expect(selectBlockingState(make({ backend: 'disconnected', hosted: 'reconnecting' }))).toBe(
+ 'backend-only'
+ );
+ expect(selectBlockingState(make({ core: 'unreachable', hosted: 'reconnecting' }))).toBe(
+ 'core-unreachable'
+ );
+ expect(selectBlockingState(make({ internet: 'offline', hosted: 'reconnecting' }))).toBe(
+ 'internet-offline'
+ );
+ });
+});
+
+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('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.ts
index e3dcf9e6b7..b1eb038c7a 100644
--- a/app/src/store/__tests__/connectivitySlice.test.ts
+++ b/app/src/store/__tests__/connectivitySlice.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it, vi } from 'vitest';
-import connectivityReducer, { setBackend, setCore, setInternet } from '../connectivitySlice';
+import connectivityReducer, {
+ setBackend,
+ setCore,
+ setHosted,
+ setInternet,
+} from '../connectivitySlice';
describe('connectivitySlice', () => {
it('setInternet flips the internet channel and tracks errors only on offline', () => {
@@ -56,6 +61,36 @@ describe('connectivitySlice', () => {
expect('backend' in state.lastError).toBe(false);
});
+ it('setHosted mirrors the core link and keeps an error only for a degraded reading', () => {
+ // Boot default: the core's reconnect loop is not known to be running.
+ expect(connectivityReducer(undefined, { type: 'noop' }).hosted).toBe('unknown');
+
+ let state = connectivityReducer(
+ undefined,
+ setHosted({ value: 'reconnecting', error: 'Ping timeout' })
+ );
+ expect(state.hosted).toBe('reconnecting');
+ expect(state.lastError.hosted).toBe('Ping timeout');
+
+ // A degraded reading without a message must not leave the old one behind.
+ state = connectivityReducer(state, setHosted({ value: 'connecting' }));
+ expect(state.hosted).toBe('connecting');
+ expect('hosted' in state.lastError).toBe(false);
+
+ state = connectivityReducer(state, setHosted({ value: 'error', error: 'server error' }));
+ expect(state.lastError.hosted).toBe('server error');
+
+ // Recovery clears it…
+ state = connectivityReducer(state, setHosted({ value: 'connected' }));
+ expect(state.hosted).toBe('connected');
+ expect('hosted' in state.lastError).toBe(false);
+
+ // …and so does the loop going away (sign-out), even if a message rides along.
+ state = connectivityReducer(state, setHosted({ value: 'unknown', error: 'session expired' }));
+ expect(state.hosted).toBe('unknown');
+ expect('hosted' in state.lastError).toBe(false);
+ });
+
it('initial internet state is "offline" when navigator.onLine is false (line 33)', () => {
// Simulate the browser reporting no network at boot time.
const originalOnLine = Object.getOwnPropertyDescriptor(navigator, 'onLine');
diff --git a/app/src/store/connectivitySelectors.ts b/app/src/store/connectivitySelectors.ts
index 03778dfae6..1b285aa594 100644
--- a/app/src/store/connectivitySelectors.ts
+++ b/app/src/store/connectivitySelectors.ts
@@ -1,3 +1,4 @@
+import type { HostedState } from './connectivitySlice';
import { RootState } from './index';
/**
@@ -6,11 +7,30 @@ import { RootState } from './index';
*
* - `internet-offline` : navigator.onLine = false. Nothing else can talk.
* - `core-unreachable` : local sidecar isn't answering. App is dead-in-the-water.
- * - `backend-only` : backend Socket.IO is down but core is alive — the
- * app stays usable, we just show a soft banner.
+ * - `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).
* - `ok` : everything healthy.
*/
-type BlockingState = 'internet-offline' | 'core-unreachable' | 'backend-only' | 'ok';
+type BlockingState =
+ | 'internet-offline'
+ | 'core-unreachable'
+ | 'backend-only'
+ | 'hosted-degraded'
+ | '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.
+ */
+export const isHostedDegraded = (hosted: HostedState | undefined): boolean =>
+ hosted === 'connecting' || hosted === 'reconnecting' || hosted === 'error';
export const selectBlockingState = (s: RootState): BlockingState => {
if (s.connectivity.internet === 'offline') return 'internet-offline';
@@ -18,5 +38,6 @@ export const selectBlockingState = (s: RootState): BlockingState => {
if (s.connectivity.backend === 'disconnected' || s.connectivity.backend === 'connecting') {
return 'backend-only';
}
+ if (isHostedDegraded(s.connectivity.hosted)) return 'hosted-degraded';
return 'ok';
};
diff --git a/app/src/store/connectivitySlice.ts b/app/src/store/connectivitySlice.ts
index 3223c900e0..f365d0ae5b 100644
--- a/app/src/store/connectivitySlice.ts
+++ b/app/src/store/connectivitySlice.ts
@@ -1,7 +1,7 @@
import { createSlice, type PayloadAction } from '@reduxjs/toolkit';
/**
- * Three independent connectivity channels surfaced separately so the UI can
+ * Four independent connectivity channels surfaced separately so the UI can
* tell the user *which* link is broken instead of one conflated "Disconnected"
* pill (#1527).
*
@@ -9,30 +9,48 @@ import { createSlice, type PayloadAction } from '@reduxjs/toolkit';
* listeners on `window`.
* - `core` — local Rust sidecar reachability. Source: `coreHealthMonitor`
* poll of `openhuman.connectivity_diag`.
- * - `backend` — Socket.IO link to the hosted backend. Source:
- * `socketService` lifecycle callbacks.
+ * - `backend` — the renderer's Socket.IO link to the local core, the realtime
+ * path for chat streaming and approvals. Source: `socketService` lifecycle
+ * callbacks.
+ * - `hosted` — the Rust core's own Socket.IO link to the hosted backend
+ * (webhooks, Composio triggers, managed-DM channel routing, hosted-brain
+ * runs). Source: `coreHealthMonitor` reading `socket_state` off the same
+ * `connectivity_diag` poll (#6256). `unknown` means the core's reconnect
+ * loop is not running at all — signed out, local session, early boot — and
+ * is deliberately not a degraded state: the core reports `reconnecting`
+ * between retries, so a link that is down but being retried is never
+ * mistaken for one that was never wanted.
*/
export type InternetState = 'online' | 'offline';
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.
+ */
+export type HostedState = 'connected' | 'connecting' | 'reconnecting' | 'error' | 'unknown';
export interface ConnectivityState {
internet: InternetState;
core: CoreState;
backend: BackendState;
+ hosted: HostedState;
/**
* Last error string emitted per channel, if any. Cleared on the next
* successful state for that channel. UI surfaces these in tooltips /
* blocking screens for diagnosability.
*/
- lastError: { internet?: string; core?: string; backend?: string };
+ lastError: { internet?: string; core?: string; backend?: string; hosted?: string };
}
const initialState: ConnectivityState = {
internet: typeof navigator !== 'undefined' && navigator.onLine === false ? 'offline' : 'online',
core: 'unknown',
backend: 'connecting',
+ hosted: 'unknown',
lastError: {},
};
@@ -70,8 +88,20 @@ const slice = createSlice({
state.lastError.backend = action.payload.error;
}
},
+ setHosted(state, action: PayloadAction<{ value: HostedState; error?: string }>) {
+ const { value, error } = action.payload;
+ state.hosted = value;
+ // `connected` and `unknown` are not outages, and a degraded reading that
+ // carries no message must not leave an older one behind — delete rather
+ // than assign `undefined` (same lesson as `setBackend` above).
+ if (value === 'connected' || value === 'unknown' || error === undefined) {
+ delete state.lastError.hosted;
+ } else {
+ state.lastError.hosted = error;
+ }
+ },
},
});
-export const { setInternet, setCore, setBackend } = slice.actions;
+export const { setInternet, setCore, setBackend, setHosted } = slice.actions;
export default slice.reducer;
diff --git a/crates/openhuman-core/src/core/observability_error_classification_network_tests.rs b/crates/openhuman-core/src/core/observability_error_classification_network_tests.rs
index 641cb479f7..21d621b62d 100644
--- a/crates/openhuman-core/src/core/observability_error_classification_network_tests.rs
+++ b/crates/openhuman-core/src/core/observability_error_classification_network_tests.rs
@@ -159,6 +159,24 @@ fn classifies_wave4_socket_transport_wire_shapes() {
);
}
+#[test]
+fn classifies_socket_connect_deadline_as_network_unreachable() {
+ // #6256: `connect_with_redirects_within` renders its per-hop deadline as
+ // an `io::ErrorKind::TimedOut` carrying the `operation timed out` phrase,
+ // wrapped by `run_connection` and the supervisor's sustained-outage
+ // escalation like every other connect-stage failure. A path that keeps
+ // blackholing the upgrade is user-environment / edge state the reconnect
+ // loop already retries — it must demote, never page.
+ assert_eq!(
+ expected_error_kind(
+ "[socket] Connection failed (sustained outage after 5 attempts): \
+ WebSocket connect: IO error: operation timed out after 10s waiting \
+ for the WebSocket upgrade"
+ ),
+ Some(ExpectedErrorKind::NetworkUnreachable)
+ );
+}
+
#[test]
fn http_200_classifier_does_not_silence_unrelated_log_lines() {
// The captive-portal arm anchors on `"http error: 200 ok"` (the
diff --git a/crates/openhuman-core/src/platform/socket/README.md b/crates/openhuman-core/src/platform/socket/README.md
index e52f63113d..3213956704 100644
--- a/crates/openhuman-core/src/platform/socket/README.md
+++ b/crates/openhuman-core/src/platform/socket/README.md
@@ -5,11 +5,11 @@ Persistent, Rust-native Socket.IO client to the OpenHuman backend. The `socket`
## Responsibilities
- Open and maintain a persistent Socket.IO connection to the backend over a raw WebSocket; perform the Engine.IO OPEN and Socket.IO CONNECT handshakes by hand.
-- Authenticate the SIO CONNECT with a JWT and reconnect automatically with exponential backoff (1 s → 30 s cap).
+- Authenticate the SIO CONNECT with a JWT and reconnect automatically with exponential backoff (1 s → 30 s cap). Every connect attempt (DNS + TCP + TLS + upgrade) is bounded at 10 s per redirect hop (`CONNECT_TIMEOUT`), so a path that accepts the connection and then goes silent fails the attempt instead of parking the loop until the far end gives up (#6256).
- 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.
+- 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).
- 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`.
@@ -101,5 +101,7 @@ None of its own. State (`status`, `socket_id`, `error`, attached `WebhookRouter`
- The reconnect loop bounds "fresh-token immediate retry" to **one** per cycle so a provider that returns a different non-empty token every call cannot hot-loop without sleeping or escalating (CodeRabbit Major, #2905).
- A genuinely fresh token from the invalid-token decision is **carried forward** (`pending_token`) so the next iteration uses the exact validated value, avoiding a redundant profile-store lock/disk read.
- Sentry escalation fires exactly once, on the 5th consecutive failure (~15 s of accumulated backoff), and is routed through the observability classifier so offline/transport shapes demote to a breadcrumb (OPENHUMAN-TAURI-8M / -BH).
+- A connect attempt that outlives `CONNECT_TIMEOUT` is rendered as `WsError::Io(TimedOut)` with the `operation timed out` phrase on purpose — that is the substring `is_network_unreachable_message` demotes, so a sustained blackhole never pages. Keep the wording if you touch it.
+- The ping-timeout warning carries the connection age, the number of Engine.IO pings the connection ever received, and the frames sent since the last server frame; a successful handshake after an outage logs `Reconnected after Ns (N failed attempt(s))`. Both exist so a drop report can be root-caused from the log alone (#6256): drops that always land at the same connection age point at a lifetime ceiling on the path (#5603), zero pings on a minutes-old connection point at the server.
- Redirect following only persists the "update BACKEND_URL" warning for permanent redirects (301/308); temporary (302/307) hops don't (CodeRabbit, #1547).
- No agent tools and no `bus.rs` — this is a transport domain that publishes events for others to handle.
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop.rs b/crates/openhuman-core/src/platform/socket/ws_loop.rs
index 7047b8f135..418f1bf237 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop.rs
@@ -19,8 +19,8 @@ pub(super) use reconnect::ws_loop;
#[cfg(test)]
use connect::{
- connect_with_redirects, extract_location_header, is_redirect_status, record_redirect_warning,
- resolve_redirect_target,
+ connect_with_redirects, connect_with_redirects_within, extract_location_header,
+ is_redirect_status, record_redirect_warning, resolve_redirect_target, CONNECT_TIMEOUT,
};
#[cfg(test)]
use dispatch::{handle_eio_message, handle_sio_packet, parse_sio_ack};
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs
index 0c49aab672..3c76bb45cb 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs
@@ -30,6 +30,39 @@ use crate::platform::socket::types::{ConnectionOutcome, WsStream};
/// redirects while still bounding pathological loops.
const MAX_REDIRECT_HOPS: u8 = 3;
+/// Upper bound on one WebSocket connect attempt — DNS resolution, TCP
+/// connect, TLS handshake and the HTTP upgrade response together — applied
+/// per redirect hop.
+///
+/// `connect_async` carries no deadline of its own, so a path that accepts the
+/// TCP connection and then goes silent (an ingress that blackholes the
+/// upgrade, a stalled TLS handshake, a resolver that never answers) used to
+/// park the reconnect loop until the far end gave up. Both ten-minute
+/// reconnect gaps reported in #6256 measure ~608 s: the ~600 s ingress
+/// ceiling documented on #5603, plus one backoff sleep and a handshake. The
+/// client had no bound of its own. Ten seconds matches the two handshake
+/// reads that follow (`read_eio_open`, `read_sio_connect_ack`) and the
+/// renderer's own socket.io connect timeout: a healthy path completes in well
+/// under a second and a remote or tunnelled one in a few, while a hang now
+/// surfaces as a `Failed` attempt that the next backoff cycle retries.
+pub(super) const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
+
+/// What the reconnect loop knows about the outage a connection attempt is
+/// recovering from, so a successful handshake can say how long the socket
+/// was down and how many attempts it took (#6256).
+#[derive(Clone, Copy, Debug, Default)]
+pub(super) struct ReconnectContext {
+ /// When the outage began: the moment the previous connection was lost,
+ /// or the first failed attempt if there was no connection yet. `None`
+ /// on a first connect that has not failed.
+ pub(super) outage_started: Option<Instant>,
+ /// Whether a live connection preceded this outage — distinguishes
+ /// "reconnected" from "connected after initial failures" in the log.
+ pub(super) lost_previous: bool,
+ /// Attempts that ended in `ConnectionOutcome::Failed` since the outage began.
+ pub(super) failed_attempts: u32,
+}
+
// ---------------------------------------------------------------------------
// Background loop
// ---------------------------------------------------------------------------
@@ -48,6 +81,7 @@ pub(super) async fn run_connection(
shutdown_rx: &mut watch::Receiver<bool>,
internal_tx: &mpsc::UnboundedSender<String>,
emit_ready: &Mutex<bool>,
+ reconnect: ReconnectContext,
) -> ConnectionOutcome {
log::info!("[socket] WS URL: {}", ws_url);
@@ -123,6 +157,18 @@ pub(super) async fn run_connection(
*shared.socket_id.write() = sio_sid;
*emit_ready.lock() = true;
emit_state_change(shared);
+ if let Some(started) = reconnect.outage_started {
+ log::info!(
+ "[socket] {} after {:.1}s ({} failed attempt(s))",
+ if reconnect.lost_previous {
+ "Reconnected"
+ } else {
+ "Connected"
+ },
+ started.elapsed().as_secs_f64(),
+ reconnect.failed_attempts
+ );
+ }
// 7. Main event loop
// Deadline = pingInterval + pingTimeout + 5 s grace so minor server-side
@@ -130,6 +176,16 @@ pub(super) async fn run_connection(
let timeout_ms = ping_interval + ping_timeout_ms + 5_000;
let timeout_duration = Duration::from_millis(timeout_ms);
let mut deadline = Instant::now() + timeout_duration;
+ // Deadline diagnostics (#6256): when the deadline fires, the warning says
+ // how old this connection is, how many Engine.IO pings it ever saw, and
+ // how many frames we pushed into the silence — enough to tell "server
+ // went quiet" from "path went dead" from the log alone. A drop that
+ // always lands at the same connection age points at a lifetime ceiling
+ // on the path (#5603); zero pings on a minutes-old connection points at
+ // the server.
+ let connected_at = Instant::now();
+ let mut pings_received: u32 = 0;
+ let mut sent_since_last_frame: u32 = 0;
loop {
tokio::select! {
@@ -137,10 +193,17 @@ pub(super) async fn run_connection(
match msg {
Some(Ok(WsMessage::Text(text))) => {
deadline = Instant::now() + timeout_duration;
- handle_eio_message(&text, internal_tx, shared);
+ sent_since_last_frame = 0;
+ let frame: &str = &text;
+ if frame.starts_with('2') {
+ pings_received = pings_received.saturating_add(1);
+ }
+ handle_eio_message(frame, internal_tx, shared);
}
Some(Ok(WsMessage::Ping(data))) => {
+ sent_since_last_frame = 0;
let _ = ws_write.send(WsMessage::Pong(data)).await;
+ sent_since_last_frame = sent_since_last_frame.saturating_add(1);
}
Some(Ok(WsMessage::Close(_))) => {
log::info!("[socket] Server closed WebSocket");
@@ -152,7 +215,10 @@ pub(super) async fn run_connection(
None => {
return ConnectionOutcome::Lost("WebSocket stream ended".into());
}
- _ => {} // Binary, Pong, Frame
+ _ => {
+ // Binary, Pong, Frame: still proof the path is alive.
+ sent_since_last_frame = 0;
+ }
}
}
outgoing = emit_rx.recv() => {
@@ -161,6 +227,7 @@ pub(super) async fn run_connection(
if let Err(e) = ws_write.send(WsMessage::Text(msg.into())).await {
return ConnectionOutcome::Lost(format!("Send failed: {e}"));
}
+ sent_since_last_frame = sent_since_last_frame.saturating_add(1);
}
None => {
let _ = ws_write.send(WsMessage::Close(None)).await;
@@ -170,10 +237,13 @@ pub(super) async fn run_connection(
}
_ = tokio::time::sleep_until(deadline) => {
log::warn!(
- "[socket] No server ping received within {}ms (interval={}ms + timeout={}ms + 5s grace); reconnecting",
+ "[socket] No server ping received within {}ms (interval={}ms + timeout={}ms + 5s grace); connection age {:.0}s, {} EIO ping(s) received on this connection, {} frame(s) sent since the last server frame; reconnecting",
timeout_ms,
ping_interval,
ping_timeout_ms,
+ connected_at.elapsed().as_secs_f64(),
+ pings_received,
+ sent_since_last_frame,
);
return ConnectionOutcome::Lost("Ping timeout".into());
}
@@ -281,13 +351,32 @@ async fn read_sio_connect_ack(
///
/// On non-redirect failures the original error is returned and the caller
/// counts it toward the exponential backoff like before.
+///
+/// Every hop is bounded by [`CONNECT_TIMEOUT`]; a hop that outlives it fails
+/// the attempt with a timed-out `WsError::Io` (#6256).
pub(super) async fn connect_with_redirects(
ws_url: &mut String,
shared: &Arc<SharedState>,
+) -> Result<WsStream, WsError> {
+ connect_with_redirects_within(ws_url, shared, CONNECT_TIMEOUT).await
+}
+
+/// [`connect_with_redirects`] with an explicit per-hop deadline. Split out so
+/// a test can prove the bound with a sub-second budget instead of waiting out
+/// [`CONNECT_TIMEOUT`].
+pub(super) async fn connect_with_redirects_within(
+ ws_url: &mut String,
+ shared: &Arc<SharedState>,
+ connect_timeout: Duration,
) -> Result<WsStream, WsError> {
let original = ws_url.clone();
for hop in 0..=MAX_REDIRECT_HOPS {
- match connect_async(ws_url.as_str()).await {
+ let attempt =
+ match tokio::time::timeout(connect_timeout, connect_async(ws_url.as_str())).await {
+ Ok(attempt) => attempt,
+ Err(_elapsed) => return Err(connect_timed_out(connect_timeout)),
+ };
+ match attempt {
Ok((stream, _response)) => return Ok(stream),
Err(WsError::Http(response)) if is_redirect_status(response.status()) => {
if hop == MAX_REDIRECT_HOPS {
@@ -343,6 +432,22 @@ pub(super) async fn connect_with_redirects(
unreachable!("connect_with_redirects exited loop without returning")
}
+/// The error a connect attempt surfaces when it outlives its deadline.
+///
+/// Rendered through `WsError::Io` so `run_connection`'s
+/// `"WebSocket connect: IO error: …"` wrapping stays uniform, and worded with
+/// the `operation timed out` phrase the observability classifier already
+/// treats as a user-environment transport shape
+/// (`core::observability::is_network_unreachable_message`): a sustained hang
+/// escalates to one `warn` breadcrumb on the fifth attempt, never to Sentry —
+/// the same treatment `ETIMEDOUT` gets when the OS reports it.
+fn connect_timed_out(after: Duration) -> WsError {
+ WsError::Io(std::io::Error::new(
+ std::io::ErrorKind::TimedOut,
+ format!("operation timed out after {after:?} waiting for the WebSocket upgrade"),
+ ))
+}
+
/// Statuses we treat as "follow the Location and retry".
///
/// 308 (Permanent Redirect) and 307 (Temporary Redirect) explicitly preserve
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs
index 57640c19fa..258e2e2112 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs
@@ -7,11 +7,11 @@ use std::sync::Arc;
use parking_lot::Mutex;
use tokio::sync::{mpsc, watch};
-use tokio::time::Duration;
+use tokio::time::{Duration, Instant};
use crate::api::models::socket::ConnectionStatus;
-use super::connect::run_connection;
+use super::connect::{run_connection, ReconnectContext};
use crate::platform::socket::manager::{emit_state_change, SharedState};
use crate::platform::socket::token_provider::{is_invalid_token_error, TokenProvider};
use crate::platform::socket::types::ConnectionOutcome;
@@ -83,6 +83,9 @@ pub(crate) async fn ws_loop(
// follow the Location header and pin the resolved URL here so subsequent
// reconnects skip the redirect round-trip entirely.
let mut ws_url = crate::api::socket::websocket_url(&url);
+ // What the next attempt is recovering from, so the handshake can log how
+ // long the socket was down and how many attempts it took (#6256).
+ let mut reconnect = ReconnectContext::default();
loop {
if *shutdown_rx.borrow() {
@@ -145,6 +148,7 @@ pub(crate) async fn ws_loop(
&mut shutdown_rx,
&internal_tx,
&emit_ready,
+ reconnect,
)
.await;
@@ -180,6 +184,23 @@ pub(crate) async fn ws_loop(
shared.ack_registry.cancel_all();
workflows::end_connection_generation();
+ match &outcome {
+ ConnectionOutcome::Lost(_) => {
+ reconnect = ReconnectContext {
+ outage_started: Some(Instant::now()),
+ lost_previous: true,
+ failed_attempts: 0,
+ };
+ }
+ ConnectionOutcome::Failed(_) => {
+ if reconnect.outage_started.is_none() {
+ reconnect.outage_started = Some(Instant::now());
+ }
+ reconnect.failed_attempts = reconnect.failed_attempts.saturating_add(1);
+ }
+ ConnectionOutcome::Shutdown => {}
+ }
+
match outcome {
ConnectionOutcome::Shutdown => {
log::info!("[socket] Clean shutdown");
@@ -288,7 +309,13 @@ pub(crate) async fn ws_loop(
}
}
- *shared.status.write() = ConnectionStatus::Disconnected;
+ // Between attempts the loop is alive and will retry, so report
+ // `Reconnecting` rather than `Disconnected`: `Disconnected` is what a
+ // stopped loop reports (signed out, session expired, shutdown), and
+ // the frontend's connectivity chip has to tell the two apart — a link
+ // that is down but being retried is an outage worth showing, a loop
+ // that was never started is not (#6256).
+ *shared.status.write() = ConnectionStatus::Reconnecting;
*shared.socket_id.write() = None;
emit_state_change(&shared);
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.rs
new file mode 100644
index 0000000000..5081718ce7
--- /dev/null
+++ b/crates/openhuman-core/src/platform/socket/ws_loop_deadline_tests.rs
@@ -0,0 +1,229 @@
+//! #6256 — the connect deadline, the `Reconnecting` status between attempts,
+//! and the ping-deadline diagnostics. Sibling of `ws_loop_reconnect_tests.rs`,
+//! which sits at the layout gate's line limit.
+
+use super::*;
+
+use crate::platform::socket::types::ConnectionStatus;
+use futures_util::{SinkExt, StreamExt};
+use std::sync::Arc;
+use tokio::sync::mpsc;
+use tokio::sync::watch;
+use tokio_tungstenite::tungstenite::Error as WsError;
+
+/// #6256: a connect attempt has a deadline of its own. A listener that
+/// accepts the TCP connection and never answers the upgrade used to park
+/// `connect_with_redirects` until the far end gave up — ten minutes in the
+/// field, the ~600 s ingress ceiling from #5603 plus a backoff sleep. With
+/// the bound the attempt fails fast, as the timed-out transport shape the
+/// observability classifier already demotes.
+#[tokio::test]
+async fn connect_with_redirects_times_out_when_upgrade_never_answers() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
+ let addr = listener.local_addr().expect("addr");
+ let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
+ tokio::spawn(async move {
+ let (stream, _) = listener.accept().await.expect("accept");
+ // Hold the connection open without ever writing a byte back.
+ let _ = release_rx.await;
+ drop(stream);
+ });
+
+ let shared = make_shared();
+ let mut url = format!("ws://{addr}/socket.io/?EIO=4&transport=websocket");
+ let started = tokio::time::Instant::now();
+ let err =
+ connect_with_redirects_within(&mut url, &shared, tokio::time::Duration::from_millis(200))
+ .await
+ .expect_err("a silent upgrade must not hang the connect attempt");
+ let elapsed = started.elapsed();
+ assert!(
+ elapsed < tokio::time::Duration::from_secs(5),
+ "deadline did not bound the attempt: took {elapsed:?}"
+ );
+ assert!(
+ matches!(&err, WsError::Io(io) if io.kind() == std::io::ErrorKind::TimedOut),
+ "expected a timed-out IO error, got {err}"
+ );
+ assert!(
+ err.to_string().contains("operation timed out"),
+ "message must carry the classifier's transport shape: {err}"
+ );
+ let _ = release_tx.send(());
+}
+
+/// The production budget spans DNS + TCP + TLS + the upgrade response, so it
+/// must never be tighter than the single 10 s reads that follow it
+/// (`read_eio_open`, `read_sio_connect_ack`); otherwise a slow-but-healthy
+/// link would fail at the connect step it used to survive.
+#[test]
+fn connect_timeout_is_not_tighter_than_a_handshake_read() {
+ assert!(CONNECT_TIMEOUT >= tokio::time::Duration::from_secs(10));
+}
+
+/// #6256: between attempts the loop is alive and will retry, and it says so.
+/// `Disconnected` is reserved for a loop that stopped (signed out, session
+/// expired, shutdown), so the connectivity chip can tell "down, retrying"
+/// from "never wanted". A listener that accepts and drops every connection
+/// makes each attempt fail and sends the loop into its backoff sleep.
+#[tokio::test]
+async fn ws_loop_reports_reconnecting_between_attempts() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
+ let addr = listener.local_addr().expect("addr");
+ tokio::spawn(async move {
+ loop {
+ let Ok((stream, _)) = listener.accept().await else {
+ return;
+ };
+ drop(stream);
+ }
+ });
+
+ let shared = make_shared();
+ *shared.status.write() = ConnectionStatus::Disconnected;
+ let (_emit_tx, emit_rx) = mpsc::unbounded_channel::<String>();
+ let (shutdown_tx, shutdown_rx) = watch::channel(false);
+ let (internal_tx, _internal_rx) = mpsc::unbounded_channel::<String>();
+
+ let loop_shared = Arc::clone(&shared);
+ let handle = tokio::spawn(async move {
+ ws_loop(
+ http_base_for(addr),
+ static_token_provider("backoff-token".to_string()),
+ loop_shared,
+ emit_rx,
+ shutdown_rx,
+ internal_tx,
+ Arc::new(Mutex::new(false)),
+ )
+ .await;
+ });
+
+ let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(5);
+ loop {
+ if *shared.status.read() == ConnectionStatus::Reconnecting {
+ break;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "loop never reported Reconnecting during its backoff sleep; status={:?}",
+ *shared.status.read()
+ );
+ tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
+ }
+
+ 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.
+ assert_eq!(*shared.status.read(), ConnectionStatus::Disconnected);
+}
+
+/// Spawn an EIO server that answers two connections and reports each client
+/// SIO CONNECT on `forward_tx`. Both connections complete the handshake and
+/// are then **held open until `release_rx` fires** — the server never closes
+/// them, so only the client's own deadline can end the first one. The first
+/// connection additionally sends one Engine.IO ping, one WebSocket-level ping
+/// and one binary frame before going silent, so every inbound arm of the
+/// event loop runs. Short ping intervals keep the client's deadline
+/// (`interval + timeout + 5 s grace`) at ~5.4 s instead of 50 s.
+async fn spawn_mock_server_that_goes_silent(
+ forward_tx: mpsc::UnboundedSender<String>,
+ release_rx: tokio::sync::oneshot::Receiver<()>,
+) -> std::net::SocketAddr {
+ let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
+ let addr = listener.local_addr().expect("addr");
+ tokio::spawn(async move {
+ let open = r#"0{"sid":"mock-eio-sid","upgrades":[],"pingInterval":200,"pingTimeout":200}"#;
+ let mut held = Vec::new();
+ for connection in 0..2u8 {
+ let Ok((stream, _)) = listener.accept().await else {
+ return;
+ };
+ let ws = accept_async(stream).await.expect("ws accept");
+ let (mut write, mut read) = ws.split();
+ let _ = write.send(WsMessage::Text(open.into())).await;
+ if let Some(Ok(WsMessage::Text(t))) = read.next().await {
+ let _ = forward_tx.send(t.to_string());
+ }
+ let _ = write
+ .send(WsMessage::Text(r#"40{"sid":"mock-sio-sid"}"#.into()))
+ .await;
+ if connection == 0 {
+ let _ = write.send(WsMessage::Text("2".into())).await;
+ let _ = write.send(WsMessage::Ping(vec![1].into())).await;
+ let _ = write.send(WsMessage::Binary(vec![0].into())).await;
+ }
+ held.push(write.reunite(read).expect("reunite"));
+ }
+ let _ = release_rx.await;
+ drop(held);
+ });
+ addr
+}
+
+/// #6256 diagnostics path: a server that completes the handshake and then
+/// goes silent without closing is ended by the client's own ping deadline,
+/// the loop reports the loss and reconnects on the next attempt, and the
+/// deadline warning plus the `Reconnected after …` line execute on the way.
+#[tokio::test]
+async fn ws_loop_reconnects_after_ping_deadline_on_a_silent_server() {
+ let (fwd_tx, mut fwd_rx) = mpsc::unbounded_channel::<String>();
+ let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
+ let addr = spawn_mock_server_that_goes_silent(fwd_tx, release_rx).await;
+
+ let shared = make_shared();
+ *shared.status.write() = ConnectionStatus::Disconnected;
+ let (emit_tx, emit_rx) = mpsc::unbounded_channel::<String>();
+ let (shutdown_tx, shutdown_rx) = watch::channel(false);
+ // The loop answers the server's Engine.IO ping through this channel.
+ let internal_tx = emit_tx.clone();
+ drop(emit_tx);
+
+ let loop_shared = Arc::clone(&shared);
+ let handle = tokio::spawn(async move {
+ ws_loop(
+ http_base_for(addr),
+ static_token_provider("deadline-token".to_string()),
+ loop_shared,
+ emit_rx,
+ shutdown_rx,
+ internal_tx,
+ Arc::new(Mutex::new(false)),
+ )
+ .await;
+ });
+
+ // Two SIO CONNECT frames mean two handshakes. The second can only follow
+ // the client's deadline (200 + 200 + 5000 ms) ending the first connection,
+ // because the server never closes it.
+ let started = tokio::time::Instant::now();
+ let mut connects = 0u8;
+ while connects < 2 {
+ match tokio::time::timeout(tokio::time::Duration::from_secs(20), fwd_rx.recv()).await {
+ Ok(Some(frame)) if frame.starts_with("40") => connects += 1,
+ Ok(Some(_)) => {}
+ _ => break,
+ }
+ }
+ let elapsed = started.elapsed();
+ assert_eq!(
+ connects, 2,
+ "client never reconnected after the server went silent (elapsed {elapsed:?})"
+ );
+ assert!(
+ elapsed >= tokio::time::Duration::from_millis(5_400),
+ "second handshake happened before the ping deadline could have fired: {elapsed:?}"
+ );
+
+ for _ in 0..50 {
+ if *shared.status.read() == ConnectionStatus::Connected {
+ break;
+ }
+ tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
+ }
+ assert_eq!(*shared.status.read(), ConnectionStatus::Connected);
+
+ let _ = shutdown_tx.send(true);
+ let _ = tokio::time::timeout(tokio::time::Duration::from_secs(5), handle).await;
+ let _ = release_tx.send(());
+}
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop_tests.rs b/crates/openhuman-core/src/platform/socket/ws_loop_tests.rs
index 00a7e95b1e..cb955e8920 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop_tests.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop_tests.rs
@@ -199,6 +199,8 @@ async fn spawn_mock_invalid_token_server() -> std::net::SocketAddr {
addr
}
+#[path = "ws_loop_deadline_tests.rs"]
+mod deadline_tests;
#[path = "ws_loop_dispatch_and_redirect_tests.rs"]
mod dispatch_and_redirect_tests;
#[path = "ws_loop_reconnect_tests.rs"]
diff --git a/docs/RELEASE-MANUAL-SMOKE.md b/docs/RELEASE-MANUAL-SMOKE.md
index 07609f5ac5..fbdca5710f 100644
--- a/docs/RELEASE-MANUAL-SMOKE.md
+++ b/docs/RELEASE-MANUAL-SMOKE.md
@@ -68,6 +68,7 @@ Applies to every release, all platforms.
- [ ] **Logging out + logging back in preserves nothing private** — Sign out, sign in as a different user. Expected: no leaked memory, threads, or skill state from the previous session (regression watch — see #900).
- [ ] **A Docker core gateway connects, serves the app, and is torn down on switch-back** — Build `openhuman-core:local` (`docker compose build openhuman-core`). In `Settings > Core connection > Run the core somewhere else`, add a location running in a container and choose it. Expected: the status advances through its named steps and settles on Connected; chat, memory, and an agent run work against it; `docker ps` shows one `tinybox-*` container. Switch back to This computer. Expected: the local core answers again and the container is gone. Then relaunch the app while the gateway is selected. Expected: it re-provisions and reconnects rather than silently falling back to the local core — that fallback is the failure this row exists to catch, because everything keeps working against the wrong core.
- [ ] **`memory_tree` migrates WAL→TRUNCATE on upgrade with memory intact** — Install a previous (WAL-era) build, use it enough to populate memory so a `chunks.db-wal`/`-shm` pair exists under `~/.openhuman/.../workspace/memory_tree/`, then upgrade to this build. Expected on first launch: `PRAGMA journal_mode` on `chunks.db` reports `truncate`, the `-wal`/`-shm` side-files are gone, previously-captured memories still surface in recall, and no `Failed to initialize memory_tree schema` errors appear.
+- [ ] **Home connectivity chip reflects the core's hosted link** — Sign in on a desktop build and wait for the chip on Home to read green "Connected". Block the hosted backend for the core for about a minute (e.g. add `127.0.0.1 api.tinyhumans.ai` to the hosts file, or drop the VPN route). Expected: the chip turns amber "Disconnected" within ~30 s while chat keeps working, and returns to green within ~5 s of restoring the route. In `~/.openhuman/logs/openhuman.<date>.log` the `[socket] Connection failed (attempt N/5)` lines are never more than ~10 s plus the backoff apart, and recovery logs `[socket] Reconnected after …` (#6256).
---
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index e628b50e1e..5acd5da8fb 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -311,6 +311,8 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an
| 7.2.3 | TinyFish Integration Tools | RU | `crates/openhuman-core/src/search/tools/tinyfish_tests.rs`, `crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rs::all_tools_executes_tinyfish_family_against_fake_backend` | ✅ | Backend-proxied Search, Fetch, and Agent run tools covered with fake backend |
| 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 |
---
diff --git a/gitbooks/developing/architecture/frontend.md b/gitbooks/developing/architecture/frontend.md
index ff2da58046..b34778d82d 100644
--- a/gitbooks/developing/architecture/frontend.md
+++ b/gitbooks/developing/architecture/frontend.md
@@ -166,7 +166,7 @@ Authoritative list = the `reducer` map in `store/index.ts`. One-line purposes:
| `channelConnections` | Messaging channel connections (WhatsApp, Slack, …) | connections + migration/default-channel fields |
| `chatRuntime` | Streaming buffers, tool timelines, inference status, artifacts | only `artifactsByThread` (ready snapshots) |
| `companion` | Companion overlay state | no |
-| `connectivity` | navigator.onLine + backend/core health status | no |
+| `connectivity` | navigator.onLine, core health, renderer↔core socket, core↔hosted link | no |
| `coreMode` | Pre-login core mode selection (embedded / self-hosted / cloud) | `mode` (plain localStorage) |
| `layout` | Two-pane layout geometry (sidebar visibility, dragged widths) | `panels` |
| `locale` | UI language | `current` (plain localStorage) |