Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: retry the socket forever and show a Reconnecting pill when it stays down
[._.]/ Adam Eivycaa1a6afb711
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 3f62058cad..eec172c0c6 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -45,6 +45,7 @@ import { useSharingNotifications } from '../hooks/useSharingNotifications';import UpdateBanners from './UpdateBanners';import SetupBanner from './SetupBanner';import PasswordRiskWarning from './PasswordRiskWarning.jsx';+import SocketReconnectingPill from './SocketReconnectingPill.jsx';import { useAIStatusNotifications } from '../hooks/useAIStatusNotifications';import { useNavWorkingSet } from '../hooks/useNavWorkingSet.js';import { migrateLegacyNavPath } from '../utils/navWorkingSet.js';@@ -1108,6 +1109,8 @@ export default function Layout() {<CmdKSearch />{/* Keyboard shortcuts help — press ? to toggle */}<KeyboardHelp />+ {/* The one shared "your live views are frozen" signal — see #12027 */}+ <SocketReconnectingPill />{/* Push-to-talk voice widget — self-hides when voice.enabled is false */}<VoiceWidget /></div>diff --git a/client/src/components/Layout.test.jsx b/client/src/components/Layout.test.jsxindex 9d56a2adb9..88274e1dd6 100644--- a/client/src/components/Layout.test.jsx+++ b/client/src/components/Layout.test.jsx@@ -98,6 +98,7 @@ import { __resetInstanceFeatureCache } from '../hooks/useInstanceFeatures.js';import { NAV_COMMANDS } from '../../../server/lib/navManifest.js';import Layout from './Layout';import { isFullWidthRoute } from '../lib/layoutRoutes.js';+import { RECONNECTING_PILL_DELAY_MS } from './SocketReconnectingPill.jsx';import {NAV_PRESENTATION,SECTIONS_BEFORE_GOALS,@@ -130,6 +131,29 @@ const renderLayout = async (initialPath = '/brain/inbox') => {// label shouldn't break these tests). Returns null when the section isn't rendered.const pinnedSection = () => screen.queryByTestId('pinned-section');+describe('Layout — socket reconnecting pill', () => {+ // Plain fake timers: renderLayout settles on microtasks only, and auto-advance+ // would fire Layout's own timers outside act() between assertions.+ beforeEach(() => { vi.useFakeTimers(); });+ afterEach(() => { vi.useRealTimers(); });++ it('shows "Reconnecting…" after the shared socket has been down for the delay and hides it on connect', async () => {+ // The mocked socket reports no `connected` flag, i.e. disconnected from mount.+ await renderLayout();+ expect(screen.queryByText('Reconnecting…')).toBeNull();++ act(() => { vi.advanceTimersByTime(RECONNECTING_PILL_DELAY_MS); });+ expect(screen.getByText('Reconnecting…')).toBeInTheDocument();++ // Every 'connect' handler Layout's hooks registered fires here, and some+ // of them refetch (mocked, resolving on microtasks) — settle inside act.+ await act(async () => {+ for (const [event, handler] of socket.on.mock.calls) if (event === 'connect') handler();+ });+ expect(screen.queryByText('Reconnecting…')).toBeNull();+ });+});+describe('Layout — manifest-derived sidebar structure', () => {it.each([false, true])('keeps global unread notifications off CoS navigation (collapsed: %s)', async (collapsed) => {localStorage.setItem('portos-sidebar-collapsed', String(collapsed));diff --git a/client/src/components/SocketReconnectingPill.jsx b/client/src/components/SocketReconnectingPill.jsxnew file mode 100644index 0000000000..32f199358a--- /dev/null+++ b/client/src/components/SocketReconnectingPill.jsx@@ -0,0 +1,41 @@+import { useEffect, useState } from 'react';+import { WifiOff } from 'lucide-react';+import Pill from './ui/Pill.jsx';+import { useSocketConnected } from '../hooks/useSocket.js';++/**+ * How long the shared socket may stay disconnected before the pill shows.+ * A server restart or a Wi-Fi blip reconnects well inside this window, so+ * the pill marks a real outage (sleep, Tailscale re-establishing) rather+ * than flashing on every PM2 reload.+ */+export const RECONNECTING_PILL_DELAY_MS = 10_000;++/**+ * Small "Reconnecting…" status pill for the app shell. Every live view in+ * PortOS is push-driven, so a dead socket leaves the page looking current+ * while silently frozen (#12027); this is the one shared surface that says+ * so. Mounted once from Layout.jsx.+ */+export default function SocketReconnectingPill() {+ const connected = useSocketConnected();+ const [visible, setVisible] = useState(false);++ useEffect(() => {+ if (connected) {+ setVisible(false);+ return undefined;+ }+ const timer = setTimeout(() => setVisible(true), RECONNECTING_PILL_DELAY_MS);+ return () => clearTimeout(timer);+ }, [connected]);++ if (!visible) return null;+ return (+ <div className="fixed top-2 left-1/2 -translate-x-1/2 z-[60] pointer-events-none print:hidden">+ <Pill tone="warning" icon={WifiOff} role="status" aria-live="polite" className="shadow-lg bg-port-card">+ Reconnecting…+ </Pill>+ </div>+ );+}diff --git a/client/src/components/SocketReconnectingPill.test.jsx b/client/src/components/SocketReconnectingPill.test.jsxnew file mode 100644index 0000000000..27cf48888e--- /dev/null+++ b/client/src/components/SocketReconnectingPill.test.jsx@@ -0,0 +1,65 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { render, screen, act, cleanup } from '@testing-library/react';++// Drive the shared socket's connect/disconnect handlers by hand so the test+// pins the pill's timing without a transport.+const handlers = new Map();+const socketState = { connected: false };+vi.mock('../services/socket', () => ({+ default: {+ get connected() { return socketState.connected; },+ on: (event, fn) => {+ if (!handlers.has(event)) handlers.set(event, new Set());+ handlers.get(event).add(fn);+ },+ off: (event, fn) => { handlers.get(event)?.delete(fn); },+ },+}));++const { default: SocketReconnectingPill, RECONNECTING_PILL_DELAY_MS } = await import('./SocketReconnectingPill.jsx');++const fire = (event) => act(() => {+ socketState.connected = event === 'connect';+ for (const fn of [...(handlers.get(event) || [])]) fn();+});+const advance = (ms) => act(() => { vi.advanceTimersByTime(ms); });+const pill = () => screen.queryByText('Reconnecting…');++beforeEach(() => {+ vi.useFakeTimers();+ handlers.clear();+ socketState.connected = false;+});+afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++describe('SocketReconnectingPill', () => {+ it('appears only after the socket has been down for the full delay, and clears on reconnect', () => {+ render(<SocketReconnectingPill />);+ expect(pill()).toBeNull();++ advance(RECONNECTING_PILL_DELAY_MS - 1);+ expect(pill()).toBeNull();+ advance(1);+ expect(pill()).toBeInTheDocument();+ expect(screen.getByRole('status')).toHaveTextContent('Reconnecting…');++ fire('connect');+ expect(pill()).toBeNull();+ });++ it('stays hidden for a blip that reconnects inside the delay', () => {+ socketState.connected = true;+ render(<SocketReconnectingPill />);+ advance(RECONNECTING_PILL_DELAY_MS * 2);+ expect(pill()).toBeNull();++ fire('disconnect');+ advance(RECONNECTING_PILL_DELAY_MS / 2);+ fire('connect');+ advance(RECONNECTING_PILL_DELAY_MS * 2);+ expect(pill()).toBeNull();+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 00b92b6914..c938986b4a 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -98,7 +98,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useFableLoomRun` | Revisioned editorial/production snapshots, identity-safe mutation replies and entry/reconnect/reshow recovery. | FableLoom run views. || `useSocketSubscription` | Refcounted `<namespace>:subscribe`/`unsubscribe` for a `registerSubscriber` room: the first mounted consumer subscribes and re-emits on every socket reconnect, the last to unmount unsubscribes, and `onResubscribe` refetches whatever a consumer may have missed while disconnected. | Any hook/page that emits a literal `<ns>:subscribe` for `cos`/`errors`/`notifications`/`agents`/`instances`/`loops`/`beeper` — don't hand-roll the reconnect dance; `client/src/socketSubscriptionConventions.test.js` enforces this. || `useAccountSyncStatus` | Per-account busy/auth state and deduplicated HTTP/socket sync outcomes. | Calendar and Messages sync controls. |-| `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |+| `useSocket` | Shared socket instance; the caller re-renders on connect/disconnect. `useSocketConnected` (same file) returns the live connected flag as a boolean. | You need to subscribe to a socket event, or show connection state (`components/SocketReconnectingPill.jsx`). || `useItermSession` | Socket.IO `iterm:*` state for the Shell page's iTerm2 view (#8114): list subscription, URL-selected attach with a strict pending-target guard, byte-exact input, and an xterm sized to iTerm2's own grid (never fit, never resized back). Never touches `shell:*`. || `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCd, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. `sendCd(path)` sends a FOLDER over `shell:cd` rather than composing a `cd` line — the server renders it for the session's actual shell (`server/lib/shellCd.js`), which is the only form that works on a Windows cmd.exe session. `sendCommand(cmd)` submits with CR, never `\n` (see `SUBMIT_KEY` in `server/lib/tuiHandshake.js`). `sendImage(file, message)` is the one operation that leaves the socket — it POSTs to `/api/shell/sessions/:id/image` so a running agent TUI gets the photo's path pasted into its prompt. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. || `useUpdateChecker` | Update-available + install-out-of-sync advisories as *state* (`{ update, outOfSync, ignoreUpdate, dismissUpdate, clearOutOfSync, dismissOutOfSync }`), never toasts — a non-transient advisory must not occlude the screen's primary action (#3786). Out-of-sync dismissals persist per on-disk commit in `safeStorage`, so a later `git pull` re-raises; `clearOutOfSync` is the session-only clear used when the user acts on it. | Never call it directly — `components/UpdateBanners` owns the single instance and Layout renders that once at the app root. A second caller means a second status fetch and socket subscription. |diff --git a/client/src/hooks/useSocket.js b/client/src/hooks/useSocket.jsindex d3a8c02534..32a7807e11 100644--- a/client/src/hooks/useSocket.js+++ b/client/src/hooks/useSocket.js@@ -2,11 +2,13 @@ import { useEffect, useState } from 'react';import socket from '../services/socket';/**- * Hook to access the shared socket instance and track connection status.- * Uses the singleton socket from services/socket.js to avoid duplicate connections.+ * Live `socket.connected` as React state: flips on every `connect` /+ * `disconnect` so a consumer re-renders when the shared transport drops or+ * recovers. Reads the current value at mount (and again inside the effect)+ * so a hook mounted mid-reconnect does not report a stale initial state.*/-export function useSocket() {- const [, setConnected] = useState(socket.connected);+export function useSocketConnected() {+ const [connected, setConnected] = useState(() => Boolean(socket.connected));useEffect(() => {const handleConnect = () => setConnected(true);@@ -14,9 +16,7 @@ export function useSocket() {socket.on('connect', handleConnect);socket.on('disconnect', handleDisconnect);-- // Set initial state- setConnected(socket.connected);+ setConnected(Boolean(socket.connected));return () => {socket.off('connect', handleConnect);@@ -24,6 +24,17 @@ export function useSocket() {};}, []);+ return connected;+}++/**+ * Hook to access the shared socket instance. Uses the singleton socket from+ * services/socket.js to avoid duplicate connections, and re-renders the+ * caller on connect/disconnect so a `socket.connected` read in render is+ * never stale. Use `useSocketConnected()` to read that flag as a value.+ */+export function useSocket() {+ useSocketConnected();return socket;}diff --git a/client/src/services/socket.js b/client/src/services/socket.jsindex ba6544a1b8..f9d4958f77 100644--- a/client/src/services/socket.js+++ b/client/src/services/socket.js@@ -9,22 +9,37 @@ import toast from '../components/ui/Toast';// The connection will use the same host the page was loaded fromconst isHostedAudienceRoute = typeof window !== 'undefined' &&isPublicGuestRoute(window.location.pathname);+// The server is the user's own machine, so there is no "give up" case: a+// capped attempt count (#12027) left every push-driven view silently frozen+// after a laptop sleep outlasted the retries, because nothing re-arms the+// manager once it emits `reconnect_failed`. Retry forever, with the backoff+// capped so recovery after a long outage never waits more than 10 s.const socket = io({path: '/socket.io',transports: ['websocket', 'polling'],autoConnect: !isHostedAudienceRoute,reconnection: true,- reconnectionAttempts: 10,- reconnectionDelay: 1000+ reconnectionAttempts: Infinity,+ reconnectionDelay: 1000,+ reconnectionDelayMax: 10000});-socket.on('connect', () => {- // Connection established-});+// Belt and braces for the backoff: the browser knows the moment the network+// is back (`online`) and the moment the user is looking again (tab visible),+// so reconnect right then instead of waiting out the current backoff. A+// hosted-audience route never opens this socket (`autoConnect` above), and+// `connect()` is a no-op while the manager already has a reconnect in flight.+const reconnectIfDisconnected = () => {+ if (isHostedAudienceRoute || socket.connected) return;+ socket.connect();+};-socket.on('disconnect', () => {- // Connection lost - Socket.IO will attempt reconnection automatically-});+if (typeof window !== 'undefined') {+ window.addEventListener('online', reconnectIfDisconnected);+ document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible') reconnectIfDisconnected();+ });+}socket.on('connect_error', (err) => {// Auth gate rejected the handshake (server: services/authGate.js socketAuthGate).diff --git a/client/src/services/socket.test.js b/client/src/services/socket.test.jsnew file mode 100644index 0000000000..ef186d860a--- /dev/null+++ b/client/src/services/socket.test.js@@ -0,0 +1,94 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// The transport is the one thing under test, so socket.io-client is replaced+// with a fake that records its options and exposes `connected` + `connect()`.+// Everything else socket.js wires at import (build-drift watcher, auth bounce)+// is mocked to its exported surface only.+const fake = vi.hoisted(() => ({ socket: null, ioOptions: null, guestRoute: false }));++vi.mock('socket.io-client', () => ({+ io: vi.fn((options) => {+ fake.ioOptions = options;+ fake.socket = {+ connected: false,+ on: vi.fn(),+ off: vi.fn(),+ emit: vi.fn(),+ connect: vi.fn(),+ };+ return fake.socket;+ }),+}));+vi.mock('../lib/publicGuestRoutes', () => ({ isPublicGuestRoute: () => fake.guestRoute }));+vi.mock('./apiSystem', () => ({ getSystemBuild: vi.fn(() => new Promise(() => {})) }));+vi.mock('./staleBuildToast', () => ({ showStaleBuildToast: vi.fn() }));+vi.mock('../components/ui/Toast', () => ({ default: { dismiss: vi.fn() } }));++const setVisibility = (state) => {+ Object.defineProperty(document, 'visibilityState', { value: state, configurable: true });+};++const loadSocket = async () => {+ vi.resetModules();+ await import('./socket.js');+ return fake.socket;+};++beforeEach(() => {+ fake.guestRoute = false;+ setVisibility('visible');+});+afterEach(() => {+ // The module registers window/document listeners at import; a fresh module+ // per test adds another set, so drop the old socket's reach by replacing it.+ fake.socket = null;+});++describe('services/socket reconnect policy (#12027)', () => {+ it('retries forever with a capped backoff instead of giving up after ten attempts', async () => {+ await loadSocket();+ expect(fake.ioOptions).toMatchObject({+ reconnection: true,+ reconnectionAttempts: Infinity,+ reconnectionDelayMax: 10000,+ });+ });++ it('reconnects when the browser comes back online while the socket is down', async () => {+ const socket = await loadSocket();+ // The state the old attempt cap left behind: manager gave up, nothing+ // scheduled, `connected` false for the rest of the tab's life.+ socket.connected = false;+ window.dispatchEvent(new Event('online'));+ expect(socket.connect).toHaveBeenCalledTimes(1);+ });++ it('reconnects when the tab becomes visible while the socket is down', async () => {+ const socket = await loadSocket();+ socket.connected = false;+ setVisibility('hidden');+ document.dispatchEvent(new Event('visibilitychange'));+ expect(socket.connect).not.toHaveBeenCalled();++ setVisibility('visible');+ document.dispatchEvent(new Event('visibilitychange'));+ expect(socket.connect).toHaveBeenCalledTimes(1);+ });++ it('leaves a live socket alone', async () => {+ const socket = await loadSocket();+ socket.connected = true;+ window.dispatchEvent(new Event('online'));+ document.dispatchEvent(new Event('visibilitychange'));+ expect(socket.connect).not.toHaveBeenCalled();+ });++ it('never opens the private socket from a hosted-audience route', async () => {+ fake.guestRoute = true;+ const socket = await loadSocket();+ expect(fake.ioOptions.autoConnect).toBe(false);+ socket.connected = false;+ window.dispatchEvent(new Event('online'));+ expect(socket.connect).not.toHaveBeenCalled();+ });+});