Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions catalyst-frontend/e2e/functional.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,44 @@ async function login(page: Page) {
await loginUser(page, testUser);
}

/**
* Record every in-app path this document navigates through. React Router
* redirects via history.pushState/replaceState, which fire no Playwright
* navigation event, so a `framenavigated` listener would miss a client-side
* bounce to /login. Install before the reload under test.
*/
async function recordSpaPaths(page: Page) {
await page.addInitScript(() => {
const store = window as unknown as { __spaPaths: string[] };
store.__spaPaths = [window.location.pathname];
const historyMethods = history as unknown as Record<
string,
(state: unknown, title: string, url?: string | URL | null) => void
>;
const record = (url?: string | URL | null) => {
if (url === undefined || url === null) return;
try {
store.__spaPaths.push(new URL(String(url), window.location.origin).pathname);
} catch {
// Not a resolvable path — nothing to record.
}
};
for (const method of ['pushState', 'replaceState']) {
const original = historyMethods[method].bind(history);
historyMethods[method] = (state, title, url) => {
record(url);
original(state, title, url);
};
}
});
}

async function spaPaths(page: Page): Promise<string[]> {
return page.evaluate(
() => (window as unknown as { __spaPaths?: string[] }).__spaPaths ?? [],
);
}

// ─── Test suites ─────────────────────────────────────────────────────────────

// 1. Authentication Flows
Expand Down Expand Up @@ -226,6 +264,39 @@ test.describe('Authentication Flows', () => {
.toBeVisible({ timeout: 10_000 });
});

test('Reloading an authenticated page never paints the login page', async ({ page }) => {
test.setTimeout(60_000);
await login(page);
await recordSpaPaths(page);

// EventSource streams keep the network busy, so networkidle can never settle;
// the sidebar locator below is the real "panel rendered" signal.
await page.goto('/servers', { waitUntil: 'domcontentloaded' }).catch(() => {});
await page.locator('aside nav').first().waitFor({ state: 'visible', timeout: 15_000 }).catch(() => {});

expect.soft(await spaPaths(page)).not.toContain('/login');
expect.soft(new URL(page.url()).pathname).toBe('/servers');
});

test('Reloading with a slow session probe never paints the login page', async ({ page }) => {
test.setTimeout(60_000);
await login(page);
await recordSpaPaths(page);

// Slow backend: this is the window in which the old bootstrap declared "no
// session" before /api/auth/me had answered, bouncing users to /login.
await page.route('**/api/auth/me*', async (route) => {
await new Promise((resolve) => setTimeout(resolve, 2_000));
await route.continue();
});

await page.goto('/servers', { waitUntil: 'domcontentloaded' }).catch(() => {});
await page.locator('aside nav').first().waitFor({ state: 'visible', timeout: 15_000 }).catch(() => {});

expect.soft(await spaPaths(page)).not.toContain('/login');
expect.soft(new URL(page.url()).pathname).toBe('/servers');
});

test('User can logout and is redirected', async ({ page }) => {
test.setTimeout(30_000);
await login(page);
Expand Down
92 changes: 85 additions & 7 deletions catalyst-frontend/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
import { Navigate, Route, Routes, useLocation } from 'react-router-dom';
import { Link, Navigate, Route, Routes, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import SetupPage from './pages/setup/SetupPage';
import { useSetupStatus } from './hooks/useSetupStatus';
Expand Down Expand Up @@ -71,6 +71,37 @@ function PageFallback() {
);
}

/**
* Recovery screen for a boot session probe that never settled. Shown for every
* path except the auth routes, so a signed-out user still has a way in.
*/
function SessionCheckFailedPage() {
const { t } = useTranslation(['common', 'auth']);
const isRefreshing = useAuthStore((s) => s.isRefreshing);
const retrySession = useAuthStore((s) => s.init);
return (
<div className="flex h-screen items-center justify-center bg-background px-6">
<div className="max-w-md space-y-3 text-center">
<p className="text-sm text-muted-foreground">{t('sessionCheck.failed')}</p>
<button
type="button"
onClick={() => { void retrySession().catch(() => {}); }}
disabled={isRefreshing}
className="mx-auto inline-flex h-8 items-center rounded-sm bg-primary px-3 text-mini font-semibold text-primary-foreground transition-colors hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-60"
>
{isRefreshing ? t('actions.loading') : t('actions.retry')}
</button>
<Link
to="/login"
className="block text-mini text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
>
{t('auth:login.submit')}
</Link>
</div>
</div>
);
}

/** Smooth page transition wrapper */
function PageTransition({ children }: { children: React.ReactNode }) {
const reducedMotion = useReducedMotion();
Expand Down Expand Up @@ -101,6 +132,7 @@ function App() {
const user = useAuthStore((s) => s.user);
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
const isReady = useAuthStore((s) => s.isReady);
const sessionCheckFailed = useAuthStore((s) => s.sessionCheckFailed);
const {
setupRequired,
isLoading: isSetupLoading,
Expand All @@ -109,26 +141,45 @@ function App() {
recheck: recheckSetup,
} = useSetupStatus();

// Backstop so a stalled backend can never leave the panel on Loading...
// Auth and setup hooks have their own shorter timeouts; this covers any
// other hang in the boot path.
// Backstop so a stalled boot step can never leave the panel on Loading...
// The auth hook bounds its own probe (and shows a retry screen) and the setup
// hook has its own timeout, so this only covers anything else that hangs —
// and it never overrides an in-flight session probe, because flipping the
// gate early is the login-page flash.
const [bootTimedOut, setBootTimedOut] = useState(false);
// Mirrors boot readiness so the backstop only reports when boot is
// genuinely still stuck — previously the timer always fired 20s after
// mount and reported on every session, even fast boots.
const bootReadyRef = useRef(false);
const bootReportedRef = useRef(false);
bootReadyRef.current = isReady && !isSetupLoading;
useEffect(() => {
const timer = setTimeout(() => {
let timer: ReturnType<typeof setTimeout> | undefined;
const check = (delay: number) => {
timer = setTimeout(() => {
if (bootReadyRef.current) return;
// A session probe still in flight is the one boot step this must not
// override: flipping the gate early is exactly the login-page flash.
// useAuthInit bounds that probe on its own (retry, then its retry
// screen), so keep watching instead of cancelling the backstop.
if (useAuthStore.getState().isRefreshing) {
check(5000);
return;
}
setBootTimedOut(true);
if (bootReportedRef.current) return;
bootReportedRef.current = true;
reportSystemError({
level: 'warn',
component: 'App',
message: 'Boot loading timed out, continuing without blocking on init',
});
}, 20000);
return () => clearTimeout(timer);
}, delay);
};
check(20000);
return () => {
if (timer) clearTimeout(timer);
};
}, []);

// Load public theme settings (including custom CSS) once on mount
Expand Down Expand Up @@ -272,6 +323,33 @@ function App() {
);
}

// The session probe never settled (slow or unreachable backend). Falling
// through to the router would paint /login for a user whose session may still
// be valid, so every other path gets a retry screen instead — but the auth
// routes stay reachable, because `/api/auth/me` alone can be broken while
// signing in still works. `init()` and `login()` both clear the flag.
if (sessionCheckFailed && !isAuthenticated) {
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
return (
<ErrorBoundary resetKey={location.pathname}>
<ToastProvider />
<DemoBanner />
<PluginProvider>
<AnimatePresence initial={false}>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/register" element={<RegisterPage />} />
<Route path="/forgot-password" element={<ForgotPasswordPage />} />
<Route path="/reset-password" element={<ResetPasswordPage />} />
{/* 2FA is handled inline on LoginPage (totp dialog) — keep a redirect for old links */}
<Route path="/two-factor" element={<Navigate to="/login" replace />} />
<Route path="*" element={<SessionCheckFailedPage />} />
</Routes>
</AnimatePresence>
</PluginProvider>
</ErrorBoundary>
);
}

return (
<ErrorBoundary resetKey={location.pathname}>
<ToastProvider />
Expand Down
79 changes: 79 additions & 0 deletions catalyst-frontend/src/__tests__/App.sessionCheck.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* The retry screen for a boot session probe that never settled must not trap a
* signed-out user away from the sign-in form: `/api/auth/me` alone can be
* broken while `/api/auth/login` still works.
*/

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { useAuthStore } from '../stores/authStore';

vi.mock('../hooks/useAuthInit', () => ({ useAuthInit: () => {} }));
vi.mock('../hooks/useStreamRecovery', () => ({ useStreamRecovery: () => {} }));
vi.mock('../hooks/useSetupStatus', () => ({
useSetupStatus: () => ({
setupRequired: false,
isLoading: false,
unreachable: false,
error: null,
recheck: () => {},
}),
}));
vi.mock('../services/api/theme', () => ({
themeApi: { getPublicSettings: vi.fn(async () => ({ customCss: '' })) },
}));
vi.mock('../services/api/auth', () => ({
authApi: { getOAuthProviders: vi.fn(async () => []) },
}));
// The real provider pulls in the plugin loader's `@plugins` import glob, which
// vitest cannot resolve; the gate under test does not depend on it.
vi.mock('../plugins/PluginProvider', () => ({
PluginProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));

// jsdom has no ResizeObserver and the login card's primitives touch it.
globalThis.ResizeObserver = class {
observe() {}
unobserve() {}
disconnect() {}
} as unknown as typeof ResizeObserver;

import i18n from '../i18n';
import App from '../App';

function renderAt(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}

describe('App session-check retry screen', () => {
beforeEach(() => {
useAuthStore.setState({
isReady: true,
isAuthenticated: false,
user: null,
sessionCheckFailed: true,
isRefreshing: false,
});
});

afterEach(() => {
cleanup();
useAuthStore.setState({ sessionCheckFailed: false, isReady: false });
});

it('shows the retry screen for app routes', () => {
renderAt('/dashboard');
expect(screen.getByText(i18n.t('sessionCheck.failed'))).toBeInTheDocument();
});

it('offers a way to the sign-in form', async () => {
renderAt('/dashboard');
fireEvent.click(await screen.findByRole('link'));
await waitFor(() => expect(document.querySelector('input#email')).not.toBeNull());
});
});
66 changes: 51 additions & 15 deletions catalyst-frontend/src/hooks/useAuthInit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,66 @@ import { useAuthStore } from '../stores/authStore';
import { reportSystemError } from '../services/api/systemErrors';

const AUTH_INIT_TIMEOUT_MS = 12000;
/** One retry, so a slow-but-reachable backend still answers the probe. */
const MAX_ATTEMPTS = 2;

export function useAuthInit() {
const init = useAuthStore((s) => s.init);

useEffect(() => {
let settled = false;
const timer = setTimeout(() => {
if (!settled && !useAuthStore.getState().isReady) {
useAuthStore.setState({ isReady: true });
let cancelled = false;
const timers = new Set<ReturnType<typeof setTimeout>>();

/**
* Run the boot probe under a time limit. Never writing `isReady` here is the
* point: the store announces readiness when the session question is actually
* answered, so a slow backend cannot bounce an authenticated user to /login.
*/
const start = (attempt: number) => {
let settled = false;
const timer = setTimeout(() => {
timers.delete(timer);
if (cancelled || settled || useAuthStore.getState().isReady) return;
if (attempt < MAX_ATTEMPTS) {
// Re-arm the deadline rather than declaring "no session": if the first
// probe already failed this starts a fresh one, and if it is still
// running the retry joins it instead of racing a second request.
start(attempt + 1);
return;
}
// Still unresolved: fail open so the panel renders, and say so rather
// than presenting a bare sign-in form. App renders the retry screen off
// this flag; the retry button calls init() again.
settled = true;
useAuthStore.setState({ isReady: true, sessionCheckFailed: true });
reportSystemError({
level: 'warn',
component: 'useAuthInit',
message: `Auth init timed out after ${AUTH_INIT_TIMEOUT_MS}ms, continuing without session`,
message: `Auth init timed out after ${MAX_ATTEMPTS * AUTH_INIT_TIMEOUT_MS}ms, continuing without session`,
});
}, AUTH_INIT_TIMEOUT_MS);
timers.add(timer);

init()
.catch(() => {})
.finally(() => {
// init() can return without answering (the loginGuard short-circuit
// leaves the session to login()); only stop the clock once the store
// says the question is answered.
if (!useAuthStore.getState().isReady) return;
settled = true;
clearTimeout(timer);
timers.delete(timer);
});
}
}, AUTH_INIT_TIMEOUT_MS);
// Silently handle 401 — expected when no session exists
init().catch(() => {}).finally(() => {
settled = true;
clearTimeout(timer);
});
};

start(1);

// Silently handle 401 — expected when no session exists.
return () => {
settled = true;
clearTimeout(timer);
cancelled = true;
for (const timer of timers) clearTimeout(timer);
timers.clear();
};
}, [init]);
}
}
3 changes: 3 additions & 0 deletions catalyst-frontend/src/i18n/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@
"transfer": "Transfer server",
"update": "Update server settings"
},
"sessionCheck": {
"failed": "We could not verify your session. The panel may still be starting up, or the backend may be unreachable. Try again in a moment."
},
"setupStatus": {
"checkFailed": "Failed to check setup status",
"timedOut": "Setup check timed out after {{ms}}ms"
Expand Down
Loading
Loading