Skip to content

Self-improving AI Employees for everyone

feat(auth): Connecting screen in front of the app, and over it when the server goes away

trohitg21a3fc90dd6e
diff --git a/CLAUDE.md b/CLAUDE.md
index 03825a5e..04e54910 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1239,7 +1239,7 @@ The historical Docker Compose topology (4-container stack: redis / backend / fro
## Authentication System
-n8n-style JWT auth in HttpOnly cookies. `VITE_AUTH_ENABLED=false` bypasses login (anonymous owner, dev); when enabled, `AUTH_MODE=single` (first user = owner, registration then closed) or `multi` (open registration). Backend: `User` (bcrypt) + `UserAuthService` + `/api/auth/*` router + `AuthMiddleware` (public-path allowlist + `/webhook/` prefix). `/login` and `/register` are throttled by the in-process `core/rate_limit.py` sliding window (`AUTH_RATE_LIMIT_*`; no `slowapi` dependency — the primary runtime is a single uvicorn worker). Frontend: `AuthContext` (TanStack-Query bootstrap with full-jitter backoff, plus `useMutation` for login/register/logout) + `ProtectedRoute` + `LoginPage` (RHF + zod via the shadcn `Form` primitives); all API calls send `credentials: 'include'`, and the WebSocket refuses to connect without the cookie.
+n8n-style JWT auth in HttpOnly cookies. `VITE_AUTH_ENABLED=false` bypasses login (anonymous owner, dev); when enabled, `AUTH_MODE=single` (first user = owner, registration then closed) or `multi` (open registration). Backend: `User` (bcrypt) + `UserAuthService` + `/api/auth/*` router + `AuthMiddleware` (public-path allowlist + `/webhook/` prefix). `/login` and `/register` are throttled by the in-process `core/rate_limit.py` sliding window (`AUTH_RATE_LIMIT_*`; no `slowapi` dependency — the primary runtime is a single uvicorn worker). Frontend: `AuthContext` (a TanStack-Query bootstrap check that never retries on its own, plus `useMutation` for login/register/logout) + `ProtectedRoute` (the sign-in gate: Connecting while the server can't be reached, then sign-in or the app, and Connecting over the app while the WebSocket is down) + `LoginPage` (RHF + zod via the shadcn `Form` primitives); all API calls send `credentials: 'include'`, and the WebSocket refuses to connect without the cookie.
**Two context distinctions that are load-bearing, not stylistic:** `isLoading` is the bootstrap query (gates the whole app in `ProtectedRoute`) while `isSubmitting` is per-request — using the former to disable the login form disables nothing, since it has already settled by the time that form renders. And `error` means "cannot reach the server" while `submitError` is the server's own rejection text; a `setQueryData` write is a *success* value, so routing a login failure through the status cache surfaces no error at all and additionally collapses `can_register`.
@@ -2425,7 +2425,7 @@ export const useNodeStatus = (nodeId: string): NodeStatus => { ... }
Features:
- Auto-connect on mount
-- Reconnect with jittered exponential backoff through PartySocket (`WS_RECONNECT` in `client/src/lib/connectionConfig.ts`); a remote close, even with code 1000, keeps retrying, and only logout or unmount (`disposeConnection`) stops it
+- Reconnect with exponential backoff through PartySocket (`WS_RECONNECT` in `client/src/lib/connectionConfig.ts`, no jitter); a remote close, even with code 1000, keeps retrying, and only logout or unmount (`disposeConnection`) stops it
- App heartbeat (`client/src/lib/webSocketHeartbeat.ts`): a ping every 30 s while the page is visible; no pong within 10 s forces a reconnect
- Message type handlers for all status update types
@@ -2690,7 +2690,7 @@ This function:
- Variable value changes
- Workflow execution progress
- Replaces API polling with push-based updates
- - Auto-reconnect with jittered exponential backoff plus an app-level heartbeat (see "WebSocket Reconnect via PartySocket" below)
+ - Auto-reconnect with exponential backoff plus an app-level heartbeat (see "WebSocket Reconnect via PartySocket" below)
- Real device detection distinguishes actual devices (with timestamp suffix) from base names
- **Android two-state model**: `connected` (relay WebSocket) vs `paired` (device paired)
- Android service nodes use `paired` status for indicator (green = paired, red = not paired)
@@ -2737,12 +2737,12 @@ This function:
- `server/core/database.py` - Cache CRUD methods (get/set/delete/cleanup)
- Supports TTL expiration and automatic cleanup of expired entries
- **Conditional Redis (historical)**: the Docker Compose topology (Redis profiles, `scripts/docker.js` wrapper) is historical — see [docs-internal/deployment_legacy.md](./docs-internal/deployment_legacy.md)
-- **WebSocket Reconnect via PartySocket** (`partysocket/ws` from Cloudflare): native-WS-compatible class handles jittered exponential backoff and replays sends buffered while disconnected (`maxEnqueuedMessages: 200`). A remote close keeps it retrying whatever the code, including 1000 (RFC 6455 §7.4.1 Normal Closure); only an explicit `close()` stops it, which `disposeConnection` does on logout and unmount. An app-level heartbeat (`client/src/lib/webSocketHeartbeat.ts`, `WS_HEARTBEAT`: 30 s ping, 10 s pong deadline, visible pages only) reconnects a socket that stopped answering, with close code 4000. Replaces the previous flat 3 s `setTimeout(connect, 3000)` loop. Reconnect envelope (`MIN_DELAY_MS: 250`, `MAX_DELAY_MS: 8000`, `GROW_FACTOR: 1.3`) lives in `client/src/lib/connectionConfig.ts`. The +12 s WS-drop-and-reconnect cycle observed under React Strict Mode is gone — verified across two consecutive cold launches with zero `Client disconnected` events through 130+ s of activity. See `docs-internal/performance.md` for measurements.
+- **WebSocket Reconnect via PartySocket** (`partysocket/ws` from Cloudflare): native-WS-compatible class handles exponential backoff (`MIN_DELAY_MS · GROW_FACTOR^(n-1)`, capped; no jitter, since PartySocket randomises only its own default minimum, which ours replaces) and replays sends buffered while disconnected (`maxEnqueuedMessages: 200`). While it is down after sign-in, the sign-in gate (`components/auth/ProtectedRoute.tsx`) shows Connecting over the app, read from `useWebSocketActions().reconnecting`. A remote close keeps it retrying whatever the code, including 1000 (RFC 6455 §7.4.1 Normal Closure); only an explicit `close()` stops it, which `disposeConnection` does on logout and unmount. An app-level heartbeat (`client/src/lib/webSocketHeartbeat.ts`, `WS_HEARTBEAT`: 30 s ping, 10 s pong deadline, visible pages only) reconnects a socket that stopped answering, with close code 4000. Replaces the previous flat 3 s `setTimeout(connect, 3000)` loop. Reconnect envelope (`MIN_DELAY_MS: 250`, `MAX_DELAY_MS: 8000`, `GROW_FACTOR: 1.3`) lives in `client/src/lib/connectionConfig.ts`. The +12 s WS-drop-and-reconnect cycle observed under React Strict Mode is gone — verified across two consecutive cold launches with zero `Client disconnected` events through 130+ s of activity. See `docs-internal/performance.md` for measurements.
- **Docker image runs uvicorn, not `company serve`**: `docker/entrypoint.sh` writes the three secrets into `/data/opencompany.env` once (the container env's value when set there, else a random one), then execs the desktop shell's uvicorn argv (`--timeout-graceful-shutdown 5`, port resolved through `core.env_defaults`). `company serve` would need root `node_modules` + the CLI venv, ignores `OPENCOMPANY_ENV_FILE`, and its supervisor would add a second tree-kill deadline (`backend_shutdown_grace_seconds`, `cli/_common.py`). `HOST` stays `127.0.0.1` (the backend dials itself at `ws://HOST:PORT/ws/internal`); the external bind is the `--host 0.0.0.0` argument. The image has no Node: `/usr/local/bin/node` links to bun, so the `#!/usr/bin/env node` bin scripts (vercel, cf) run. The Dockerfile now sets `BROWSER_RUNTIME=system`, `BROWSER_FAMILY=chromium` and `BROWSER_HEADLESS=true`; the browser extra supplies Chromium. This matches the default of rendering inside the workspace without a desktop window. The retired agent-browser variable `AGENT_BROWSER_EXECUTABLE_PATH` is no longer in the image. Installed-browser discovery, opt-in Chrome for Testing/browser-use installation and explicit headless deployment requirements are documented in [Browser](./docs-internal/browser.md). The compose project is named `opencompany-selfhost` so it never merges with another compose project called `opencompany`. See [docker.md](./docs-internal/docker.md).
- **Configurable Authentication**: `VITE_AUTH_ENABLED` environment variable
- Set to `false` to bypass login entirely (useful for local development)
- Frontend creates anonymous user with owner privileges when disabled
- - AuthContext bootstraps via TanStack Query `useQuery({queryKey: ['auth','status'], retry, retryDelay, signal})` — replaced the previous recursive `setTimeout` chain. Full-jitter exponential backoff per the AWS Architecture Blog formula `random(0, min(CAP_MS, BASE_MS * 2^attempt))` with `BASE_MS=50`, `CAP_MS=4000`, `MAX_ATTEMPTS=7` (constants in `client/src/lib/connectionConfig.ts`). Cumulative budget ~10 s vs. the old 31 s; sub-second granularity early covers the typical 4 s backend cold-start window in 4-5 attempts. 401/403 short-circuit the retry chain (no budget burn for "auth disabled / not logged in" responses). `signal` (AbortController) plumbed through `queryFn` so unmount + Strict Mode cleanup cancel in-flight requests automatically. login / register / logout invalidate the cache via `queryClient.invalidateQueries(AUTH_STATUS_QUERY_KEY)`.
+ - AuthContext checks via TanStack Query `useQuery({queryKey: ['auth','status'], retry: false, networkMode: 'always', signal})` and never retries on its own: while the server can't be reached the sign-in gate shows Connecting, which checks again through `checkAuth` after 2, 3, 5 and then every 8 s (`CONNECT_RETRY` in `client/src/lib/connectionConfig.ts`), with a countdown, Try now and the attempt on screen, then holds "Connected" 1.5 s before sign-in or the app (see [Authentication](./docs-internal/authentication.md)). `checkAuth` says whether the server answered; a failed check keeps the last answer. `signal` (AbortController) plumbed through `queryFn` so unmount + Strict Mode cleanup cancel in-flight requests automatically. login / register / logout invalidate the cache via `queryClient.invalidateQueries(AUTH_STATUS_QUERY_KEY)`.
- The backend reads the same variable through `Settings.vite_auth_enabled` (auth middleware, `routers/auth.py`, WebSocket session checks, the dev-secret guard); `Settings` itself ignores unknown variables (`extra="ignore"`)
- **CloudEvents v1.0 envelope on the wire (preserved end-to-end)**: backend `WorkflowEvent` ([server/services/events/envelope.py](./server/services/events/envelope.py)) and frontend `WorkflowEvent<T>` interface ([client/src/types/cloudEvents.ts](./client/src/types/cloudEvents.ts)) mirror each other. `matchesType(event, 'credential.api_key.*')` parity-tested vs `WorkflowEvent.matches_type` Pydantic method. Today wraps inside the legacy `{type, data}` WS frame (e.g. `credential_catalogue_updated` → `data: <envelope>`); future Wave 12 sources (`stripe.*`, `telegram.*`, `task.*`) drop into the same envelope so a single FE switch case routes them via glob dispatch instead of inventing per-source wire keys.
- **whatsapp-rpc Package**: External dependency for WhatsApp integration
diff --git a/client/src/app/ShellThemeProvider.tsx b/client/src/app/ShellThemeProvider.tsx
index 3d7c7c68..162dec78 100644
--- a/client/src/app/ShellThemeProvider.tsx
+++ b/client/src/app/ShellThemeProvider.tsx
@@ -1,19 +1,21 @@
/**
- * The app's ThemeProvider, with the shell's rule: Home (Normal mode) shows
- * the base theme of the chosen theme's family, light or dark, because Home
- * is designed for those two only. The editor (Dev mode) shows the chosen
- * theme itself, stylized or not. Switching modes moves between the two
- * without changing the choice. index.html's pre-paint script applies the
- * same rule to the first frame.
+ * The app's ThemeProvider, with the shell's rule: Home (Normal mode) and
+ * the sign-in gate's screens (Connecting, sign-in) show the base theme of
+ * the chosen theme's family, light or dark, because they are designed for
+ * those two only. The editor (Dev mode) shows the chosen theme itself,
+ * stylized or not. Moving between them never changes the choice.
+ * index.html's pre-paint script applies the mode rule to the first frame.
*/
import type { ReactNode } from 'react';
import { ThemeProvider } from '../contexts/ThemeContext';
+import { useShellDialogsStore } from '../stores/shellDialogsStore';
import { useShellMode } from './ShellModeSwitch';
export function ShellThemeProvider({ children }: { children: ReactNode }) {
const mode = useShellMode();
- return <ThemeProvider baseOnly={mode === 'normal'}>{children}</ThemeProvider>;
+ const connectScreen = useShellDialogsStore((s) => s.connectScreenOpen);
+ return <ThemeProvider baseOnly={mode === 'normal' || connectScreen}>{children}</ThemeProvider>;
}
export default ShellThemeProvider;
diff --git a/client/src/components/auth/ConnectScreen.tsx b/client/src/components/auth/ConnectScreen.tsx
new file mode 100644
index 00000000..a7e421e1
--- /dev/null
+++ b/client/src/components/auth/ConnectScreen.tsx
@@ -0,0 +1,42 @@
+/**
+ * The screen the sign-in gate shows before the app (onboarding handoff R4,
+ * R5): the whole window in the app's background, the orb filling it, and a
+ * top bar with the logo and the theme button. Connecting and sign-in render
+ * inside one, so the orb glides from one's slot to the other's. As the
+ * overlay (signed in, the server away) it covers the app, which stays
+ * mounted underneath and inert, and borrows the orb until it goes. While
+ * one shows, the theme is the base of the chosen family, as on Home.
+ */
+
+import { useLayoutEffect, type ReactNode } from 'react';
+import { OcLogo } from '@/components/brand/Logo';
+import { ThemeButton } from '@/features/home/header/ThemeButton';
+import { OrbStage } from '@/features/home/orb/OrbStage';
+import { cn } from '@/lib/utils';
+import { useShellDialogsStore } from '@/stores/shellDialogsStore';
+
+export function ConnectScreen({ overlay = false, children }: { overlay?: boolean; children: ReactNode }) {
+ useLayoutEffect(() => {
+ const { setConnectScreenOpen } = useShellDialogsStore.getState();
+ setConnectScreenOpen(true);
+ return () => setConnectScreenOpen(false);
+ }, []);
+
+ return (
+ <div
+ role={overlay ? 'dialog' : undefined}
+ aria-modal={overlay ? true : undefined}
+ aria-label={overlay ? 'Reconnecting to OpenCompany' : undefined}
+ className={cn('fixed inset-0 overflow-y-auto bg-bg-app text-fg-default', overlay && 'z-60')}
+ >
+ <OrbStage fill="screen" />
+ <div className="absolute inset-x-0 top-0 z-10 flex items-center justify-between px-5 py-4">
+ <OcLogo size="header" />
+ <ThemeButton />
+ </div>
+ <div className="relative z-1 flex min-h-full flex-col items-center justify-center px-6 pt-18 pb-10">{children}</div>
+ </div>
+ );
+}
+
+export default ConnectScreen;
diff --git a/client/src/components/auth/ConnectingPanel.tsx b/client/src/components/auth/ConnectingPanel.tsx
new file mode 100644
index 00000000..8afe0bbe
--- /dev/null
+++ b/client/src/components/auth/ConnectingPanel.tsx
@@ -0,0 +1,128 @@
+/**
+ * Connecting (onboarding handoff R4): while the server can't be reached,
+ * the orb waits and a pill counts down to the next check, with the attempt
+ * and Try now (useRetrySchedule); from the third attempt a line says to
+ * make sure OpenCompany is running. Once the server answers, a green
+ * "Connected" pops in and the orb spikes; the gate moves on a moment later.
+ *
+ * The countdown is not read out every second: one status line for screen
+ * readers says what changed (another attempt, the server found, connected).
+ * `again` is the overlay's case: the app was running and lost the server.
+ */
+
+import { Check } from 'lucide-react';
+import { useEffect, useLayoutEffect, useRef } from 'react';
+import { Button } from '@/components/ui/button';
+import { RingSpinner } from '@/components/ui/ring-spinner';
+import { SPIKE, setOrbWaiting, spikeOrb } from '@/features/home/orb/orb';
+import { OrbSlot } from '@/features/home/orb/OrbSlot';
+import { CONNECT_RETRY } from '@/lib/connectionConfig';
+import { animate, rise } from '@/lib/motion';
+import { cn } from '@/lib/utils';
+import { useRetrySchedule } from './useRetrySchedule';
+
+function ConnectedPill() {
+ const ref = useRef<HTMLSpanElement>(null);
+ useLayoutEffect(() => {
+ animate(ref.current, [{ opacity: 0, transform: 'scale(0.92)' }, { opacity: 1, transform: 'none' }], {
+ duration: 'chip-pop',
+ easing: 'overshoot',
+ });
+ }, []);
+ return (
+ <span
+ ref={ref}
+ className="mt-2 inline-flex h-10 items-center gap-2 rounded-pill border border-status-working-border bg-status-working-fill px-4 text-row font-semibold text-status-working-ink shadow-glow-connect"
+ >
+ <Check aria-hidden className="size-3.75" strokeWidth={2.5} />
+ Connected
+ </span>
+ );
+}
+
+export function ConnectingPanel({
+ check,
+ connected,
+ again = false,
+}: {
+ /** Checks the server once; true when it answered. */
+ check: () => Promise<boolean>;
+ /** The gate has what it waited for. */
+ connected: boolean;
+ again?: boolean;
+}) {
+ const { attempt, wait, checking, found, tryNow } = useRetrySchedule(check);
+ const eyebrowRef = useRef<HTMLParagraphElement>(null);
+ const titleRef = useRef<HTMLHeadingElement>(null);
+ const pillRef = useRef<HTMLDivElement>(null);
+
+ useLayoutEffect(() => {
+ rise(eyebrowRef.current);
+ rise(titleRef.current, { delay: 80 });
+ rise(pillRef.current, { delay: 240 });
+ }, []);
+
+ useEffect(() => {
+ setOrbWaiting(!connected);
+ if (connected) spikeOrb(SPIKE.connected);
+ }, [connected]);
+ useEffect(() => () => setOrbWaiting(false), []);
+
+ const reached = connected || found;
+ const eyebrow = reached ? 'Server found' : again || attempt > 1 ? 'Reconnecting' : 'Connecting';
+ const countdown = checking || found ? 'Connecting…' : `Trying again in ${wait}s`;
+ const help = !connected && attempt >= CONNECT_RETRY.HELP_FROM_ATTEMPT;
+ const status = connected
+ ? 'Connected'
+ : found
+ ? 'Found the OpenCompany server. Connecting.'
+ : `Can’t reach OpenCompany yet. Attempt ${attempt}.`;
+
+ return (
+ <div className="flex w-full max-w-130 flex-col items-center gap-3.5 text-center">
+ <OrbSlot size="connecting" />
+ <p ref={eyebrowRef} className="m-0 flex items-center gap-2 font-mono text-xs font-medium tracking-label text-fg-muted uppercase">
+ <span
+ aria-hidden
+ className={cn(
+ 'size-1.5 rounded-full bg-current shadow-pip',
+ reached ? 'text-status-working-dot' : 'opencompany-pip-pulse text-status-waiting-dot',
+ )}
+ />
+ {eyebrow}
+ </p>
+ <h1 ref={titleRef} className="m-0 text-2xl leading-hero font-semibold tracking-hero text-balance text-fg-default">
+ {connected ? 'Connected' : 'Waking up OpenCompany'}
+ </h1>
+ {connected ? (
+ <ConnectedPill />
+ ) : (
+ <div
+ ref={pillRef}
+ className="mt-2 inline-flex h-10 items-center gap-2.5 rounded-pill border border-border-default bg-bg-panel pr-1.5 pl-3.5 shadow-float"
+ >
+ <RingSpinner className="size-3 border-status-waiting-border border-t-status-waiting-dot" />
+ <span aria-hidden className="min-w-33 text-left font-mono text-xs text-fg-default">
+ {countdown}
+ </span>
+ <span aria-hidden className="h-4 w-px bg-border-default" />
+ <span className="font-mono text-2xs text-fg-faint">Attempt {attempt}</span>
+ <Button
+ variant="quiet"
+ onClick={tryNow}
+ disabled={checking || found}
+ className="h-7 rounded-pill border-border-default bg-bg-elevated px-3 text-meta font-semibold text-fg-default"
+ >
+ Try now
+ </Button>
+ </div>
+ )}
+ {help && <p className="m-0 mt-1.5 text-sm text-fg-muted">Still nothing? Make sure OpenCompany is running.</p>}
+ <p role="status" className="sr-only">
+ {status}
+ </p>
+ </div>
+ );
+}
+
+export default ConnectingPanel;
diff --git a/client/src/components/auth/ProtectedRoute.tsx b/client/src/components/auth/ProtectedRoute.tsx
index 09d44601..5320a825 100644
--- a/client/src/components/auth/ProtectedRoute.tsx
+++ b/client/src/components/auth/ProtectedRoute.tsx
@@ -1,40 +1,72 @@
/**
- * Protected Route component.
- * Wraps content that requires authentication.
- * Shows LoginPage if user is not authenticated.
+ * The sign-in gate: what shows before the app (onboarding handoff R4).
+ *
+ * | State | Shows |
+ * |-----------------------------------------|------------------------------------------------|
+ * | checking the session | a loading screen |
+ * | the server can't be reached | Connecting: a countdown to each check, Try now |
+ * | the server answered | "Connected", for CONNECT_RETRY.CONNECTED_HOLD_MS |
+ * | then | sign-in, or the app (a good session, or login off) |
+ * | signed in, the WebSocket down | Connecting over the app |
+ *
+ * Connecting and sign-in render in one ConnectScreen, so the orb glides
+ * between their slots. Over the app, the app stays mounted and inert, and
+ * the checks are HTTP session checks, so a session that expired while the
+ * server was away goes to sign-in; the overlay goes once the WebSocket is
+ * back. The auth check never retries on its own (AuthContext).
*/
import React from 'react';
import { Loader2 } from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
+import { useWebSocketActions } from '../../contexts/WebSocketContext';
+import { CONNECT_RETRY } from '../../lib/connectionConfig';
+import { ConnectingPanel } from './ConnectingPanel';
+import { ConnectScreen } from './ConnectScreen';
import LoginPage from './LoginPage';
+import { useHold } from './useHold';
-interface ProtectedRouteProps {
- children: React.ReactNode;
+function ScreenLoading() {
+ return (
+ <div className="flex h-screen items-center justify-center bg-background text-foreground">
+ <div className="text-center">
+ <Loader2 className="mx-auto mb-4 h-10 w-10 animate-spin text-node-agent" />
+ <p>Loading...</p>
+ </div>
+ </div>
+ );
}
-const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
- const { isAuthenticated, isLoading } = useAuth();
+const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const { isAuthenticated, isLoading, error, checkAuth } = useAuth();
+ const { reconnecting } = useWebSocketActions();
+ const unreachable = error !== null && !isAuthenticated;
+ const connecting = useHold(unreachable, CONNECT_RETRY.CONNECTED_HOLD_MS);
+ const away = isAuthenticated && reconnecting;
+ const overlay = useHold(away, CONNECT_RETRY.CONNECTED_HOLD_MS);
+
+ if (isLoading) return <ScreenLoading />;
- // Show loading spinner while checking auth
- if (isLoading) {
+ if (connecting || !isAuthenticated) {
return (
- <div className="flex h-screen items-center justify-center bg-background text-foreground">
- <div className="text-center">
- <Loader2 className="mx-auto mb-4 h-10 w-10 animate-spin text-node-agent" />
- <p>Loading...</p>
- </div>
- </div>
+ <ConnectScreen>
+ {connecting ? <ConnectingPanel check={checkAuth} connected={!unreachable} /> : <LoginPage />}
+ </ConnectScreen>
);
}
- // Show login page if not authenticated
- if (!isAuthenticated) {
- return <LoginPage />;
- }
-
- // Render protected content
- return <>{children}</>;
+ return (
+ <>
+ <div className="contents" inert={overlay}>
+ {children}
+ </div>
+ {overlay && (
+ <ConnectScreen overlay>
+ <ConnectingPanel check={checkAuth} connected={!away} again />
+ </ConnectScreen>
+ )}
+ </>
+ );
};
export default ProtectedRoute;
diff --git a/client/src/components/auth/__tests__/ProtectedRoute.test.tsx b/client/src/components/auth/__tests__/ProtectedRoute.test.tsx
new file mode 100644
index 00000000..90699c1f
--- /dev/null
+++ b/client/src/components/auth/__tests__/ProtectedRoute.test.tsx
@@ -0,0 +1,159 @@
+/**
+ * The sign-in gate's states (ProtectedRoute): a loading screen while the
+ * session is checked; Connecting while the server can't be reached, with
+ * its countdown, attempts and help; "Connected" held a moment once it
+ * answers, then sign-in or the app; and, signed in, Connecting over the
+ * app while the WebSocket is down, the app staying mounted, an expired
+ * session going to sign-in. The theme shows as its base while a
+ * Connecting or sign-in screen is up.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, render, screen } from '@testing-library/react';
+import { useEffect } from 'react';
+
+interface Auth {
+ isAuthenticated: boolean;
+ isLoading: boolean;
+ error: string | null;
+ checkAuth: () => Promise<boolean>;
+}
+
+let auth: Auth;
+let ws: { reconnecting: boolean };
+
+vi.mock('../../../contexts/AuthContext', () => ({ useAuth: () => auth }));
+vi.mock('../../../contexts/WebSocketContext', () => ({ useWebSocketActions: () => ws }));
+vi.mock('../LoginPage', () => ({ default: () => <p>Sign in page</p> }));
+vi.mock('@/features/home/header/ThemeButton', () => ({ ThemeButton: () => null }));
+
+import { useShellDialogsStore } from '@/stores/shellDialogsStore';
+import ProtectedRoute from '../ProtectedRoute';
+
+let mounts = 0;
+function TheApp() {
+ useEffect(() => {
+ mounts += 1;
+ }, []);
+ return <p>The app</p>;
+}
+
+const view = () => (
+ <ProtectedRoute>
+ <TheApp />
+ </ProtectedRoute>
+);
+
+async function seconds(count: number) {
+ await act(async () => {
+ vi.advanceTimersByTime(count * 1000);
+ });
+ await act(async () => {});
+}
+
+let getContext: ReturnType<typeof vi.spyOn>;
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
+ // No WebGL in jsdom: the orb's slots show the mark.
+ getContext = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
+ mounts = 0;
+ ws = { reconnecting: false };
+ auth = { isAuthenticated: false, isLoading: false, error: null, checkAuth: vi.fn(async () => false) };
+});
+
+afterEach(() => {
+ getContext.mockRestore();
+ vi.useRealTimers();
+});
+
+describe('the sign-in gate', () => {
+ it('shows a loading screen while the session is checked', () => {
+ auth.isLoading = true;
+ render(view());
+ expect(screen.getByText('Loading...')).toBeInTheDocument();
+ });
+
+ it('counts down to each check while the server cannot be reached, and offers help from the third attempt', async () => {
+ auth.error = 'Failed to connect to server';
+ render(view());
+ expect(screen.getByRole('heading', { name: 'Waking up OpenCompany' })).toBeInTheDocument();
+ expect(screen.getByText('Connecting')).toBeInTheDocument();
+ expect(screen.getByText('Trying again in 2s')).toBeInTheDocument();
+ expect(screen.getByText('Attempt 1')).toBeInTheDocument();
+ expect(useShellDialogsStore.getState().connectScreenOpen).toBe(true);
+
+ await seconds(2);
+ expect(auth.checkAuth).toHaveBeenCalledTimes(1);
+ expect(screen.getByText('Attempt 2')).toBeInTheDocument();
+ expect(screen.getByText('Reconnecting')).toBeInTheDocument();
+ expect(screen.queryByText(/Make sure OpenCompany is running/)).not.toBeInTheDocument();
+ await seconds(3);
+ expect(screen.getByText('Still nothing? Make sure OpenCompany is running.')).toBeInTheDocument();
+ });
+
+ it('says Connected for a moment once the server answers, then signs in', async () => {
+ auth.error = 'Failed to connect to server';
+ const { rerender } = render(view());
+ auth = { ...auth, error: null, checkAuth: vi.fn(async () => true) };
+ rerender(view());
+ expect(screen.getByRole('heading', { name: 'Connected' })).toBeInTheDocument();
+ expect(screen.queryByText('Sign in page')).not.toBeInTheDocument();
+ await seconds(1.5);
+ expect(screen.getByText('Sign in page')).toBeInTheDocument();
+ // One screen throughout, so the orb glides from Connecting to sign-in.
+ expect(useShellDialogsStore.getState().connectScreenOpen).toBe(true);
+ });
+
+ it('goes straight into the app after Connected when the session is good', async () => {
+ auth.error = 'Failed to connect to server';
+ const { rerender } = render(view());
+ auth = { ...auth, error: null, isAuthenticated: true };
+ rerender(view());
+ expect(screen.getByRole('heading', { name: 'Connected' })).toBeInTheDocument();
+ await seconds(1.5);
+ expect(screen.getByText('The app')).toBeInTheDocument();
+ expect(useShellDialogsStore.getState().connectScreenOpen).toBe(false);
+ });
+
+ it('shows the app when the session is good, and sign-in when it is not', () => {
+ auth.isAuthenticated = true;
+ const { rerender } = render(view());
+ expect(screen.getByText('The app')).toBeInTheDocument();
+ auth = { ...auth, isAuthenticated: false };
+ rerender(view());
+ expect(screen.getByText('Sign in page')).toBeInTheDocument();
+ });
+
+ it('covers the app while the WebSocket is down, keeping it mounted, and goes once it is back', async () => {
+ auth.isAuthenticated = true;
+ const { rerender } = render(view());
+ ws = { reconnecting: true };
+ rerender(view());
+ expect(screen.getByRole('dialog', { name: 'Reconnecting to OpenCompany' })).toBeInTheDocument();
+ expect(screen.getByText('Reconnecting')).toBeInTheDocument();
+ expect(screen.getByText('The app').closest('[inert]')).not.toBeNull();
+
+ ws = { reconnecting: false };
+ rerender(view());
+ expect(screen.getByRole('heading', { name: 'Connected' })).toBeInTheDocument();
+ await seconds(1.5);
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ expect(screen.getByText('The app').closest('[inert]')).toBeNull();
+ expect(mounts).toBe(1);
+ });
+
+ it('goes to sign-in when the session expired while the server was away', async () => {
+ auth.isAuthenticated = true;
+ const { rerender } = render(view());
+ ws = { reconnecting: true };
+ rerender(view());
+ await seconds(2);
+ expect(auth.checkAuth).toHaveBeenCalledTimes(1);
+ auth = { ...auth, isAuthenticated: false };
+ ws = { reconnecting: false };
+ rerender(view());
+ expect(screen.getByText('Sign in page')).toBeInTheDocument();
+ expect(screen.queryByText('The app')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/auth/__tests__/useRetrySchedule.test.ts b/client/src/components/auth/__tests__/useRetrySchedule.test.ts
new file mode 100644
index 00000000..295c8bdf
--- /dev/null
+++ b/client/src/components/auth/__tests__/useRetrySchedule.test.ts
@@ -0,0 +1,76 @@
+/**
+ * The Connecting screen's schedule: a countdown to each check (2, 3, 5,
+ * then every 8 seconds), Try now checking at once, a failed or rejected
+ * check moving to the next attempt, and an answer stopping it all.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, renderHook } from '@testing-library/react';
+import { useRetrySchedule } from '../useRetrySchedule';
+
+let answers: boolean[];
+const check = vi.fn(async () => answers.shift() ?? false);
+
+/** Let `seconds` pass, then the check they started settle. */
+async function seconds(count: number) {
+ await act(async () => {
+ vi.advanceTimersByTime(count * 1000);
+ });
+ await act(async () => {});
+}
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ answers = [];
+ check.mockClear();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('useRetrySchedule', () => {
+ it('counts down to each check, waiting 2, 3, 5 and then 8 seconds', async () => {
+ const { result } = renderHook(() => useRetrySchedule(check));
+ expect(result.current).toMatchObject({ attempt: 1, wait: 2, checking: false });
+ await seconds(1);
+ expect(result.current.wait).toBe(1);
+ await seconds(1);
+ expect(check).toHaveBeenCalledTimes(1);
+ expect(result.current).toMatchObject({ attempt: 2, wait: 3, checking: false });
+ await seconds(3);
+ expect(result.current).toMatchObject({ attempt: 3, wait: 5 });
+ await seconds(5);
+ expect(result.current).toMatchObject({ attempt: 4, wait: 8 });
+ await seconds(8);
+ await seconds(8);
+ expect(result.current).toMatchObject({ attempt: 6, wait: 8 });
+ expect(check).toHaveBeenCalledTimes(5);
+ });
+
+ it('checks at once on Try now', async () => {
+ const { result } = renderHook(() => useRetrySchedule(check));
+ await act(async () => {
+ result.current.tryNow();
+ });
+ expect(check).toHaveBeenCalledTimes(1);
+ expect(result.current).toMatchObject({ attempt: 2, wait: 3 });
+ });
+
+ it('stops once the server answers', async () => {
+ answers = [false, true];
+ const { result } = renderHook(() => useRetrySchedule(check));
+ await seconds(2);
+ await seconds(3);
+ expect(result.current).toMatchObject({ found: true, checking: false, attempt: 2 });
+ await seconds(30);
+ expect(check).toHaveBeenCalledTimes(2);
+ });
+
+ it('counts a check that fails outright as a failed attempt', async () => {
+ check.mockRejectedValueOnce(new Error('network'));
+ const { result } = renderHook(() => useRetrySchedule(check));
+ await seconds(2);
+ expect(result.current).toMatchObject({ attempt: 2, checking: false, found: false });
+ });
+});
diff --git a/client/src/components/auth/useHold.ts b/client/src/components/auth/useHold.ts
new file mode 100644
index 00000000..85967f07
--- /dev/null
+++ b/client/src/components/auth/useHold.ts
@@ -0,0 +1,22 @@
+/**
+ * `on`, held for `ms` after it turns off. The sign-in gate keeps the
+ * Connecting screen up a moment after the server answers, so "Connected"
+ * is seen before sign-in or the app.
+ */
+
+import { useEffect, useState } from 'react';
+
+export function useHold(on: boolean, ms: number): boolean {
+ const [held, setHeld] = useState(false);
+ const [wasOn, setWasOn] = useState(on);
+ if (wasOn !== on) {
+ setWasOn(on);
+ setHeld(!on);
+ }
+ useEffect(() => {
+ if (!held) return;
+ const timer = window.setTimeout(() => setHeld(false), ms);
+ return () => window.clearTimeout(timer);
+ }, [held, ms]);
+ return on || held;
+}
diff --git a/client/src/components/auth/useRetrySchedule.ts b/client/src/components/auth/useRetrySchedule.ts
new file mode 100644
index 00000000..e029f3a6
--- /dev/null
+++ b/client/src/components/auth/useRetrySchedule.ts
@@ -0,0 +1,78 @@
+/**
+ * When the Connecting screen checks the server again (onboarding handoff
+ * R4): after each wait in CONNECT_RETRY.DELAYS_S in turn, then the last one
+ * every time, counted down a second at a time where the owner can see it.
+ * Try now checks at once. `check` resolves true once the server answered;
+ * the countdown then stops and the screen says it found the server.
+ *
+ * `attempt` counts the checks that failed, the first being the one that
+ * brought the screen up.
+ */
+
+import { useCallback, useEffect, useReducer } from 'react';
+import { CONNECT_RETRY } from '@/lib/connectionConfig';
+
+interface Schedule {
+ attempt: number;
+ /** Seconds until the next check. */
+ wait: number;
+ /** A check is under way. */
+ checking: boolean;
+ /** The server answered. */
+ found: boolean;
+}
+
+type Event = 'second' | 'now' | 'failed' | 'found';
+
+/** The wait after `attempt` failed checks. */
+function delayAfter(attempt: number): number {
+ const delays = CONNECT_RETRY.DELAYS_S;
+ return delays[Math.min(attempt, delays.length) - 1];
+}
+
+const START: Schedule = { attempt: 1, wait: delayAfter(1), checking: false, found: false };
+
+function next(state: Schedule, event: Event): Schedule {
+ if (state.found) return state;
+ switch (event) {
+ case 'second':
+ if (state.checking) return state;
+ return state.wait <= 1 ? { ...state, wait: 0, checking: true } : { ...state, wait: state.wait - 1 };
+ case 'now':
+ return state.checking ? state : { ...state, wait: 0, checking: true };
+ case 'failed':
+ return { attempt: state.attempt + 1, wait: delayAfter(state.attempt + 1), checking: false, found: false };
+ case 'found':
+ return { ...state, checking: false, found: true };
+ }
+}
+
+export function useRetrySchedule(check: () => Promise<boolean>): Schedule & { tryNow: () => void } {
+ const [state, dispatch] = useReducer(next, START);
+ const { checking, found } = state;
+
+ useEffect(() => {
+ if (checking || found) return;
+ const timer = window.setInterval(() => dispatch('second'), 1000);
+ return () => window.clearInterval(timer);
+ }, [checking, found]);
+
+ useEffect(() => {
+ if (!checking) return;
+ let current = true;
+ check().then(
+ (answered) => {
+ if (current) dispatch(answered ? 'found' : 'failed');
+ },
+ () => {
+ if (current) dispatch('failed');
+ },
+ );
+ return () => {
+ current = false;
+ };
+ }, [checking, check]);
+
+ const tryNow = useCallback(() => dispatch('now'), []);
+ return { ...state, tryNow };
+}
diff --git a/client/src/contexts/AuthContext.tsx b/client/src/contexts/AuthContext.tsx
index e2a1d4cd..2f1de290 100644
--- a/client/src/contexts/AuthContext.tsx
+++ b/client/src/contexts/AuthContext.tsx
@@ -2,10 +2,13 @@
/**
* Authentication Context for user session management.
*
- * The auth-status check runs through TanStack Query (`useQuery`) so
- * exponential backoff with full jitter, AbortController-based unmount
- * cleanup, Strict-Mode safety, and 401/403 fast-fail are all delegated
- * to the library — see https://tanstack.com/query/v5/docs/framework/react/guides/query-retries.
+ * The auth-status check runs through TanStack Query (`useQuery`), which
+ * owns AbortController-based unmount cleanup and Strict-Mode safety. It
+ * never retries in secret: when the server can't be reached the sign-in
+ * gate (components/auth/ProtectedRoute) shows the Connecting screen and
+ * checks again through `checkAuth` on a schedule the owner can see
+ * (`CONNECT_RETRY`). `networkMode: 'always'` keeps the browser's idea of
+ * being offline from pausing a check of a server on this computer.
*
* Login / register / logout are `useMutation`s that settle by invalidating
* the `['auth', 'status']` query rather than calling a private setter — the
@@ -33,7 +36,6 @@
import React, { createContext, useContext, useCallback, useMemo } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { API_CONFIG } from '../config/api';
-import { AUTH_RETRY } from '../lib/connectionConfig';
export interface User {
id: number;
@@ -69,7 +71,8 @@ interface AuthContextType {
login: (email: string, password: string) => Promise<boolean>;
register: (email: string, password: string, displayName: string) => Promise<boolean>;
logout: () => Promise<void>;
- checkAuth: () => Promise<void>;
+ /** Check the session again; true when the server answered. */
+ checkAuth: () => Promise<boolean>;
/** Clear stale submit errors (mode toggle, field edit). */
resetAuthErrors: () => void;
}
@@ -89,31 +92,6 @@ const ANONYMOUS_USER: User = {
// Login / register / logout invalidate it via `queryClient.invalidateQueries`.
export const AUTH_STATUS_QUERY_KEY = ['auth', 'status'] as const;
-/**
- * Full-jitter exponential backoff. Constants live in
- * `lib/connectionConfig.ts` (`AUTH_RETRY`) so a future tuning pass is a
- * single-file edit. See that module for the rationale and the reference
- * link to the AWS Architecture Blog.
- */
-const authRetryDelay = (attemptIndex: number): number =>
- Math.random() * Math.min(AUTH_RETRY.CAP_MS, AUTH_RETRY.BASE_MS * 2 ** attemptIndex);
-
-/**
- * Retry on network failures + 5xx; never retry on auth errors (401/403)
- * because those are valid responses meaning "auth disabled / not logged
- * in", not "backend unavailable". Cap at `AUTH_RETRY.MAX_ATTEMPTS`.
- */
-const authShouldRetry = (failureCount: number, error: unknown): boolean => {
- if (failureCount >= AUTH_RETRY.MAX_ATTEMPTS) return false;
- const msg = error instanceof Error ? error.message : String(error);
- if (msg.includes('HTTP 401') || msg.includes('HTTP 403')) return false;
- if (msg.includes(NON_RETRYABLE)) return false;
- return true;
-};
-
-/** Marks an error as pointless to retry (see `authShouldRetry`). */
-const NON_RETRYABLE = 'auth.non-retryable';
-
const isJsonResponse = (response: Response): boolean =>
(response.headers.get('content-type') ?? '').toLowerCase().includes('application/json');
@@ -175,16 +153,12 @@ const fetchAuthStatus = async ({ signal }: { signal: AbortSignal }): Promise<Aut
signal,
});
if (!response.ok) {
- // Wrap status in the error message so `authShouldRetry` can detect
- // 401/403 without parsing the original Response.
throw new Error(`auth.status: HTTP ${response.status}`);
}
- // A 200 carrying HTML means the SPA fallback swallowed /api/auth/status --
- // usually a proxy misroute. Retrying cannot turn HTML into JSON, and the
- // raw SyntaxError message matches none of the fast-fail checks, so it used
- // to burn the entire retry budget on an unrecoverable condition.
+ // A 200 carrying HTML means the SPA fallback swallowed /api/auth/status,
+ // usually a proxy misroute; parsing it would only throw a SyntaxError.
if (!isJsonResponse(response)) {
- throw new Error(`auth.status: ${NON_RETRYABLE} (non-JSON response)`);
+ throw new Error('auth.status: non-JSON response');
}
return response.json() as Promise<AuthStatus>;
};
@@ -199,8 +173,9 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
const authQuery = useQuery({
queryKey: AUTH_STATUS_QUERY_KEY,
queryFn: fetchAuthStatus,
- retry: authShouldRetry,
- retryDelay: authRetryDelay,
+ // The gate checks again where the owner can see it (checkAuth).
+ retry: false,
+ networkMode: 'always',
// Boot-once: never refetch on focus / mount / network reconnect.
// Logout / login explicitly invalidate.
staleTime: Infinity,
@@ -316,9 +291,11 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
// Deliberately NOT `authQuery.refetch()`: `authQuery`'s identity changes on
// essentially every render, which churned `checkAuth`, which broke the
// context `useMemo` below and re-rendered every `useAuth()` consumer on
- // every provider render.
+ // every provider render. A failed check keeps the last answer (a signed-in
+ // owner stays signed in while the server is away) and sets `error`.
const checkAuth = useCallback(async () => {
await queryClient.refetchQueries({ queryKey: AUTH_STATUS_QUERY_KEY });
+ return queryClient.getQueryState(AUTH_STATUS_QUERY_KEY)?.status === 'success';
}, [queryClient]);
const resetAuthErrors = useCallback(() => {
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index cb4d8c83..6bc65d37 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -763,6 +763,8 @@ const WebSocketContext = createContext<WebSocketContextValue | null>(null);
export interface WebSocketActions {
isConnected: boolean;
isReady: boolean;
+ /** The socket was open and closed; it is retrying. */
+ reconnecting: boolean;
sendRequest: WebSocketContextValue['sendRequest'];
addEventListener: WebSocketContextValue['addEventListener'];
startWorkflow: WebSocketContextValue['startWorkflow'];
@@ -3653,6 +3655,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
const actions: WebSocketActions = useMemo(() => ({
isConnected,
isReady,
+ reconnecting,
sendRequest,
addEventListener,
startWorkflow: startWorkflowAsync,
@@ -3664,7 +3667,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
getWorkflowControlStatus: getWorkflowControlStatusAsync,
getWorkflowStatus: getWorkflowStatusAsync,
}), [
- isConnected, isReady, sendRequest, addEventListener,
+ isConnected, isReady, reconnecting, sendRequest, addEventListener,
startWorkflowAsync, startEmployeeAsync, pauseWorkflowAsync, stopChatRunAsync,
resumeWorkflowAsync, resetWorkflowAsync, getWorkflowControlStatusAsync,
getWorkflowStatusAsync,
diff --git a/client/src/contexts/__tests__/AuthContext.test.tsx b/client/src/contexts/__tests__/AuthContext.test.tsx
index d8c39a27..8e272b2e 100644
--- a/client/src/contexts/__tests__/AuthContext.test.tsx
+++ b/client/src/contexts/__tests__/AuthContext.test.tsx
@@ -6,17 +6,16 @@
*
* 1. Anonymous-mode happy path: backend reports `auth_enabled: false`
* → user is auto-set to the anonymous owner without further work.
- * 2. Retry-then-recover: 503 fails N times then 200 succeeds → user
- * is set, no LoginPage flash.
- * 3. 401 fast-fail: backend returns 401 → query reports error
- * immediately, NO retry budget burned (would otherwise wait 10s).
+ * 2. No hidden retries: a 503 is one failed check, reported at once;
+ * `checkAuth` (the sign-in gate's visible retry) recovers once the
+ * server answers, and says whether it did.
+ * 3. A 401 or a non-JSON 200 is one failed check too.
* 4. Logout invalidates the cache: after logout the cached data shows
* `authenticated: false` so the WebSocketContext logout effect
* fires deterministically.
*
- * Backoff is verified at the unit level (the AUTH_RETRY constant is
- * used by `lib/connectionConfig.ts`); the E2E backoff curve is covered
- * by the manual flake-test plan in docs-internal/release_build_pipeline.md.
+ * The gate's schedule (CONNECT_RETRY) is covered by
+ * components/auth/__tests__.
*/
import React from 'react';
@@ -101,26 +100,24 @@ describe('AuthContext (TanStack Query)', () => {
});
});
- it('retries on 503 and surfaces the user on the 200', async () => {
- let attempt = 0;
- vi.spyOn(globalThis, 'fetch').mockImplementation(async () => {
- attempt += 1;
- if (attempt < 3) {
- return new Response('upstream not ready', { status: 503 });
- }
- return new Response(
- JSON.stringify({
- auth_enabled: true,
- auth_mode: 'single',
- authenticated: true,
- user: { id: 1, email: 'a@b', display_name: 'A', is_owner: true },
- can_register: false,
- }),
- { status: 200, headers: { 'Content-Type': 'application/json' } },
- );
- });
+ it('reports a 503 at once, and checkAuth recovers when the server answers', async () => {
+ let up = false;
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
+ up
+ ? new Response(
+ JSON.stringify({
+ auth_enabled: true,
+ auth_mode: 'single',
+ authenticated: true,
+ user: { id: 1, email: 'a@b', display_name: 'A', is_owner: true },
+ can_register: false,
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ )
+ : new Response('upstream not ready', { status: 503 }),
+ );
- // Allow up to 3 retries here so the third attempt resolves the 200.
+ // A client-wide retry budget changes nothing: the query never retries.
const client = makeQueryClient({ retry: 3 });
const { states, Probe } = makeProbe();
render(
@@ -129,22 +126,37 @@ describe('AuthContext (TanStack Query)', () => {
</Wrapper>,
);
+ await waitFor(() => {
+ const last = states[states.length - 1];
+ expect(last.isLoading).toBe(false);
+ expect(last.error).not.toBeNull();
+ });
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+
+ let answered: boolean | undefined;
+ await act(async () => {
+ answered = await states[states.length - 1].checkAuth();
+ });
+ expect(answered).toBe(false);
+
+ up = true;
+ await act(async () => {
+ answered = await states[states.length - 1].checkAuth();
+ });
+ expect(answered).toBe(true);
await waitFor(() => {
const last = states[states.length - 1];
expect(last.isAuthenticated).toBe(true);
expect(last.user?.email).toBe('a@b');
+ expect(last.error).toBeNull();
});
- expect(attempt).toBeGreaterThanOrEqual(3);
});
- it('does not retry a 401 — surfaces "not authenticated" immediately', async () => {
+ it('reports a 401 as one failed check', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
new Response(JSON.stringify({ detail: 'unauthorized' }), { status: 401 }),
);
- // Even with a generous retry budget the AuthContext's `retry`
- // predicate refuses 401/403 — `fetchSpy` should be called exactly
- // ONCE.
const client = makeQueryClient({ retry: 5 });
const { states, Probe } = makeProbe();
render(
@@ -424,10 +436,8 @@ describe('AuthContext login/register', () => {
await waitFor(() => expect(latest().submitError).toBeNull());
});
- it('does not retry a non-JSON 200 from /status', async () => {
+ it('reports a non-JSON 200 from /status as one failed check', async () => {
// A 200 carrying HTML means the SPA fallback swallowed the API route.
- // Retrying cannot turn HTML into JSON, and the raw SyntaxError matched
- // none of the fast-fail checks, so this burned the whole retry budget.
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
new Response('<!doctype html><html></html>', {
status: 200,
diff --git a/client/src/contexts/__tests__/webSocketActions.test.tsx b/client/src/contexts/__tests__/webSocketActions.test.tsx
index 6338574c..40b642f7 100644
--- a/client/src/contexts/__tests__/webSocketActions.test.tsx
+++ b/client/src/contexts/__tests__/webSocketActions.test.tsx
@@ -161,7 +161,7 @@ describe('WebSocket actions for Normal mode', () => {
unmount();
});
- it('sends straight away again once the socket has reconnected', async () => {
+ it('says while it reconnects, and sends straight away again once the socket is back', async () => {
let actions!: WebSocketActions;
function Probe() {
actions = useWebSocketActions();
@@ -170,12 +170,16 @@ describe('WebSocket actions for Normal mode', () => {
const { unmount } = mount(Probe);
const socket = sockets[0];
await open(socket);
+ expect(actions.reconnecting).toBe(false);
act(() => {
socket.readyState = 3;
socket.onclose?.({ code: 1006, reason: 'server restarted' });
});
+ // The sign-in gate covers the app while this is true.
+ expect(actions.reconnecting).toBe(true);
// PartySocket reopens the same instance.
await open(socket);
+ expect(actions.reconnecting).toBe(false);
const request = actions.sendRequest('list_employees', {});
expect(frames(socket).map((frame) => frame.type)).toContain('list_employees');
diff --git a/client/src/lib/__tests__/connectionConfig.test.ts b/client/src/lib/__tests__/connectionConfig.test.ts
index b9200c35..e9e121bc 100644
--- a/client/src/lib/__tests__/connectionConfig.test.ts
+++ b/client/src/lib/__tests__/connectionConfig.test.ts
@@ -1,60 +1,35 @@
/**
* Lock-in tests for `lib/connectionConfig.ts`.
*
- * The tuning constants here drive AuthContext's TanStack Query retry
- * policy and PartySocket's reconnect envelope. Drift in either —
- * accidentally raising AUTH_RETRY.CAP_MS to 30s, or flipping
- * WS_CLOSE.NORMAL_CLOSURE off RFC 6455's 1000 — would silently
- * regress perceived launch time or break the "intentional close"
+ * The tuning constants here drive the sign-in gate's visible retries and
+ * PartySocket's reconnect envelope. Drift in either (a first check minutes
+ * away, or WS_CLOSE.NORMAL_CLOSURE off RFC 6455's 1000) would silently
+ * regress how fast the app comes back or break the "intentional close"
* contract.
*/
import { describe, it, expect } from 'vitest';
-import { AUTH_RETRY, WS_CLOSE, WS_RECONNECT } from '../connectionConfig';
+import { CONNECT_RETRY, WS_CLOSE, WS_RECONNECT } from '../connectionConfig';
-describe('AUTH_RETRY', () => {
- it('keeps base under 100 ms for sub-second first retries', () => {
- // The previous hand-rolled chain started at 1000 ms, which cost
- // ~3 s of perceived launch time when the backend was ready 100 ms
- // after the first failure. Anything above 100 ms here would
- // re-introduce that stall.
- expect(AUTH_RETRY.BASE_MS).toBeLessThan(100);
+describe('CONNECT_RETRY', () => {
+ it('checks again after 2, 3, 5 and then every 8 seconds', () => {
+ expect(CONNECT_RETRY.DELAYS_S).toEqual([2, 3, 5, 8, 8]);
});
- it('caps individual retries below 5 s so a slow backend still recovers in <30 s wall', () => {
- expect(AUTH_RETRY.CAP_MS).toBeGreaterThan(0);
- expect(AUTH_RETRY.CAP_MS).toBeLessThan(5_000);
+ it('never waits less than before', () => {
+ const delays = CONNECT_RETRY.DELAYS_S;
+ for (let i = 1; i < delays.length; i += 1) expect(delays[i]).toBeGreaterThanOrEqual(delays[i - 1]);
});
- it('allows enough attempts to span a multi-second backend cold start', () => {
- // With BASE_MS=50, CAP_MS=4000: cumulative upper bound
- // sum_{n=0..N-1} min(CAP_MS, BASE_MS * 2^n)
- // For N=7 → ~10 s, which covers the typical 4 s backend window.
- expect(AUTH_RETRY.MAX_ATTEMPTS).toBeGreaterThanOrEqual(5);
- expect(AUTH_RETRY.MAX_ATTEMPTS).toBeLessThanOrEqual(10);
- });
-
- it('full-jitter formula stays within the documented envelope for every attempt', () => {
- // The actual formula:
- // sleep = random(0, min(CAP_MS, BASE_MS * 2 ** attempt))
- // Sample 1000 draws per attempt and confirm every draw stays under
- // the cap. (Random.random() is bounded [0, 1) so the upper bound is
- // strict.)
- for (let attempt = 0; attempt < AUTH_RETRY.MAX_ATTEMPTS; attempt += 1) {
- const upperBound = Math.min(AUTH_RETRY.CAP_MS, AUTH_RETRY.BASE_MS * 2 ** attempt);
- for (let i = 0; i < 100; i += 1) {
- const draw = Math.random() * upperBound;
- expect(draw).toBeGreaterThanOrEqual(0);
- expect(draw).toBeLessThanOrEqual(AUTH_RETRY.CAP_MS);
- }
- }
+ it('holds Connected long enough to read, and offers help from the third attempt', () => {
+ expect(CONNECT_RETRY.CONNECTED_HOLD_MS).toBe(1_500);
+ expect(CONNECT_RETRY.HELP_FROM_ATTEMPT).toBe(3);
});
});
describe('WS_RECONNECT', () => {
it('first reconnect attempt is sub-second', () => {
- // Matches the AuthContext retry shape so first reconnect after a
- // transient drop is fast.
+ // A transient drop reconnects before the overlay has much to say.
expect(WS_RECONNECT.MIN_DELAY_MS).toBeGreaterThan(0);
expect(WS_RECONNECT.MIN_DELAY_MS).toBeLessThan(1_000);
});
diff --git a/client/src/lib/connectionConfig.ts b/client/src/lib/connectionConfig.ts
index 6af585f7..6b79ebdb 100644
--- a/client/src/lib/connectionConfig.ts
+++ b/client/src/lib/connectionConfig.ts
@@ -1,12 +1,8 @@
/**
- * Centralised tuning constants for the auth + WebSocket connection layer.
- *
- * The hand-rolled retry chain in `AuthContext` and the flat 3-second
- * reconnect timer in `WebSocketContext` were retired in favour of
- * library-backed retry policies (TanStack Query for auth, PartySocket
- * for the WS). The numeric envelope of those policies lives here so a
- * future tuning pass — tighter backoff, longer cap, smaller queue — is
- * a single-file edit and tests can reference the same values.
+ * Centralised tuning constants for the connection layer: when the sign-in
+ * gate checks the server again, PartySocket's reconnect envelope, the app
+ * heartbeat and the close codes. A tuning pass is a single-file edit, and
+ * tests reference the same values.
*
* Pattern mirrors `client/src/lib/queryConfig.ts`'s `STALE_TIME` /
* `GC_TIME` buckets: named, frozen, JSDoc-explained.
@@ -17,46 +13,28 @@
*/
/**
- * Auth-bootstrap retry tuning, consumed by `AuthContext`'s
- * `useQuery({ retry, retryDelay })` config.
- *
- * Full-jitter exponential backoff per the AWS Architecture Blog —
- * https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/.
- *
- * Formula:
- *
- * sleep = random_between(0, min(CAP_MS, BASE_MS * 2^attempt))
- *
- * Sample sequence (BASE_MS=50, CAP_MS=4000):
- *
- * attempt 0 → up to 50ms
- * attempt 1 → up to 100ms
- * attempt 2 → up to 200ms
- * attempt 3 → up to 400ms
- * attempt 4 → up to 800ms
- * attempt 5 → up to 1600ms
- * attempt 6 → up to 3200ms
- * attempt 7 → up to 4000ms (capped)
- *
- * Total upper-bound wall time ≈ 10 s across 7 retries — covers the
- * typical ~4 s backend cold-start window in 4-5 attempts. The previous
- * `1000ms · Math.pow(2, n)` chain needed 31 s in the worst case.
+ * The Connecting screen (components/auth/ConnectingPanel, onboarding
+ * handoff R4). The auth check itself never retries in secret; while the
+ * server can't be reached, the gate checks it again after each of these
+ * waits in turn, then after the last one every time, counting down where
+ * the owner can see it. "Connected" shows for CONNECTED_HOLD_MS before
+ * sign-in or the app, and from attempt HELP_FROM_ATTEMPT a line says to
+ * make sure OpenCompany is running.
*/
-export const AUTH_RETRY = {
- /** Base for the exponential factor (ms). */
- BASE_MS: 50,
- /** Cap on a single retry's delay (ms). */
- CAP_MS: 4_000,
- /** Stop retrying after this many failed attempts. */
- MAX_ATTEMPTS: 7,
+export const CONNECT_RETRY = {
+ /** Seconds before each check. */
+ DELAYS_S: [2, 3, 5, 8, 8],
+ CONNECTED_HOLD_MS: 1_500,
+ HELP_FROM_ATTEMPT: 3,
} as const;
/**
* WebSocket reconnect envelope, consumed by `WebSocketContext`'s
* `new ReconnectingWebSocket(url, [], {...})` constructor.
*
- * `partysocket/ws` interleaves jitter automatically; these values
- * define the envelope it stays inside.
+ * PartySocket waits MIN_DELAY_MS · GROW_FACTOR^(n-1) before attempt n,
+ * capped at MAX_DELAY_MS. There is no jitter: PartySocket randomises only
+ * its own default minimum, which MIN_DELAY_MS replaces.
*
* Sample reconnect sequence (MIN_DELAY_MS=250, GROW_FACTOR=1.3,
* MAX_DELAY_MS=8000):
diff --git a/client/src/stores/shellDialogsStore.ts b/client/src/stores/shellDialogsStore.ts
index d5b1494d..275c1c8d 100644
--- a/client/src/stores/shellDialogsStore.ts
+++ b/client/src/stores/shellDialogsStore.ts
@@ -21,6 +21,10 @@ interface ShellDialogsState {
credentialsOptions: CredentialsOptions & { intent: CredentialsIntent };
/** Repeated opens are navigation requests, even when their target matches. */
credentialsRequestId: number;
+ /** The sign-in gate's Connecting or sign-in screen is showing
+ * (components/auth/ConnectScreen): the theme shows as its base. */
+ connectScreenOpen: boolean;
+ setConnectScreenOpen: (open: boolean) => void;
openSettings: () => void;
closeSettings: () => void;
openCredentials: (options?: CredentialsOptions) => void;
@@ -32,6 +36,8 @@ export const useShellDialogsStore = create<ShellDialogsState>((set) => ({
credentialsOpen: false,
credentialsOptions: { intent: 'manage' },
credentialsRequestId: 0,
+ connectScreenOpen: false,
+ setConnectScreenOpen: (open) => set({ connectScreenOpen: open }),
openSettings: () => set({ settingsOpen: true }),
closeSettings: () => set({ settingsOpen: false }),
openCredentials: (options) => set((state) => ({
diff --git a/docs-internal/authentication.md b/docs-internal/authentication.md
index ab57aa2c..a63be3dc 100644
--- a/docs-internal/authentication.md
+++ b/docs-internal/authentication.md
@@ -12,7 +12,8 @@ n8n-inspired authentication system with JWT tokens stored in HttpOnly cookies. A
When `VITE_AUTH_ENABLED=false`:
- Frontend skips login page entirely
- User is set to anonymous with owner privileges
-- No backend auth API calls are made
+- The client still asks `GET /api/auth/status` once at boot; it answers
+ `auth_enabled: false`, and that is how the client knows to skip login
- Useful for local development and testing
## Deployment Modes (when auth enabled)
@@ -147,20 +148,31 @@ interface AuthContextValue {
login: (email: string, password: string) => Promise<boolean>;
register: (email: string, password: string, displayName: string) => Promise<boolean>;
logout: () => Promise<void>;
- checkAuth: () => Promise<void>;
+ /** Check the session again; true when the server answered. */
+ checkAuth: () => Promise<boolean>;
}
```
### Protected Route (`client/src/components/auth/ProtectedRoute.tsx`)
-Wraps protected content, shows LoginPage if not authenticated:
-```typescript
-const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
- const { isAuthenticated, isLoading } = useAuth();
- if (isLoading) return <LoadingSpinner />;
- if (!isAuthenticated) return <LoginPage />;
- return <>{children}</>;
-};
-```
+The sign-in gate (onboarding handoff R4), in front of the whole app:
+
+| State | Shows |
+|-------|-------|
+| the session is being checked (`isLoading`) | a loading screen |
+| the server can't be reached (`error`, not signed in) | Connecting (`ConnectingPanel`): a countdown to each check, Try now, "Attempt n", and from the third attempt "Still nothing? Make sure OpenCompany is running." |
+| the server answered | "Connected", held `CONNECT_RETRY.CONNECTED_HOLD_MS` (1.5 s, `useHold`) |
+| then | sign-in, or the app when the session is good or login is off |
+| signed in, the WebSocket down (`reconnecting` from `useWebSocketActions`) | Connecting over the app (`role="dialog"`, `z-60`); the app stays mounted, `inert` |
+
+Connecting and sign-in render inside one `ConnectScreen` (the whole window,
+the orb filling it, the logo and the theme button on top), so the orb
+glides from one's slot to the other's. The schedule is `useRetrySchedule`:
+`CONNECT_RETRY.DELAYS_S` (2, 3, 5, 8, 8 s), each check being `checkAuth`;
+over the app the checks are HTTP session checks too, so a session that
+expired while the server was away goes to sign-in, and the overlay goes
+once the WebSocket is back. While a `ConnectScreen` shows, the theme is the
+base of the chosen family (`shellDialogsStore.connectScreenOpen`, read by
+`app/ShellThemeProvider.tsx`).
### Login Page (`client/src/components/auth/LoginPage.tsx`)
- shadcn `Form` composition (react-hook-form + zod), matching `EmailPanel` —
@@ -284,34 +296,34 @@ is not `local`. Only a `.env` that `company build` creates itself gets fresh
install nothing warns. See
[Credentials Encryption → Placeholder secrets](./credentials_encryption.md#placeholder-secrets).
-## Race Condition Handling (TanStack Query bootstrap)
+## Race Condition Handling (the bootstrap check)
The frontend starts before the backend is ready during cold launch, so the
-auth-status check must tolerate transient failures.
-
-The `AuthContext` bootstraps the auth-status check through TanStack Query
-(`useQuery({ queryKey: AUTH_STATUS_QUERY_KEY, queryFn: fetchAuthStatus, retry, retryDelay, signal })`),
-which replaced the previous recursive `setTimeout` retry chain. Behaviour:
-
-- **Full-jitter exponential backoff** per the AWS Architecture Blog formula:
- `random(0, min(CAP_MS, BASE_MS * 2^attempt))`. Constants live in
- [`client/src/lib/connectionConfig.ts`](../client/src/lib/connectionConfig.ts)
- under `AUTH_RETRY`: `BASE_MS = 50`, `CAP_MS = 4000`, `MAX_ATTEMPTS = 7`.
- Cumulative budget is ~10 s (vs. the old ~31 s); sub-second granularity early
- covers the typical 4 s backend cold-start window in 4–5 attempts.
-- **401/403 short-circuit the retry chain** — those are valid responses meaning
- "auth disabled / not logged in", not "backend unavailable", so no retry
- budget is burned (`authShouldRetry` returns `false` when the wrapped error
- message contains `HTTP 401` / `HTTP 403`).
+auth-status check must tolerate the server not being there yet.
+
+The `AuthContext` runs the check through TanStack Query
+(`useQuery({ queryKey: AUTH_STATUS_QUERY_KEY, queryFn: fetchAuthStatus, retry: false, networkMode: 'always' })`):
+
+- **No hidden retries.** A failed check (no answer, a 5xx, a 401/403 or a
+ non-JSON 200) sets `error` at once, and the sign-in gate shows Connecting,
+ which checks again through `checkAuth` on a schedule the owner can see
+ (`CONNECT_RETRY` in
+ [`client/src/lib/connectionConfig.ts`](../client/src/lib/connectionConfig.ts)).
+ `checkAuth` refetches and says whether the server answered; a failed check
+ keeps the last answer, so a signed-in owner stays signed in while the
+ server is away. Nothing ever writes a failure into the status cache.
+- **`networkMode: 'always'`**: the browser's idea of being offline never
+ pauses a check of a server on this computer.
- **AbortController `signal`** is plumbed through `queryFn` so unmount + React
Strict Mode cleanup cancel in-flight requests automatically.
- `login` / `register` / `logout` invalidate the cache via
`queryClient.invalidateQueries({ queryKey: AUTH_STATUS_QUERY_KEY })`
(`AUTH_STATUS_QUERY_KEY = ['auth', 'status']`).
-> Historical note: the original implementation used 5 fixed retries with
-> exponential backoff (1 s, 2 s, 4 s, 8 s, 16 s) and a recursive `setTimeout`
-> chain, surfacing "Failed to connect to server" only after all retries were
-> exhausted. This was superseded by the TanStack Query bootstrap above.
+> Historical note: the check used to retry on its own, first through a
+> recursive `setTimeout` chain (1, 2, 4, 8, 16 s), then through TanStack
+> Query's full-jitter backoff (`AUTH_RETRY`, about 10 s in all), after which
+> the login page showed "Failed to connect to server" and nothing checked
+> again. The visible Connecting screen replaced both.
## Cookie-Based Auth for API Calls
All API calls must include `credentials: 'include'` for the HttpOnly cookie:
@@ -366,11 +378,13 @@ useEffect(() => {
## Key Files
| File | Description |
|------|-------------|
-| `client/src/config/api.ts` | API config with AUTH_ENABLED toggle |
-| `client/src/contexts/AuthContext.tsx` | React auth state with TanStack Query bootstrap + retry logic |
-| `client/src/lib/connectionConfig.ts` | `AUTH_RETRY` backoff constants (`BASE_MS` / `CAP_MS` / `MAX_ATTEMPTS`) |
+| `client/src/config/api.ts` | The backend's base URL (same origin unless `VITE_PYTHON_SERVICE_URL`) |
+| `client/src/contexts/AuthContext.tsx` | React auth state: the TanStack Query bootstrap check, `checkAuth` |
+| `client/src/lib/connectionConfig.ts` | `CONNECT_RETRY` (the Connecting screen's schedule) and the WebSocket envelope |
| `client/src/components/auth/LoginPage.tsx` | Login UI |
-| `client/src/components/auth/ProtectedRoute.tsx` | Route guard |
+| `client/src/components/auth/ProtectedRoute.tsx` | The sign-in gate (states above) |
+| `client/src/components/auth/ConnectScreen.tsx`, `ConnectingPanel.tsx` | The screen around Connecting and sign-in, and Connecting itself |
+| `client/src/components/auth/useRetrySchedule.ts`, `useHold.ts` | The countdown to each check; "Connected" held a moment |
| `server/models/auth.py` | User SQLModel with bcrypt |
| `server/services/user_auth.py` | `UserAuthService`: register / login / JWT mint + verify / `get_current_user`. Holds the encryption service and credentials database but uses neither; its `is_encryption_initialized()` has no callers (see the note under Auth Service) |
| `server/routers/auth.py` | REST endpoints |
diff --git a/docs-internal/performance.md b/docs-internal/performance.md
index 5e0878c7..e005c32c 100644
--- a/docs-internal/performance.md
+++ b/docs-internal/performance.md
@@ -198,7 +198,7 @@ T+51 — example workflows imported (still inline — see follow-ups)
is idle in this window; the cost lives on the frontend. Likely
contributors:
-1. **TanStack Query auth-bootstrap retry budget** ([client/src/contexts/AuthContext.tsx](../client/src/contexts/AuthContext.tsx) + [client/src/lib/connectionConfig.ts](../client/src/lib/connectionConfig.ts)). The `AUTH_RETRY` envelope (BASE 50 ms, CAP 4000 ms, MAX_ATTEMPTS 7) covers the typical 4 s backend cold-start window in 4-5 attempts. If the backend finishes mid-retry-cycle, the next jittered draw can land 1-3 s after readiness.
+1. **The sign-in gate's visible retry schedule** ([client/src/components/auth/ProtectedRoute.tsx](../client/src/components/auth/ProtectedRoute.tsx) + [client/src/lib/connectionConfig.ts](../client/src/lib/connectionConfig.ts)). The auth check no longer retries on its own: when the backend is not up at the first check, the Connecting screen checks again after 2, 3, 5 and then every 8 s (`CONNECT_RETRY`) and holds "Connected" 1.5 s before sign-in or the app. A backend that becomes ready just after a check waits for the next one. (The measurement above predates this; it used a 50 ms full-jitter backoff.) The desktop shell loads the SPA only after `/health/ready`, so it never shows Connecting at launch.
2. **React Strict Mode dual-mount** in dev. The 100 ms `connectTimeout` guard in `WebSocketProvider`'s auth-gated connect effect ([WebSocketContext.tsx](../client/src/contexts/WebSocketContext.tsx)) absorbs the bulk; remaining cost is React reconciliation + babel-plugin-react-compiler overhead on first render.
3. **PartySocket upgrade handshake**. Sub-100 ms in normal cases; would only matter on slow networks.
@@ -210,18 +210,19 @@ Single source of truth: [client/src/lib/connectionConfig.ts](../client/src/lib/c
| Constant | Value | Notes |
|---|---|---|
-| `AUTH_RETRY.BASE_MS` | 50 ms | Full-jitter base; first failure waits up to 50 ms vs. 1 s previously |
-| `AUTH_RETRY.CAP_MS` | 4000 ms | Cap on per-retry delay |
-| `AUTH_RETRY.MAX_ATTEMPTS` | 7 | Cumulative upper bound ~10 s (vs. 31 s on the old recursive `setTimeout`) |
+| `CONNECT_RETRY.DELAYS_S` | 2, 3, 5, 8, 8 s | The Connecting screen's waits before each check, the last repeated |
+| `CONNECT_RETRY.CONNECTED_HOLD_MS` | 1500 ms | "Connected" shows this long before sign-in or the app |
+| `CONNECT_RETRY.HELP_FROM_ATTEMPT` | 3 | "Still nothing? Make sure OpenCompany is running." from here |
| `WS_RECONNECT.MIN_DELAY_MS` | 250 ms | First reconnect attempt |
| `WS_RECONNECT.MAX_DELAY_MS` | 8000 ms | Cap on any single reconnect delay |
| `WS_RECONNECT.GROW_FACTOR` | 1.3 | Multiplier per attempt |
| `WS_RECONNECT.MAX_ENQUEUED_MESSAGES` | 200 | PartySocket send-while-disconnected buffer |
| `WS_CLOSE.NORMAL_CLOSURE` | 1000 | RFC 6455 §7.4.1; PartySocket skips reconnect for this code |
-Backoff formula (AWS Architecture Blog "full jitter" pattern):
+PartySocket's reconnect delay (no jitter: it randomises only its own default
+minimum, which `MIN_DELAY_MS` replaces):
- sleep = random(0, min(CAP_MS, BASE_MS * 2^attempt))
+ delay(n) = min(MAX_DELAY_MS, MIN_DELAY_MS * GROW_FACTOR^(n-1))
Lock-in tests: [client/src/lib/__tests__/connectionConfig.test.ts](../client/src/lib/__tests__/connectionConfig.test.ts).
@@ -309,8 +310,8 @@ cd client
bun run vitest run src/lib/__tests__/connectionConfig.test.ts
```
-10 tests, locks RFC 6455 close code, AUTH_RETRY envelope, full-jitter
-formula bound check across 100 × MAX_ATTEMPTS draws.
+Locks the RFC 6455 close code, the Connecting schedule (`CONNECT_RETRY`) and
+the reconnect envelope.
## Anti-patterns we've removed (don't reintroduce)
@@ -320,7 +321,7 @@ These were observed and fixed; the lessons are durable.
- **Eager SDK import at LLM provider registration, just to reference typed exception classes.** The `services/llm/providers/*` registration blocks did `import anthropic` / `import openai` / `from google.genai import errors` at module bottom solely to populate `ProviderSpec.sdk_exception_types` — re-creating the anti-pattern above through the raw SDKs (~7.6 s warm / ~45 s cold for the AIService import vs the 703 ms baseline; google.genai alone was ~4 s warm / ~15 s cold). Fixed with lazy `"module:ClassName"` refs (`ProviderSpec.sdk_exception_refs`) resolved via `pkgutil.resolve_name` at except/read time — by then the provider factory has already imported the SDK, so resolution is a `sys.modules` cache hit. Locked by [server/tests/llm/test_lazy_sdk_imports.py](../server/tests/llm/test_lazy_sdk_imports.py) (subprocess purity probe). When adding a provider: pass a string ref, never import the SDK at module level. **The guard is per-provider-layer, and every new one needs its own copy** — the probe runs in a clean interpreter because the pytest process already has SDKs loaded by other tests, so an in-process assertion would pass vacuously. `nodes/speech/` ships its equivalent in [tests/nodes/test_speech.py](../server/tests/nodes/test_speech.py) (`TestLazySdkImports`), asserting that importing the whole speech plugin leaves `openai` / `anthropic` / `google.genai` out of `sys.modules`.
- **Unconditional `client/node_modules/.vite` wipe on every `company dev`.** Forced a full esbuild dependency re-optimization (1-2 minutes on Windows) on every first page load. Vite self-invalidates the dep cache via lockfile/config/NODE_ENV hashes in `.vite/deps/_metadata.json`; the wipe was pure waste on a stable lockfile. Replaced with `company dev --force` → `VITE_FORCE=1` → `optimizeDeps.force` (Vite's own re-bundle mechanism), plus `optimizeDeps.include` for the heavy lazily-reached deps so late discovery can't trigger the mid-session re-optimization behind the "Outdated Optimize Dep" 504 (vitejs/vite#14284).
- **Synchronous temporalio `Worker()` construction on the event loop.** The constructor derives a default build id by MD5-hashing the bytecode of every module in `sys.modules` (disk reads included) — ~3.1 s at our module count, freezing the loop and inflating concurrent boot work (`broadcaster.refresh_whatsapp` measured 4.2 s vs its ~0.4 s siblings). The value is memoized SDK-globally, so `TemporalWorkerManager.start()` pre-warms it once via `asyncio.to_thread(load_default_build_id)` before constructing the manager worker; all pool workers then construct cheaply. Any new long synchronous call in an async startup path should get the same `to_thread` treatment.
-- **Recursive `setTimeout` retry chain in `useEffect` without `AbortController`.** Survived unmount, leaked timers, called `setState` on stale closures. The React docs explicitly flag this in [https://react.dev/reference/react/useEffect](https://react.dev/reference/react/useEffect). Replaced with TanStack Query's `signal`-aware `queryFn`.
+- **Recursive `setTimeout` retry chain in `useEffect` without `AbortController`.** Survived unmount, leaked timers, called `setState` on stale closures. The React docs explicitly flag this in [https://react.dev/reference/react/useEffect](https://react.dev/reference/react/useEffect). Replaced with TanStack Query's `signal`-aware `queryFn`; the retries themselves are now the sign-in gate's visible schedule (`components/auth/useRetrySchedule.ts`).
- **Flat `setTimeout(connect, 3000)` reconnect loop.** No exponential backoff, no jitter, no `code === 1000` honouring, no message replay. Replaced with PartySocket — see [client/src/contexts/WebSocketContext.tsx](../client/src/contexts/WebSocketContext.tsx).
- **`if (event.code !== 1000)` magic numbers** scattered through the WS lifecycle. Replaced with `WS_CLOSE.NORMAL_CLOSURE` from [connectionConfig.ts](../client/src/lib/connectionConfig.ts) per RFC 6455 §7.4.1.
- **Inline `chunkSizeWarningLimit: 1500`** silently masking bundle bloat. Lowered to 850 KB so future regressions surface at `vite build` time.
@@ -344,7 +345,6 @@ Tracked but explicitly **not** in any active plan.
## References
-- AWS Architecture Blog, ["Exponential Backoff and Jitter"](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/) — full-jitter formula used by `AUTH_RETRY`.
- RFC 6455 §7.4.1 — WebSocket close codes ([https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1)).
- TanStack Query v5 retry guide — [https://tanstack.com/query/v5/docs/framework/react/guides/query-retries](https://tanstack.com/query/v5/docs/framework/react/guides/query-retries).
- PartySocket API — [https://docs.partykit.io/reference/partysocket-api/](https://docs.partykit.io/reference/partysocket-api/).