salvage: uncommitted work from /home/jwoltje/distrobox-homes/mosaic-dev/src/stack-p5a (disk cleanup #824, 2026-11-06)
This commit is contained in:
1 parent
216cd72226
commit
c0500a9b9b
47 files changed
+6359
-80
No files matched your search
+1
-11
@@ -11,17 +11,7 @@
|
||||
rel="stylesheet"
|
||||
href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Fira+Code:wght@400;500&display=swap"
|
||||
/>
|
||||
<script>
|
||||
// set data-theme before first paint so the stored theme never flashes
|
||||
(function () {
|
||||
try {
|
||||
var theme = window.localStorage.getItem('mosaic-theme') || 'dark';
|
||||
document.documentElement.setAttribute('data-theme', theme === 'light' ? 'light' : 'dark');
|
||||
} catch (error) {
|
||||
document.documentElement.setAttribute('data-theme', 'dark');
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<script src="/theme-init.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
// Set data-theme before first paint so the stored theme never flashes.
|
||||
try {
|
||||
const theme = window.localStorage.getItem('mosaic-theme') || 'dark';
|
||||
document.documentElement.setAttribute('data-theme', theme === 'light' ? 'light' : 'dark');
|
||||
} catch {
|
||||
document.documentElement.setAttribute('data-theme', 'dark');
|
||||
}
|
||||
+47
-15
@@ -1,5 +1,6 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import { createBrowserRouter, Navigate, Outlet, type RouteObject } from 'react-router-dom';
|
||||
import { SPA_ROUTES } from '@mosaicstack/types';
|
||||
import { LoginPage } from '@/spa/pages/login';
|
||||
import { RegisterPage } from '@/spa/pages/register';
|
||||
import { SsoCallbackPage } from '@/spa/pages/sso-callback';
|
||||
@@ -8,13 +9,17 @@ import { ChatRouteErrorBoundary } from '@/spa/pages/chat-error-boundary';
|
||||
import { ProjectDetailPage } from '@/spa/pages/project-detail';
|
||||
import { ProjectsPage } from '@/spa/pages/projects';
|
||||
import {
|
||||
AdminRouteErrorBoundary,
|
||||
ProjectDetailRouteErrorBoundary,
|
||||
ProjectsRouteErrorBoundary,
|
||||
SettingsRouteErrorBoundary,
|
||||
TasksRouteErrorBoundary,
|
||||
} from '@/spa/pages/resource-route-error-boundaries';
|
||||
import { TasksPage } from '@/spa/pages/tasks';
|
||||
import { SettingsPage } from '@/spa/pages/settings';
|
||||
import { AdminPage } from '@/spa/pages/admin';
|
||||
import { AuthGuard, GuestGuard } from '@/spa/guards';
|
||||
import { Placeholder } from '@/spa/placeholder';
|
||||
import { AppShellLayout } from '@/spa/layout/app-shell';
|
||||
|
||||
function GuestLayout(): ReactElement {
|
||||
return (
|
||||
@@ -33,9 +38,9 @@ export const routes: RouteObject[] = [
|
||||
{
|
||||
element: <GuestLayout />,
|
||||
children: [
|
||||
{ path: '/login', element: <LoginPage /> },
|
||||
{ path: '/register', element: <RegisterPage /> },
|
||||
{ path: '/auth/provider/:provider', element: <SsoCallbackPage /> },
|
||||
{ path: SPA_ROUTES.login.path, element: <LoginPage /> },
|
||||
{ path: SPA_ROUTES.register.path, element: <RegisterPage /> },
|
||||
{ path: SPA_ROUTES.authProvider.path, element: <SsoCallbackPage /> },
|
||||
],
|
||||
},
|
||||
],
|
||||
@@ -43,21 +48,48 @@ export const routes: RouteObject[] = [
|
||||
{
|
||||
element: <AuthGuard />,
|
||||
children: [
|
||||
{ path: '/', element: <Navigate to="/chat" replace /> },
|
||||
{ path: '/chat', element: <ChatPage />, errorElement: <ChatRouteErrorBoundary /> },
|
||||
{
|
||||
path: '/projects',
|
||||
element: <ProjectsPage />,
|
||||
errorElement: <ProjectsRouteErrorBoundary />,
|
||||
path: SPA_ROUTES.root.path,
|
||||
element: <Navigate to={SPA_ROUTES.chat.path} replace />,
|
||||
},
|
||||
// Pathless layout route: the dashboard shell mounts once and persists
|
||||
// across navigation. Adding no path keeps the route-table contract
|
||||
// (SPA_ROUTES set-equality) intact.
|
||||
{
|
||||
path: '/projects/:id',
|
||||
element: <ProjectDetailPage />,
|
||||
errorElement: <ProjectDetailRouteErrorBoundary />,
|
||||
element: <AppShellLayout />,
|
||||
children: [
|
||||
{
|
||||
path: SPA_ROUTES.chat.path,
|
||||
element: <ChatPage />,
|
||||
errorElement: <ChatRouteErrorBoundary />,
|
||||
},
|
||||
{
|
||||
path: SPA_ROUTES.projects.path,
|
||||
element: <ProjectsPage />,
|
||||
errorElement: <ProjectsRouteErrorBoundary />,
|
||||
},
|
||||
{
|
||||
path: SPA_ROUTES.projectDetail.path,
|
||||
element: <ProjectDetailPage />,
|
||||
errorElement: <ProjectDetailRouteErrorBoundary />,
|
||||
},
|
||||
{
|
||||
path: SPA_ROUTES.tasks.path,
|
||||
element: <TasksPage />,
|
||||
errorElement: <TasksRouteErrorBoundary />,
|
||||
},
|
||||
{
|
||||
path: SPA_ROUTES.settings.path,
|
||||
element: <SettingsPage />,
|
||||
errorElement: <SettingsRouteErrorBoundary />,
|
||||
},
|
||||
{
|
||||
path: SPA_ROUTES.admin.path,
|
||||
element: <AdminPage />,
|
||||
errorElement: <AdminRouteErrorBoundary />,
|
||||
},
|
||||
],
|
||||
},
|
||||
{ path: '/tasks', element: <TasksPage />, errorElement: <TasksRouteErrorBoundary /> },
|
||||
{ path: '/settings', element: <Placeholder title="Settings" /> },
|
||||
{ path: '/admin', element: <Placeholder title="Admin" /> },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import type { ReactElement, ReactNode } from 'react';
|
||||
import { Navigate, Outlet } from 'react-router-dom';
|
||||
import { SPA_ROUTES } from '@mosaicstack/types';
|
||||
import { useSession } from '@/lib/auth-client';
|
||||
|
||||
export function GuestGuard(): ReactElement {
|
||||
const { data: session } = useSession();
|
||||
|
||||
return session ? <Navigate to="/chat" replace /> : <Outlet />;
|
||||
return session ? <Navigate to={SPA_ROUTES.chat.path} replace /> : <Outlet />;
|
||||
}
|
||||
|
||||
export function AuthGuard(): ReactElement {
|
||||
@@ -19,5 +20,38 @@ export function AuthGuard(): ReactElement {
|
||||
);
|
||||
}
|
||||
|
||||
return session ? <Outlet /> : <Navigate to="/login" replace />;
|
||||
return session ? <Outlet /> : <Navigate to={SPA_ROUTES.login.path} replace />;
|
||||
}
|
||||
|
||||
// The shared `@/components/admin-role-guard` cannot be imported here: it routes
|
||||
// through `next/navigation`'s `useRouter`, which only works inside the Next.js
|
||||
// app runtime. This is the same relationship `GuestGuard`/`AuthGuard` above
|
||||
// have to the Next auth/guest guards: identical policy (pending → loading, no
|
||||
// session → login, non-admin → root), expressed with react-router navigation
|
||||
// instead. It stays a children wrapper rather than an `Outlet` layout guard
|
||||
// because the admin policy gates a single page, not a route group.
|
||||
export function AdminRoleGuard({ children }: { children: ReactNode }): ReactElement | null {
|
||||
const { data: session, isPending } = useSession();
|
||||
|
||||
const user = session?.user as
|
||||
| (NonNullable<typeof session>['user'] & { role?: string })
|
||||
| undefined;
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="text-sm text-text-muted">Loading...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
return <Navigate to={SPA_ROUTES.login.path} replace />;
|
||||
}
|
||||
|
||||
if (user?.role !== 'admin') {
|
||||
return <Navigate to={SPA_ROUTES.root.path} replace />;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi, type Mock } from 'vitest';
|
||||
import { SPA_ROUTES } from '@mosaicstack/types';
|
||||
|
||||
const { apiMock, useSessionMock, signOutMock } = vi.hoisted(() => ({
|
||||
apiMock: vi.fn(),
|
||||
useSessionMock: vi.fn(),
|
||||
signOutMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/auth-client', () => ({
|
||||
authClient: { updateUser: vi.fn() },
|
||||
useSession: useSessionMock,
|
||||
signIn: { oauth2: vi.fn() },
|
||||
signUp: vi.fn(),
|
||||
signOut: signOutMock,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
api: apiMock,
|
||||
}));
|
||||
|
||||
// The real chat page opens a socket.io connection on mount; the shell spec
|
||||
// exercises layout mounting, not chat behaviour, which has its own suite.
|
||||
vi.mock('@/spa/pages/chat', () => ({
|
||||
ChatPage: function ChatPageStub() {
|
||||
return <main>Chat page</main>;
|
||||
},
|
||||
}));
|
||||
|
||||
import { routes } from '@/routes';
|
||||
import { workspaceNavItems } from '@/spa/layout/sidebar';
|
||||
import { ThemeProvider } from '@/providers/theme-provider';
|
||||
|
||||
const adminSession = {
|
||||
user: {
|
||||
id: 'user-1',
|
||||
name: 'Ada Lovelace',
|
||||
email: '[email protected]',
|
||||
role: 'admin',
|
||||
},
|
||||
};
|
||||
|
||||
interface RenderedRouter {
|
||||
container: HTMLDivElement;
|
||||
router: ReturnType<typeof createMemoryRouter>;
|
||||
}
|
||||
|
||||
const mountedRoots: Root[] = [];
|
||||
const installedMatchMedia: Array<() => void> = [];
|
||||
const installedStorage: Array<() => void> = [];
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
// jsdom ships no matchMedia; the shell's SidebarProvider (shared with the
|
||||
// Next baseline) needs it to measure the mobile breakpoint. Desktop default
|
||||
// mirrors the non-mobile layout.
|
||||
function installMatchMedia(matches = false): void {
|
||||
const mediaQueryList: MediaQueryList = {
|
||||
matches,
|
||||
media: '',
|
||||
onchange: null,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
addListener: () => {},
|
||||
removeListener: () => {},
|
||||
dispatchEvent: () => false,
|
||||
};
|
||||
|
||||
const original = window.matchMedia;
|
||||
window.matchMedia = () => mediaQueryList;
|
||||
installedMatchMedia.push(() => {
|
||||
window.matchMedia = original;
|
||||
});
|
||||
}
|
||||
|
||||
// vitest's jsdom environment does not supply a usable window.localStorage — see
|
||||
// src/test/setup.ts, which installs a shared in-memory store. That store is
|
||||
// process-wide, so it would carry a persisted theme between tests in this file.
|
||||
// Install a fresh store per render, then restore the descriptor that was in
|
||||
// place beforehand — deleting the property instead would strip the setup file's
|
||||
// store from the window for the rest of the file.
|
||||
function installLocalStorage(): void {
|
||||
const store = new Map<string, string>();
|
||||
const storage: Storage = {
|
||||
length: store.size,
|
||||
getItem: (key: string) => store.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => void store.set(key, value),
|
||||
removeItem: (key: string) => void store.delete(key),
|
||||
clear: () => void store.clear(),
|
||||
key: (index: number) => [...store.keys()][index] ?? null,
|
||||
};
|
||||
|
||||
const original = Object.getOwnPropertyDescriptor(window, 'localStorage');
|
||||
Object.defineProperty(window, 'localStorage', {
|
||||
configurable: true,
|
||||
get: () => storage,
|
||||
});
|
||||
installedStorage.push(() => {
|
||||
if (original) {
|
||||
Object.defineProperty(window, 'localStorage', original);
|
||||
} else {
|
||||
Reflect.deleteProperty(window, 'localStorage');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function renderApp(
|
||||
initialEntry: string,
|
||||
{ mobile = false }: { mobile?: boolean } = {},
|
||||
): Promise<RenderedRouter> {
|
||||
installMatchMedia(mobile);
|
||||
installLocalStorage();
|
||||
document.documentElement.removeAttribute('data-theme');
|
||||
const router = createMemoryRouter(routes, { initialEntries: [initialEntry] });
|
||||
const container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
const root = createRoot(container);
|
||||
mountedRoots.push(root);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<ThemeProvider>
|
||||
<RouterProvider router={router} />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
return { container, router };
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
for (const restore of installedStorage.splice(0)) {
|
||||
restore();
|
||||
}
|
||||
for (const restore of installedMatchMedia.splice(0)) {
|
||||
restore();
|
||||
}
|
||||
for (const root of mountedRoots.splice(0)) {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
}
|
||||
document.body.replaceChildren();
|
||||
apiMock.mockReset();
|
||||
useSessionMock.mockReset();
|
||||
signOutMock.mockReset();
|
||||
});
|
||||
|
||||
function mockSignedIn(): void {
|
||||
useSessionMock.mockReturnValue({ data: adminSession, isPending: false });
|
||||
apiMock.mockResolvedValue([]);
|
||||
}
|
||||
|
||||
function mockSignedOut(): void {
|
||||
useSessionMock.mockReturnValue({ data: null, isPending: false });
|
||||
}
|
||||
|
||||
function findButtonByLabel(container: HTMLElement, label: string): HTMLButtonElement {
|
||||
const button = [...container.querySelectorAll('button')].find(
|
||||
(candidate) => candidate.getAttribute('aria-label') === label,
|
||||
);
|
||||
if (!button) {
|
||||
throw new Error(`Button with aria-label "${label}" not found`);
|
||||
}
|
||||
return button;
|
||||
}
|
||||
|
||||
function navLinks(container: HTMLElement): HTMLAnchorElement[] {
|
||||
return [...container.querySelectorAll<HTMLAnchorElement>('nav a')];
|
||||
}
|
||||
|
||||
function clickSignOut(view: RenderedRouter): Promise<void> {
|
||||
return act(async () => {
|
||||
[...view.container.querySelectorAll('button')]
|
||||
.find((button) => button.textContent === 'Sign out')
|
||||
?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
}
|
||||
|
||||
// Records every router location change after tracking starts. The sign-out
|
||||
// specs use this to prove no SOFT navigation occurred — half of the hard-handoff
|
||||
// contract. The other half (that the teardown actually happened) is covered by
|
||||
// stubDocumentLocation below.
|
||||
function trackSoftNavigations(view: RenderedRouter): {
|
||||
navigated: string[];
|
||||
stop: () => void;
|
||||
} {
|
||||
const navigated: string[] = [];
|
||||
const unsubscribe = view.router.subscribe(() => {
|
||||
navigated.push(view.router.state.location.pathname);
|
||||
});
|
||||
return { navigated, stop: unsubscribe };
|
||||
}
|
||||
|
||||
// Measured in this environment: `window.location.replace` is unforgeable — its
|
||||
// own descriptor is configurable=false, writable=false, and both assignment and
|
||||
// defineProperty on it throw TypeError. `window.location` itself, however, is a
|
||||
// configurable accessor on `window` and CAN be redefined, so swapping the whole
|
||||
// object is the seam that makes the sign-out document teardown observable.
|
||||
// Without it the handler could stop navigating altogether and every sign-out
|
||||
// test would still pass (verified by mutation). Safe here because the specs use
|
||||
// a memory router, which never reads the real location.
|
||||
function stubDocumentLocation(): { replace: Mock; restore: () => void } {
|
||||
const original = Object.getOwnPropertyDescriptor(window, 'location');
|
||||
const { href, origin, pathname, search, hash } = window.location;
|
||||
const replace = vi.fn();
|
||||
|
||||
Object.defineProperty(window, 'location', {
|
||||
configurable: true,
|
||||
value: { href, origin, pathname, search, hash, replace, assign: vi.fn(), reload: vi.fn() },
|
||||
});
|
||||
|
||||
return {
|
||||
replace,
|
||||
restore: () => {
|
||||
if (original) {
|
||||
Object.defineProperty(window, 'location', original);
|
||||
} else {
|
||||
Reflect.deleteProperty(window, 'location');
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('AppShellLayout mounting', () => {
|
||||
it.each([
|
||||
SPA_ROUTES.chat.path,
|
||||
SPA_ROUTES.tasks.path,
|
||||
SPA_ROUTES.projects.path,
|
||||
SPA_ROUTES.settings.path,
|
||||
SPA_ROUTES.admin.path,
|
||||
SPA_ROUTES.projectDetail.path.replace(':id', 'mission-1'),
|
||||
])('renders the dashboard shell around the page at %s', async (path) => {
|
||||
mockSignedIn();
|
||||
|
||||
const view = await renderApp(path);
|
||||
|
||||
expect(view.container.querySelector('aside')).not.toBeNull();
|
||||
expect(view.container.textContent).toContain('Sign out');
|
||||
});
|
||||
|
||||
it.each([
|
||||
SPA_ROUTES.login.path,
|
||||
SPA_ROUTES.register.path,
|
||||
SPA_ROUTES.authProvider.path.replace(':provider', 'authentik'),
|
||||
])('renders the auth page without the dashboard shell at %s', async (path) => {
|
||||
mockSignedOut();
|
||||
|
||||
const view = await renderApp(path);
|
||||
|
||||
expect(view.container.querySelector('aside')).toBeNull();
|
||||
expect(view.container.textContent).not.toContain('Sign out');
|
||||
expect(view.container.textContent).not.toContain('Mission Control');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AppShellLayout sidebar nav', () => {
|
||||
it('marks only the current destination as the current page', async () => {
|
||||
mockSignedIn();
|
||||
|
||||
const view = await renderApp(SPA_ROUTES.tasks.path);
|
||||
|
||||
const current = navLinks(view.container).filter(
|
||||
(link) => link.getAttribute('aria-current') === 'page',
|
||||
);
|
||||
expect(current).toHaveLength(1);
|
||||
expect(current[0]?.textContent).toContain('Tasks');
|
||||
});
|
||||
|
||||
it('marks Projects as current on a nested project detail route', async () => {
|
||||
mockSignedIn();
|
||||
|
||||
const view = await renderApp(SPA_ROUTES.projectDetail.path.replace(':id', 'mission-1'));
|
||||
|
||||
const current = navLinks(view.container).filter(
|
||||
(link) => link.getAttribute('aria-current') === 'page',
|
||||
);
|
||||
expect(current).toHaveLength(1);
|
||||
expect(current[0]?.textContent).toContain('Projects');
|
||||
});
|
||||
|
||||
it('targets exactly the workspace nav destinations', async () => {
|
||||
mockSignedIn();
|
||||
|
||||
const view = await renderApp(SPA_ROUTES.chat.path);
|
||||
|
||||
const links = navLinks(view.container);
|
||||
const renderedHrefs = links.map((link) => link.getAttribute('href'));
|
||||
expect(renderedHrefs).toEqual(workspaceNavItems.map((item) => item.href));
|
||||
// Independent of the href comparison above: every nav item must render a
|
||||
// non-empty accessible name — href parity alone cannot catch an item
|
||||
// whose label stops rendering.
|
||||
for (const link of links) {
|
||||
expect((link.textContent ?? '').trim().length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it('covers SPA_ROUTES so a new dashboard route cannot silently miss the nav', () => {
|
||||
// Routes intentionally absent from the nav: the root redirect, the auth
|
||||
// group, and the project detail view (reached through the Projects nav).
|
||||
// Any future SPA_ROUTES entry must join the nav or this exclusion list.
|
||||
const nonNavRoutes = [
|
||||
SPA_ROUTES.root,
|
||||
SPA_ROUTES.login,
|
||||
SPA_ROUTES.register,
|
||||
SPA_ROUTES.authProvider,
|
||||
SPA_ROUTES.projectDetail,
|
||||
];
|
||||
|
||||
const navAndExcluded = [
|
||||
...workspaceNavItems.map((item) => item.href),
|
||||
...nonNavRoutes.map((route) => route.path),
|
||||
].sort();
|
||||
const contractedPaths = Object.values(SPA_ROUTES)
|
||||
.map((route) => route.path)
|
||||
.sort();
|
||||
|
||||
expect(navAndExcluded).toEqual(contractedPaths);
|
||||
});
|
||||
});
|
||||
|
||||
describe('AppShellLayout topbar', () => {
|
||||
it('shows the session name, falling back to email', async () => {
|
||||
mockSignedIn();
|
||||
|
||||
const named = await renderApp(SPA_ROUTES.settings.path);
|
||||
expect(named.container.textContent).toContain('Ada Lovelace');
|
||||
|
||||
useSessionMock.mockReturnValue({
|
||||
data: { ...adminSession, user: { ...adminSession.user, name: null } },
|
||||
isPending: false,
|
||||
});
|
||||
|
||||
const unnamed = await renderApp(SPA_ROUTES.settings.path);
|
||||
expect(unnamed.container.textContent).toContain('[email protected]');
|
||||
});
|
||||
|
||||
it('flips the document theme from the topbar toggle', async () => {
|
||||
mockSignedIn();
|
||||
|
||||
const view = await renderApp(SPA_ROUTES.tasks.path);
|
||||
|
||||
expect(document.documentElement.getAttribute('data-theme')).toBe('dark');
|
||||
|
||||
const toggle = view.container.querySelector<HTMLButtonElement>(
|
||||
'button[title="Switch to light mode"]',
|
||||
);
|
||||
expect(toggle).not.toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
toggle?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(document.documentElement.getAttribute('data-theme')).toBe('light');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AppShellLayout sign-out', () => {
|
||||
it('tears the document down to the login route without soft-navigating while the session atom is still populated', async () => {
|
||||
mockSignedIn();
|
||||
// Real client ordering (better-auth 1.5.5): the sign-out POST resolves
|
||||
// while the session atom is still populated — it only clears on a delayed
|
||||
// /get-session refetch. A soft navigate to /login in that window is the
|
||||
// GuestGuard bounce the handler must avoid, so the mock must NOT touch
|
||||
// the session store.
|
||||
signOutMock.mockResolvedValue({ data: { success: true }, error: null });
|
||||
|
||||
const view = await renderApp(SPA_ROUTES.chat.path);
|
||||
const { navigated, stop } = trackSoftNavigations(view);
|
||||
const location = stubDocumentLocation();
|
||||
|
||||
try {
|
||||
await clickSignOut(view);
|
||||
} finally {
|
||||
stop();
|
||||
location.restore();
|
||||
}
|
||||
|
||||
expect(signOutMock).toHaveBeenCalledTimes(1);
|
||||
// A successful sign-out hands the whole document to the login route via
|
||||
// window.location.replace — atom, socket singleton and provider state are
|
||||
// discarded together.
|
||||
expect(location.replace).toHaveBeenCalledTimes(1);
|
||||
expect(location.replace).toHaveBeenCalledWith(SPA_ROUTES.login.path);
|
||||
// ...and it must be that hard handoff, not a soft navigate: the pre-fix
|
||||
// handler navigated to /login and GuestGuard bounced it straight back
|
||||
// through a re-mounted authenticated shell.
|
||||
expect(navigated).toEqual([]);
|
||||
expect(view.router.state.location.pathname).toBe(SPA_ROUTES.chat.path);
|
||||
});
|
||||
|
||||
it('keeps the session shell and surfaces the error when sign-out resolves with an error', async () => {
|
||||
mockSignedIn();
|
||||
// better-fetch resolves HTTP failures (500/403 on session revocation) as
|
||||
// { data: null, error } without throwing — the user must not be sent to
|
||||
// a signed-out URL while the session is still live.
|
||||
signOutMock.mockResolvedValue({
|
||||
data: null,
|
||||
error: { message: 'Server error', status: 500 },
|
||||
});
|
||||
|
||||
const view = await renderApp(SPA_ROUTES.chat.path);
|
||||
const { navigated, stop } = trackSoftNavigations(view);
|
||||
const location = stubDocumentLocation();
|
||||
|
||||
try {
|
||||
await clickSignOut(view);
|
||||
} finally {
|
||||
stop();
|
||||
location.restore();
|
||||
}
|
||||
|
||||
expect(location.replace).not.toHaveBeenCalled();
|
||||
expect(navigated).toEqual([]);
|
||||
expect(view.router.state.location.pathname).toBe(SPA_ROUTES.chat.path);
|
||||
expect(view.container.querySelector('[role="alert"]')?.textContent).toContain(
|
||||
'Sign out failed',
|
||||
);
|
||||
// The retry affordance stays mounted.
|
||||
expect(
|
||||
[...view.container.querySelectorAll('button')].some(
|
||||
(button) => button.textContent === 'Sign out',
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the session shell and surfaces the error when sign-out rejects', async () => {
|
||||
mockSignedIn();
|
||||
// Network-level failures reject (better-auth leaves catchAllError
|
||||
// unset); before the fix that rejection was unhandled and the button
|
||||
// silently did nothing.
|
||||
signOutMock.mockRejectedValue(new Error('network unreachable'));
|
||||
|
||||
const view = await renderApp(SPA_ROUTES.chat.path);
|
||||
const { navigated, stop } = trackSoftNavigations(view);
|
||||
const location = stubDocumentLocation();
|
||||
|
||||
try {
|
||||
await clickSignOut(view);
|
||||
} finally {
|
||||
stop();
|
||||
location.restore();
|
||||
}
|
||||
|
||||
expect(location.replace).not.toHaveBeenCalled();
|
||||
expect(navigated).toEqual([]);
|
||||
expect(view.router.state.location.pathname).toBe(SPA_ROUTES.chat.path);
|
||||
expect(view.container.querySelector('[role="alert"]')?.textContent).toContain(
|
||||
'Sign out failed',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('AppShellLayout sidebar toggle', () => {
|
||||
it('collapses and restores the sidebar on desktop from the topbar toggle', async () => {
|
||||
mockSignedIn();
|
||||
|
||||
const view = await renderApp(SPA_ROUTES.chat.path);
|
||||
|
||||
const shell = () => view.container.querySelector('.app-shell');
|
||||
expect(shell()?.getAttribute('data-sidebar-hidden')).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
findButtonByLabel(view.container, 'Toggle sidebar').dispatchEvent(
|
||||
new MouseEvent('click', { bubbles: true }),
|
||||
);
|
||||
});
|
||||
|
||||
expect(shell()?.getAttribute('data-sidebar-hidden')).toBe('true');
|
||||
|
||||
await act(async () => {
|
||||
findButtonByLabel(view.container, 'Toggle sidebar').dispatchEvent(
|
||||
new MouseEvent('click', { bubbles: true }),
|
||||
);
|
||||
});
|
||||
|
||||
expect(shell()?.getAttribute('data-sidebar-hidden')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('AppShellLayout shell persistence', () => {
|
||||
it('keeps one shell mounted across navigation and retains the collapsed state', async () => {
|
||||
mockSignedIn();
|
||||
|
||||
const view = await renderApp(SPA_ROUTES.chat.path);
|
||||
|
||||
// Collapse the sidebar on desktop first.
|
||||
const shell = () => view.container.querySelector('.app-shell');
|
||||
expect(shell()?.getAttribute('data-sidebar-hidden')).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
findButtonByLabel(view.container, 'Toggle sidebar').dispatchEvent(
|
||||
new MouseEvent('click', { bubbles: true }),
|
||||
);
|
||||
});
|
||||
expect(shell()?.getAttribute('data-sidebar-hidden')).toBe('true');
|
||||
|
||||
// Navigate through the sidebar nav itself, covering nav-driven
|
||||
// navigation.
|
||||
const tasksLink = navLinks(view.container).find(
|
||||
(link) => link.getAttribute('href') === SPA_ROUTES.tasks.path,
|
||||
);
|
||||
expect(tasksLink).toBeDefined();
|
||||
|
||||
await act(async () => {
|
||||
tasksLink?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
// The routed page swapped under the shell...
|
||||
expect(view.router.state.location.pathname).toBe(SPA_ROUTES.tasks.path);
|
||||
expect(view.container.querySelector('h1')?.textContent).toBe('Tasks');
|
||||
expect(view.container.textContent).not.toContain('Chat page');
|
||||
|
||||
// ...while the same SidebarProvider instance survived: its collapsed
|
||||
// state is still set and the shell is still mounted. A per-page or
|
||||
// pathname-keyed shell would reset collapsed to false here.
|
||||
expect(shell()?.getAttribute('data-sidebar-hidden')).toBe('true');
|
||||
expect(view.container.querySelector('aside')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('AppShellLayout mobile drawer', () => {
|
||||
it('opens the drawer from the topbar toggle and closes it from the overlay', async () => {
|
||||
mockSignedIn();
|
||||
|
||||
const view = await renderApp(SPA_ROUTES.tasks.path, { mobile: true });
|
||||
|
||||
const sidebar = () => view.container.querySelector('aside');
|
||||
expect(sidebar()?.getAttribute('data-mobile-open')).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
findButtonByLabel(view.container, 'Toggle sidebar').dispatchEvent(
|
||||
new MouseEvent('click', { bubbles: true }),
|
||||
);
|
||||
});
|
||||
|
||||
expect(sidebar()?.getAttribute('data-mobile-open')).toBe('true');
|
||||
expect(view.container.querySelector('[aria-label="Close sidebar"]')).not.toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
findButtonByLabel(view.container, 'Close sidebar').dispatchEvent(
|
||||
new MouseEvent('click', { bubbles: true }),
|
||||
);
|
||||
});
|
||||
|
||||
expect(sidebar()?.getAttribute('data-mobile-open')).toBeNull();
|
||||
expect(view.container.querySelector('[aria-label="Close sidebar"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import { Outlet } from 'react-router-dom';
|
||||
import { SidebarProvider, useSidebar } from '@/components/layout/sidebar-context';
|
||||
import { Sidebar } from './sidebar';
|
||||
import { Topbar } from './topbar';
|
||||
|
||||
// The shared `@/components/layout/app-shell` cannot be used directly: its
|
||||
// sidebar/topbar route through `next/link` and `next/navigation`, which only
|
||||
// work inside the Next.js app runtime. This is the same relationship
|
||||
// `spa/guards.tsx` has to the Next guards — identical structure, expressed with
|
||||
// react-router primitives — mounted as a pathless layout route so the shell
|
||||
// renders once and persists across navigation.
|
||||
function AppShellFrame(): ReactElement {
|
||||
const { collapsed, isMobile } = useSidebar();
|
||||
|
||||
return (
|
||||
<div className="app-shell" data-sidebar-hidden={!isMobile && collapsed ? 'true' : undefined}>
|
||||
<Topbar />
|
||||
<Sidebar />
|
||||
<div className="app-main">
|
||||
<main className="h-full overflow-y-auto p-6">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AppShellLayout(): ReactElement {
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<AppShellFrame />
|
||||
</SidebarProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { SPA_ROUTES } from '@mosaicstack/types';
|
||||
import { cn } from '@/lib/cn';
|
||||
import { MosaicLogo } from '@/components/ui/mosaic-logo';
|
||||
import { useSidebar } from '@/components/layout/sidebar-context';
|
||||
|
||||
interface NavItem {
|
||||
label: string;
|
||||
href: string;
|
||||
icon: React.JSX.Element;
|
||||
}
|
||||
|
||||
function IconChat(): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<path d="M3 4.5A2.5 2.5 0 0 1 5.5 2h5A2.5 2.5 0 0 1 13 4.5v3A2.5 2.5 0 0 1 10.5 10H8l-3.5 3v-3H5.5A2.5 2.5 0 0 1 3 7.5z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function IconTasks(): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<path d="M6 3h7M6 8h7M6 13h7" />
|
||||
<path d="M2.5 3.5 3.5 4.5 5 2.5M2.5 8.5 3.5 9.5 5 7.5M2.5 13.5 3.5 14.5 5 12.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function IconProjects(): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<path d="M2 4.5A1.5 1.5 0 0 1 3.5 3h3l1.5 1.5h4A1.5 1.5 0 0 1 13.5 6v5.5A1.5 1.5 0 0 1 12 13H3.5A1.5 1.5 0 0 1 2 11.5z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function IconSettings(): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<circle cx="8" cy="8" r="2.25" />
|
||||
<path d="M8 1.5v2M8 12.5v2M1.5 8h2M12.5 8h2M3.05 3.05l1.4 1.4M11.55 11.55l1.4 1.4M3.05 12.95l1.4-1.4M11.55 4.45l1.4-1.4" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function IconAdmin(): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<path d="M8 1.75 13 3.5v3.58c0 3.12-1.88 5.94-5 7.17-3.12-1.23-5-4.05-5-7.17V3.5z" />
|
||||
<path d="M6.25 7.75 7.5 9l2.5-2.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// Every href resolves through SPA_ROUTES; the workspace nav must never embed a
|
||||
// literal path. The layout spec asserts this list against SPA_ROUTES so a new
|
||||
// dashboard route cannot silently miss the nav.
|
||||
export const workspaceNavItems: NavItem[] = [
|
||||
{ label: 'Chat', href: SPA_ROUTES.chat.path, icon: <IconChat /> },
|
||||
{ label: 'Tasks', href: SPA_ROUTES.tasks.path, icon: <IconTasks /> },
|
||||
{ label: 'Projects', href: SPA_ROUTES.projects.path, icon: <IconProjects /> },
|
||||
{ label: 'Settings', href: SPA_ROUTES.settings.path, icon: <IconSettings /> },
|
||||
{ label: 'Admin', href: SPA_ROUTES.admin.path, icon: <IconAdmin /> },
|
||||
];
|
||||
|
||||
export function Sidebar(): React.JSX.Element {
|
||||
const { pathname } = useLocation();
|
||||
const { mobileOpen, setMobileOpen } = useSidebar();
|
||||
|
||||
return (
|
||||
<>
|
||||
<aside
|
||||
className="app-sidebar"
|
||||
data-mobile-open={mobileOpen ? 'true' : undefined}
|
||||
style={{
|
||||
width: 'var(--sidebar-w)',
|
||||
background: 'var(--surface)',
|
||||
borderRightColor: 'var(--border)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="flex h-16 items-center gap-3 border-b px-5"
|
||||
style={{ borderColor: 'var(--border)' }}
|
||||
>
|
||||
<MosaicLogo size={32} />
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="text-sm font-semibold uppercase tracking-[0.12em] text-[var(--text)]">
|
||||
Mosaic
|
||||
</span>
|
||||
<span className="text-xs text-[var(--muted)]">Mission Control</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 px-3 py-4">
|
||||
<div className="mb-3 px-2 text-[11px] font-medium uppercase tracking-[0.18em] text-[var(--muted)]">
|
||||
Workspace
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
{workspaceNavItems.map((item) => {
|
||||
const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`);
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
to={item.href}
|
||||
onClick={() => setMobileOpen(false)}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
className={cn(
|
||||
'group flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm transition-all duration-150',
|
||||
isActive ? 'font-medium' : 'hover:bg-white/4',
|
||||
)}
|
||||
style={
|
||||
isActive
|
||||
? {
|
||||
background: 'color-mix(in srgb, var(--primary) 18%, transparent)',
|
||||
color: 'var(--primary)',
|
||||
}
|
||||
: { color: 'var(--text-2)' }
|
||||
}
|
||||
>
|
||||
<span className="shrink-0" aria-hidden="true">
|
||||
{item.icon}
|
||||
</span>
|
||||
<span>{item.label}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div className="border-t px-5 py-4" style={{ borderColor: 'var(--border)' }}>
|
||||
<p className="text-xs text-[var(--muted)]">Mosaic Stack v0.0.4</p>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{mobileOpen ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Close sidebar"
|
||||
className="fixed inset-0 z-40 bg-black/40 md:hidden"
|
||||
onClick={() => setMobileOpen(false)}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { useState } from 'react';
|
||||
import { SPA_ROUTES } from '@mosaicstack/types';
|
||||
import { signOut, useSession } from '@/lib/auth-client';
|
||||
import { ThemeToggle } from '@/components/layout/theme-toggle';
|
||||
import { useSidebar } from '@/components/layout/sidebar-context';
|
||||
|
||||
function MenuIcon(): React.JSX.Element {
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<path d="M2 4h12M2 8h12M2 12h12" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function Topbar(): React.JSX.Element {
|
||||
const { data: session } = useSession();
|
||||
const [signOutFailed, setSignOutFailed] = useState(false);
|
||||
const { isMobile, mobileOpen, setMobileOpen, toggleCollapsed } = useSidebar();
|
||||
|
||||
async function handleSignOut(): Promise<void> {
|
||||
setSignOutFailed(false);
|
||||
|
||||
// better-auth's client leaves better-fetch's catchAllError unset, so HTTP
|
||||
// failures (e.g. 500/403 on session revocation) resolve as
|
||||
// { data: null, error } and only network-level failures reject. Either
|
||||
// way the user must stay here: navigating to /login with a live session
|
||||
// strands them on a signed-out URL while still authenticated.
|
||||
try {
|
||||
const result = await signOut();
|
||||
if (result.error) {
|
||||
setSignOutFailed(true);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
setSignOutFailed(true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Full document teardown, not a soft navigate: better-auth clears the
|
||||
// session atom only on a delayed /get-session refetch after the sign-out
|
||||
// POST, so a soft navigate would land on /login with the atom still
|
||||
// populated and GuestGuard would bounce the user back through a
|
||||
// re-mounted authenticated shell (new socket). Replacing the document
|
||||
// discards the atom, the socket singleton and all provider state in one
|
||||
// step, letting the guards bootstrap from a clean state.
|
||||
window.location.replace(SPA_ROUTES.login.path);
|
||||
}
|
||||
|
||||
function handleSidebarToggle(): void {
|
||||
if (isMobile) {
|
||||
setMobileOpen(!mobileOpen);
|
||||
return;
|
||||
}
|
||||
|
||||
toggleCollapsed();
|
||||
}
|
||||
|
||||
return (
|
||||
<header
|
||||
className="app-header justify-between border-b px-4 md:px-6"
|
||||
style={{
|
||||
height: 'var(--topbar-h)',
|
||||
background: 'color-mix(in srgb, var(--surface) 88%, transparent)',
|
||||
borderBottomColor: 'var(--border)',
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSidebarToggle}
|
||||
className="btn-ghost rounded-lg border p-2"
|
||||
style={{ borderColor: 'var(--border)', color: 'var(--text-2)' }}
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
<MenuIcon />
|
||||
</button>
|
||||
<div className="hidden sm:block">
|
||||
<div className="text-sm font-medium text-[var(--text)]">Workspace</div>
|
||||
<div className="text-xs text-[var(--muted)]">Unified agent operations</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<ThemeToggle />
|
||||
{session?.user ? (
|
||||
<>
|
||||
{signOutFailed ? (
|
||||
<span
|
||||
role="alert"
|
||||
className="rounded-md border border-error/30 bg-error/10 px-2.5 py-1 text-xs text-error"
|
||||
>
|
||||
Sign out failed. Try again.
|
||||
</span>
|
||||
) : null}
|
||||
<span className="hidden text-sm text-[var(--text-2)] sm:block">
|
||||
{session.user.name ?? session.user.email}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSignOut}
|
||||
className="rounded-md px-3 py-1.5 text-sm transition-colors"
|
||||
style={{ color: 'var(--muted)' }}
|
||||
>
|
||||
Sign out
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-sm text-[var(--muted)]">Not signed in</span>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { SPA_ROUTES } from '@mosaicstack/types';
|
||||
|
||||
const { apiMock, useSessionMock } = vi.hoisted(() => ({
|
||||
apiMock: vi.fn(),
|
||||
useSessionMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
api: apiMock,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/auth-client', () => ({
|
||||
useSession: useSessionMock,
|
||||
}));
|
||||
|
||||
import { AdminPage } from './admin';
|
||||
|
||||
const adminSession = {
|
||||
user: { id: 'admin-1', name: 'Grace', email: '[email protected]', role: 'admin' },
|
||||
};
|
||||
|
||||
const memberSession = {
|
||||
user: { id: 'user-2', name: 'Alan', email: '[email protected]', role: 'member' },
|
||||
};
|
||||
|
||||
const userFixtures = [
|
||||
{
|
||||
id: 'admin-1',
|
||||
name: 'Grace',
|
||||
email: '[email protected]',
|
||||
role: 'admin',
|
||||
banned: false,
|
||||
banReason: null,
|
||||
createdAt: '2026-03-01T09:00:00.000Z',
|
||||
updatedAt: '2026-03-01T09:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'user-2',
|
||||
name: 'Alan',
|
||||
email: '[email protected]',
|
||||
role: 'member',
|
||||
banned: false,
|
||||
banReason: null,
|
||||
createdAt: '2026-04-01T09:00:00.000Z',
|
||||
updatedAt: '2026-04-01T09:00:00.000Z',
|
||||
},
|
||||
];
|
||||
|
||||
const healthFixture = {
|
||||
status: 'ok',
|
||||
database: { status: 'ok', latencyMs: 3 },
|
||||
cache: { status: 'ok', latencyMs: 1 },
|
||||
agentPool: { activeSessions: 2 },
|
||||
providers: [{ id: 'ollama', name: 'Ollama', available: true, modelCount: 5 }],
|
||||
checkedAt: '2026-04-20T12:00:00.000Z',
|
||||
};
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
root = null;
|
||||
apiMock.mockReset();
|
||||
useSessionMock.mockReset();
|
||||
});
|
||||
|
||||
async function renderAdminPage(): Promise<ReturnType<typeof createMemoryRouter>> {
|
||||
const routes: RouteObject[] = [
|
||||
{ path: SPA_ROUTES.admin.path, element: <AdminPage /> },
|
||||
{ path: SPA_ROUTES.root.path, element: <p>Root redirect target</p> },
|
||||
{ path: SPA_ROUTES.login.path, element: <p>Login redirect target</p> },
|
||||
];
|
||||
const router = createMemoryRouter(routes, { initialEntries: [SPA_ROUTES.admin.path] });
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(<RouterProvider router={router} />);
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
function clickButtonByText(text: string): void {
|
||||
const button = [...container.querySelectorAll('button')].find((candidate) =>
|
||||
candidate.textContent?.includes(text),
|
||||
);
|
||||
if (!button) {
|
||||
throw new Error(`Button containing "${text}" not found`);
|
||||
}
|
||||
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
}
|
||||
|
||||
describe('AdminPage', () => {
|
||||
it('renders the guard loading state and makes no API calls while the session is pending', async () => {
|
||||
useSessionMock.mockReturnValue({ data: null, isPending: true });
|
||||
|
||||
await renderAdminPage();
|
||||
|
||||
expect(container.textContent).toContain('Loading...');
|
||||
expect(container.textContent).not.toContain('Admin Panel');
|
||||
expect(apiMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects a signed-out session to the login route', async () => {
|
||||
useSessionMock.mockReturnValue({ data: null, isPending: false });
|
||||
|
||||
const router = await renderAdminPage();
|
||||
|
||||
expect(router.state.location.pathname).toBe(SPA_ROUTES.login.path);
|
||||
expect(container.textContent).toContain('Login redirect target');
|
||||
expect(container.textContent).not.toContain('Admin Panel');
|
||||
expect(apiMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects a non-admin session to the app root', async () => {
|
||||
useSessionMock.mockReturnValue({ data: memberSession, isPending: false });
|
||||
|
||||
const router = await renderAdminPage();
|
||||
|
||||
expect(router.state.location.pathname).toBe(SPA_ROUTES.root.path);
|
||||
expect(container.textContent).toContain('Root redirect target');
|
||||
expect(container.textContent).not.toContain('Admin Panel');
|
||||
expect(apiMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('loads and renders the user management table for admins', async () => {
|
||||
useSessionMock.mockReturnValue({ data: adminSession, isPending: false });
|
||||
apiMock.mockResolvedValueOnce({ users: userFixtures, total: 2 });
|
||||
|
||||
await renderAdminPage();
|
||||
|
||||
expect(apiMock.mock.calls).toEqual([['/api/admin/users']]);
|
||||
expect(container.textContent).toContain('Admin Panel');
|
||||
expect(container.textContent).toContain('2 user(s)');
|
||||
expect(container.textContent).toContain('[email protected]');
|
||||
expect(container.textContent).toContain('[email protected]');
|
||||
expect(container.textContent).toContain('Demote');
|
||||
expect(container.textContent).toContain('Promote');
|
||||
expect(container.textContent).toContain('Active');
|
||||
});
|
||||
|
||||
it('promotes a member through the role endpoint and reloads the user list', async () => {
|
||||
useSessionMock.mockReturnValue({ data: adminSession, isPending: false });
|
||||
apiMock
|
||||
.mockResolvedValueOnce({ users: userFixtures, total: 2 })
|
||||
.mockResolvedValueOnce({})
|
||||
.mockResolvedValueOnce({
|
||||
users: userFixtures.map((user) =>
|
||||
user.id === 'user-2' ? { ...user, role: 'admin' } : user,
|
||||
),
|
||||
total: 2,
|
||||
});
|
||||
|
||||
await renderAdminPage();
|
||||
|
||||
const alanRow = [...container.querySelectorAll('tr')].find((candidate) =>
|
||||
candidate.textContent?.includes('[email protected]'),
|
||||
);
|
||||
expect(alanRow?.textContent).toContain('Promote');
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Promote');
|
||||
});
|
||||
|
||||
expect(apiMock.mock.calls).toEqual([
|
||||
['/api/admin/users'],
|
||||
['/api/admin/users/user-2/role', { method: 'PATCH', body: { role: 'admin' } }],
|
||||
['/api/admin/users'],
|
||||
]);
|
||||
|
||||
const updatedAlanRow = [...container.querySelectorAll('tr')].find((candidate) =>
|
||||
candidate.textContent?.includes('[email protected]'),
|
||||
);
|
||||
expect(updatedAlanRow?.textContent).toContain('Demote');
|
||||
});
|
||||
|
||||
it('renders the users error state and recovers through retry', async () => {
|
||||
useSessionMock.mockReturnValue({ data: adminSession, isPending: false });
|
||||
apiMock.mockRejectedValueOnce(new Error('Admin users offline'));
|
||||
|
||||
await renderAdminPage();
|
||||
|
||||
expect(container.textContent).toContain('Admin users offline');
|
||||
expect(container.textContent).not.toContain('[email protected]');
|
||||
|
||||
apiMock.mockResolvedValueOnce({ users: userFixtures, total: 2 });
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Retry');
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain('[email protected]');
|
||||
expect(container.textContent).toContain('2 user(s)');
|
||||
});
|
||||
|
||||
it('renders system health status for admins', async () => {
|
||||
useSessionMock.mockReturnValue({ data: adminSession, isPending: false });
|
||||
apiMock.mockResolvedValueOnce({ users: [], total: 0 }).mockResolvedValueOnce(healthFixture);
|
||||
|
||||
await renderAdminPage();
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('System Health');
|
||||
});
|
||||
|
||||
expect(apiMock.mock.calls).toEqual([['/api/admin/users'], ['/api/admin/health']]);
|
||||
|
||||
expect(container.textContent).toContain('Database (PostgreSQL)');
|
||||
expect(container.textContent).toContain('Latency: 3ms');
|
||||
expect(container.textContent).toContain('Cache (Valkey)');
|
||||
expect(container.textContent).toContain('Active sessions: 2');
|
||||
expect(container.textContent).toContain('LLM Providers');
|
||||
expect(container.textContent).toContain('Ollama');
|
||||
expect(container.textContent).toContain('5 models');
|
||||
expect(container.textContent).toContain('Refresh');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,536 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useState,
|
||||
type FormEvent,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { api } from '@/lib/api';
|
||||
import { cn } from '@/lib/cn';
|
||||
import { AdminRoleGuard } from '@/spa/guards';
|
||||
|
||||
// ── Types ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface UserDto {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string;
|
||||
banned: boolean;
|
||||
banReason: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
interface UserListDto {
|
||||
users: UserDto[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface ServiceStatusDto {
|
||||
status: 'ok' | 'error';
|
||||
latencyMs?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface ProviderStatusDto {
|
||||
id: string;
|
||||
name: string;
|
||||
available: boolean;
|
||||
modelCount: number;
|
||||
}
|
||||
|
||||
interface HealthStatusDto {
|
||||
status: 'ok' | 'degraded' | 'error';
|
||||
database: ServiceStatusDto;
|
||||
cache: ServiceStatusDto;
|
||||
agentPool: { activeSessions: number };
|
||||
providers: ProviderStatusDto[];
|
||||
checkedAt: string;
|
||||
}
|
||||
|
||||
// ── Admin Page ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export function AdminPage(): ReactElement {
|
||||
return (
|
||||
<AdminRoleGuard>
|
||||
<AdminContent />
|
||||
</AdminRoleGuard>
|
||||
);
|
||||
}
|
||||
|
||||
function AdminContent(): ReactElement {
|
||||
const [activeTab, setActiveTab] = useState<'users' | 'health'>('users');
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-5xl space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-semibold text-text-primary">Admin Panel</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 border-b border-surface-border">
|
||||
{(['users', 'health'] as const).map((tab) => (
|
||||
<button
|
||||
key={tab}
|
||||
type="button"
|
||||
onClick={() => setActiveTab(tab)}
|
||||
className={cn(
|
||||
'px-4 py-2 text-sm font-medium capitalize transition-colors',
|
||||
activeTab === tab
|
||||
? 'border-b-2 border-blue-500 text-blue-400'
|
||||
: 'text-text-secondary hover:text-text-primary',
|
||||
)}
|
||||
>
|
||||
{tab === 'users' ? 'User Management' : 'System Health'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{activeTab === 'users' ? <UsersTab /> : <HealthTab />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Users Tab ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function UsersTab(): ReactElement {
|
||||
const [users, setUsers] = useState<UserDto[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
|
||||
const loadUsers = useCallback(async (): Promise<void> => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await api<UserListDto>('/api/admin/users');
|
||||
setUsers(data.users);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load users');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadUsers();
|
||||
}, [loadUsers]);
|
||||
|
||||
async function handleRoleToggle(user: UserDto): Promise<void> {
|
||||
const newRole = user.role === 'admin' ? 'member' : 'admin';
|
||||
try {
|
||||
await api(`/api/admin/users/${user.id}/role`, {
|
||||
method: 'PATCH',
|
||||
body: { role: newRole },
|
||||
});
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to update role');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleBanToggle(user: UserDto): Promise<void> {
|
||||
const endpoint = user.banned ? 'unban' : 'ban';
|
||||
try {
|
||||
await api(`/api/admin/users/${user.id}/${endpoint}`, { method: 'POST' });
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to update ban status');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(user: UserDto): Promise<void> {
|
||||
if (!confirm(`Delete user ${user.email}? This cannot be undone.`)) return;
|
||||
try {
|
||||
await api(`/api/admin/users/${user.id}`, { method: 'DELETE' });
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Failed to delete user');
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <p className="text-sm text-text-muted">Loading users...</p>;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="rounded-lg border border-red-500/30 bg-red-500/10 p-4">
|
||||
<p className="text-sm text-red-400">{error}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void loadUsers()}
|
||||
className="mt-2 text-xs text-red-300 underline hover:no-underline"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-text-muted">{users.length} user(s)</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCreate(true)}
|
||||
className="rounded-md bg-blue-600 px-3 py-1.5 text-sm text-white transition-colors hover:bg-blue-700"
|
||||
>
|
||||
+ New User
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showCreate && (
|
||||
<CreateUserForm
|
||||
onCancel={() => setShowCreate(false)}
|
||||
onCreated={() => {
|
||||
setShowCreate(false);
|
||||
void loadUsers();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{users.length === 0 ? (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-6 text-center">
|
||||
<p className="text-sm text-text-muted">No users found</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-hidden rounded-lg border border-surface-border">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="border-b border-surface-border bg-surface-elevated text-left text-xs text-text-muted">
|
||||
<th className="px-4 py-2 font-medium">Name / Email</th>
|
||||
<th className="px-4 py-2 font-medium">Role</th>
|
||||
<th className="hidden px-4 py-2 font-medium md:table-cell">Status</th>
|
||||
<th className="hidden px-4 py-2 font-medium md:table-cell">Created</th>
|
||||
<th className="px-4 py-2 font-medium">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((user) => (
|
||||
<tr key={user.id} className="border-b border-surface-border last:border-b-0">
|
||||
<td className="px-4 py-3">
|
||||
<div className="text-sm font-medium text-text-primary">{user.name}</div>
|
||||
<div className="text-xs text-text-muted">{user.email}</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',
|
||||
user.role === 'admin'
|
||||
? 'bg-purple-500/20 text-purple-400'
|
||||
: 'bg-surface-elevated text-text-secondary',
|
||||
)}
|
||||
>
|
||||
{user.role}
|
||||
</span>
|
||||
</td>
|
||||
<td className="hidden px-4 py-3 md:table-cell">
|
||||
{user.banned ? (
|
||||
<span className="inline-flex rounded-full bg-red-500/20 px-2 py-0.5 text-xs font-medium text-red-400">
|
||||
Banned
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex rounded-full bg-green-500/20 px-2 py-0.5 text-xs font-medium text-green-400">
|
||||
Active
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="hidden px-4 py-3 text-xs text-text-muted md:table-cell">
|
||||
{new Date(user.createdAt).toLocaleDateString()}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleRoleToggle(user)}
|
||||
className="text-xs text-blue-400 hover:text-blue-300"
|
||||
title={user.role === 'admin' ? 'Demote to member' : 'Promote to admin'}
|
||||
>
|
||||
{user.role === 'admin' ? 'Demote' : 'Promote'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleBanToggle(user)}
|
||||
className={cn(
|
||||
'text-xs',
|
||||
user.banned
|
||||
? 'text-green-400 hover:text-green-300'
|
||||
: 'text-yellow-400 hover:text-yellow-300',
|
||||
)}
|
||||
>
|
||||
{user.banned ? 'Unban' : 'Ban'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleDelete(user)}
|
||||
className="text-xs text-red-400 hover:text-red-300"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Create User Form ──────────────────────────────────────────────────────────
|
||||
|
||||
interface CreateUserFormProps {
|
||||
onCancel: () => void;
|
||||
onCreated: () => void;
|
||||
}
|
||||
|
||||
function CreateUserForm({ onCancel, onCreated }: CreateUserFormProps): ReactElement {
|
||||
const [name, setName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [role, setRole] = useState('member');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleSubmit(e: FormEvent): Promise<void> {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api('/api/admin/users', {
|
||||
method: 'POST',
|
||||
body: { name, email, password, role },
|
||||
});
|
||||
onCreated();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to create user');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4">
|
||||
<h3 className="mb-3 text-sm font-medium text-text-primary">Create New User</h3>
|
||||
<form onSubmit={(e) => void handleSubmit(e)} className="space-y-3">
|
||||
{error && <p className="text-xs text-red-400">{error}</p>}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="mb-1 block text-xs text-text-muted">Name</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="w-full rounded-md border border-surface-border bg-surface-elevated px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs text-text-muted">Email</label>
|
||||
<input
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="w-full rounded-md border border-surface-border bg-surface-elevated px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs text-text-muted">Password</label>
|
||||
<input
|
||||
type="password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="w-full rounded-md border border-surface-border bg-surface-elevated px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs text-text-muted">Role</label>
|
||||
<select
|
||||
value={role}
|
||||
onChange={(e) => setRole(e.target.value)}
|
||||
className="w-full rounded-md border border-surface-border bg-surface-elevated px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
>
|
||||
<option value="member">member</option>
|
||||
<option value="admin">admin</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
className="rounded-md px-3 py-1.5 text-sm text-text-muted hover:text-text-primary"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting}
|
||||
className="rounded-md bg-blue-600 px-3 py-1.5 text-sm text-white hover:bg-blue-700 disabled:opacity-50"
|
||||
>
|
||||
{submitting ? 'Creating...' : 'Create'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Health Tab ────────────────────────────────────────────────────────────────
|
||||
|
||||
function HealthTab(): ReactElement {
|
||||
const [health, setHealth] = useState<HealthStatusDto | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const loadHealth = useCallback(async (): Promise<void> => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await api<HealthStatusDto>('/api/admin/health');
|
||||
setHealth(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load health');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadHealth();
|
||||
}, [loadHealth]);
|
||||
|
||||
if (loading) {
|
||||
return <p className="text-sm text-text-muted">Loading health status...</p>;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="rounded-lg border border-red-500/30 bg-red-500/10 p-4">
|
||||
<p className="text-sm text-red-400">{error}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void loadHealth()}
|
||||
className="mt-2 text-xs text-red-300 underline hover:no-underline"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!health) return <></>;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusBadge status={health.status} />
|
||||
<span className="text-sm text-text-muted">
|
||||
Last checked: {new Date(health.checkedAt).toLocaleTimeString()}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void loadHealth()}
|
||||
className="text-xs text-blue-400 hover:text-blue-300"
|
||||
>
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
{/* Database */}
|
||||
<HealthCard title="Database (PostgreSQL)" status={health.database.status}>
|
||||
{health.database.latencyMs !== undefined && (
|
||||
<p className="text-xs text-text-muted">Latency: {health.database.latencyMs}ms</p>
|
||||
)}
|
||||
{health.database.error && <p className="text-xs text-red-400">{health.database.error}</p>}
|
||||
</HealthCard>
|
||||
|
||||
{/* Cache */}
|
||||
<HealthCard title="Cache (Valkey)" status={health.cache.status}>
|
||||
{health.cache.latencyMs !== undefined && (
|
||||
<p className="text-xs text-text-muted">Latency: {health.cache.latencyMs}ms</p>
|
||||
)}
|
||||
{health.cache.error && <p className="text-xs text-red-400">{health.cache.error}</p>}
|
||||
</HealthCard>
|
||||
|
||||
{/* Agent Pool */}
|
||||
<HealthCard title="Agent Pool" status="ok">
|
||||
<p className="text-xs text-text-muted">
|
||||
Active sessions: {health.agentPool.activeSessions}
|
||||
</p>
|
||||
</HealthCard>
|
||||
|
||||
{/* Providers */}
|
||||
<HealthCard
|
||||
title="LLM Providers"
|
||||
status={health.providers.some((p) => p.available) ? 'ok' : 'error'}
|
||||
>
|
||||
{health.providers.length === 0 ? (
|
||||
<p className="text-xs text-text-muted">No providers configured</p>
|
||||
) : (
|
||||
<ul className="space-y-1">
|
||||
{health.providers.map((p) => (
|
||||
<li key={p.id} className="flex items-center justify-between text-xs">
|
||||
<span className="text-text-secondary">{p.name}</span>
|
||||
<span
|
||||
className={cn(
|
||||
'rounded-full px-1.5 py-0.5',
|
||||
p.available ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400',
|
||||
)}
|
||||
>
|
||||
{p.available ? `${p.modelCount} models` : 'unavailable'}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</HealthCard>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Helper Components ─────────────────────────────────────────────────────────
|
||||
|
||||
function StatusBadge({ status }: { status: 'ok' | 'degraded' | 'error' }): ReactElement {
|
||||
const map = {
|
||||
ok: 'bg-green-500/20 text-green-400',
|
||||
degraded: 'bg-yellow-500/20 text-yellow-400',
|
||||
error: 'bg-red-500/20 text-red-400',
|
||||
};
|
||||
return (
|
||||
<span className={cn('rounded-full px-2 py-0.5 text-xs font-medium capitalize', map[status])}>
|
||||
{status}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
interface HealthCardProps {
|
||||
title: string;
|
||||
status: 'ok' | 'error';
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
function HealthCard({ title, status, children }: HealthCardProps): ReactElement {
|
||||
return (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<h3 className="text-sm font-medium text-text-primary">{title}</h3>
|
||||
<span
|
||||
className={cn('h-2 w-2 rounded-full', status === 'ok' ? 'bg-green-400' : 'bg-red-400')}
|
||||
/>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ vi.mock('@/lib/auth-client', () => ({
|
||||
}));
|
||||
|
||||
import { routes } from '@/routes';
|
||||
import { ThemeProvider } from '@/providers/theme-provider';
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
@@ -73,7 +74,11 @@ describe('ChatRouteErrorBoundary', () => {
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
try {
|
||||
await act(async () => {
|
||||
root?.render(<RouterProvider router={router} />);
|
||||
root?.render(
|
||||
<ThemeProvider>
|
||||
<RouterProvider router={router} />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalled();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { CoordMissionStatus } from './projects';
|
||||
import type { Mission, Project, Task } from '@/lib/types';
|
||||
|
||||
export const projectFixtures: Project[] = [
|
||||
@@ -25,6 +26,33 @@ export const projectFixtures: Project[] = [
|
||||
},
|
||||
];
|
||||
|
||||
export const coordMissionStatusFixture: CoordMissionStatus = {
|
||||
mission: {
|
||||
id: 'coord-mission-1',
|
||||
name: 'Ship the gateway static surface',
|
||||
status: 'active',
|
||||
projectPath: '/workspace/stack',
|
||||
},
|
||||
milestones: {
|
||||
total: 4,
|
||||
completed: 1,
|
||||
current: {
|
||||
id: 'milestone-2',
|
||||
name: 'Static serving',
|
||||
status: 'in-progress',
|
||||
},
|
||||
},
|
||||
tasks: {
|
||||
total: 7,
|
||||
done: 3,
|
||||
inProgress: 2,
|
||||
pending: 1,
|
||||
blocked: 1,
|
||||
cancelled: 0,
|
||||
},
|
||||
nextTaskId: 'task-5',
|
||||
};
|
||||
|
||||
export const missionFixtures: Mission[] = [
|
||||
{
|
||||
id: 'mission-1',
|
||||
|
||||
@@ -2,7 +2,7 @@ import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { projectFixtures } from './page-fixtures';
|
||||
import { coordMissionStatusFixture, projectFixtures } from './page-fixtures';
|
||||
|
||||
const { apiMock } = vi.hoisted(() => ({
|
||||
apiMock: vi.fn(),
|
||||
@@ -30,6 +30,22 @@ function createDeferred<T>(): Deferred<T> {
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
/**
|
||||
* Stubs the gateway API by request path. Every path the page fetches must be
|
||||
* registered explicitly, so a new unmocked fetch fails loudly instead of
|
||||
* silently resolving to undefined.
|
||||
*/
|
||||
function mockApiByPath(handlers: Record<string, unknown>): void {
|
||||
apiMock.mockImplementation((path: string) => {
|
||||
if (!(path in handlers)) {
|
||||
throw new Error(`No API mock registered for ${path}`);
|
||||
}
|
||||
const response = handlers[path];
|
||||
if (response instanceof Error) return Promise.reject(response);
|
||||
return Promise.resolve(response);
|
||||
});
|
||||
}
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
@@ -71,10 +87,25 @@ async function renderProjectsPage(): Promise<ReturnType<typeof createMemoryRoute
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value a StatCard renders under the given label. Asserting the
|
||||
* label-to-value pairing (instead of a bare substring of page text) ensures
|
||||
* each stat's assertion can only be satisfied by that stat's own element.
|
||||
*/
|
||||
function statValue(label: string): string | null {
|
||||
const labelElement = [...container.querySelectorAll('p')].find(
|
||||
(element) => element.textContent === label,
|
||||
);
|
||||
return labelElement?.nextElementSibling?.textContent ?? null;
|
||||
}
|
||||
|
||||
describe('ProjectsPage', () => {
|
||||
it('shows a visible loading state while the project request is in flight', async () => {
|
||||
const deferred = createDeferred<typeof projectFixtures>();
|
||||
apiMock.mockReturnValueOnce(deferred.promise);
|
||||
mockApiByPath({
|
||||
'/api/projects': deferred.promise,
|
||||
'/api/coord/status': coordMissionStatusFixture,
|
||||
});
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
@@ -87,7 +118,10 @@ describe('ProjectsPage', () => {
|
||||
});
|
||||
|
||||
it('renders project cards from the API and navigates to a project detail route on click', async () => {
|
||||
apiMock.mockResolvedValueOnce(projectFixtures);
|
||||
mockApiByPath({
|
||||
'/api/projects': projectFixtures,
|
||||
'/api/coord/status': coordMissionStatusFixture,
|
||||
});
|
||||
|
||||
const router = await renderProjectsPage();
|
||||
|
||||
@@ -109,7 +143,10 @@ describe('ProjectsPage', () => {
|
||||
});
|
||||
|
||||
it('renders the empty state when the API returns no projects', async () => {
|
||||
apiMock.mockResolvedValueOnce([]);
|
||||
mockApiByPath({
|
||||
'/api/projects': [],
|
||||
'/api/coord/status': coordMissionStatusFixture,
|
||||
});
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
@@ -120,7 +157,10 @@ describe('ProjectsPage', () => {
|
||||
});
|
||||
|
||||
it('renders a visible alert when the projects request fails', async () => {
|
||||
apiMock.mockRejectedValueOnce(new Error('Projects are unavailable'));
|
||||
mockApiByPath({
|
||||
'/api/projects': new Error('Projects are unavailable'),
|
||||
'/api/coord/status': coordMissionStatusFixture,
|
||||
});
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
@@ -128,4 +168,117 @@ describe('ProjectsPage', () => {
|
||||
expect(alert).toBeTruthy();
|
||||
expect(alert?.textContent).toContain('Projects are unavailable');
|
||||
});
|
||||
|
||||
describe('active mission section', () => {
|
||||
it('renders the active mission summary from the coord status endpoint below the project grid', async () => {
|
||||
mockApiByPath({
|
||||
'/api/projects': projectFixtures,
|
||||
'/api/coord/status': coordMissionStatusFixture,
|
||||
});
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
expect(apiMock).toHaveBeenCalledWith('/api/coord/status');
|
||||
expect(container.textContent).toContain('Active Mission');
|
||||
|
||||
const pageText = container.textContent ?? '';
|
||||
const gridEnd = pageText.indexOf('Agent Runtime');
|
||||
const sectionStart = pageText.indexOf('Active Mission');
|
||||
expect(gridEnd).toBeGreaterThanOrEqual(0);
|
||||
expect(sectionStart).toBeGreaterThan(gridEnd);
|
||||
|
||||
expect(pageText).toContain('coord-mission-1');
|
||||
expect(pageText).toContain('Static serving');
|
||||
expect(pageText).toContain('3 / 7');
|
||||
expect(pageText).toContain('active');
|
||||
|
||||
expect(statValue('Mission')).toBe('coord-mission-1');
|
||||
expect(statValue('Phase')).toBe('Static serving');
|
||||
expect(statValue('Tasks')).toBe('3 / 7');
|
||||
expect(statValue('Status')).toBe('active');
|
||||
});
|
||||
|
||||
it('shows a mission loading state while the coord status request is in flight', async () => {
|
||||
const deferred = createDeferred<typeof coordMissionStatusFixture>();
|
||||
mockApiByPath({
|
||||
'/api/projects': projectFixtures,
|
||||
'/api/coord/status': deferred.promise,
|
||||
});
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
expect(container.textContent).toContain('Loading mission status...');
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve(coordMissionStatusFixture);
|
||||
await deferred.promise;
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain('coord-mission-1');
|
||||
});
|
||||
|
||||
it('shows the no-active-mission state when the gateway reports no coord mission', async () => {
|
||||
mockApiByPath({
|
||||
'/api/projects': projectFixtures,
|
||||
'/api/coord/status': Object.assign(new Error('No active coord mission found'), {
|
||||
statusCode: 404,
|
||||
}),
|
||||
});
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
expect(container.textContent).toContain('No active mission detected');
|
||||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('surfaces a visible alert when the coord status request fails', async () => {
|
||||
mockApiByPath({
|
||||
'/api/projects': projectFixtures,
|
||||
'/api/coord/status': new Error('Mission status unavailable'),
|
||||
});
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
const alert = container.querySelector('[role="alert"]');
|
||||
expect(alert).toBeTruthy();
|
||||
expect(alert?.textContent).toContain('Mission status unavailable');
|
||||
});
|
||||
|
||||
it('keeps the project grid rendered when the coord status request fails', async () => {
|
||||
mockApiByPath({
|
||||
'/api/projects': projectFixtures,
|
||||
'/api/coord/status': new Error('Mission status unavailable'),
|
||||
});
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
expect(container.textContent).toContain('Mosaic Stack');
|
||||
expect(container.textContent).toContain('Agent Runtime');
|
||||
|
||||
const alert = container.querySelector('[role="alert"]');
|
||||
expect(alert?.textContent).toContain('Mission status unavailable');
|
||||
});
|
||||
|
||||
it('renders a mission alert and keeps the project grid when a 200 returns JSON of the wrong shape', async () => {
|
||||
mockApiByPath({
|
||||
'/api/projects': projectFixtures,
|
||||
'/api/coord/status': {
|
||||
mission: { id: 42, status: 'active' },
|
||||
milestones: { total: 4, completed: 1 },
|
||||
tasks: { total: 'seven', done: 3 },
|
||||
},
|
||||
});
|
||||
|
||||
await renderProjectsPage();
|
||||
|
||||
const alert = container.querySelector('[role="alert"]');
|
||||
expect(alert).toBeTruthy();
|
||||
expect(alert?.textContent).toContain('malformed');
|
||||
|
||||
expect(container.textContent).not.toContain('No active mission detected');
|
||||
|
||||
expect(container.textContent).toContain('Mosaic Stack');
|
||||
expect(container.textContent).toContain('Agent Runtime');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,141 @@ import { api } from '@/lib/api';
|
||||
import type { Project } from '@/lib/types';
|
||||
import { getErrorMessage } from './page-errors';
|
||||
|
||||
export interface CoordMissionStatus {
|
||||
mission: {
|
||||
id: string;
|
||||
name: string;
|
||||
status: string;
|
||||
projectPath: string;
|
||||
};
|
||||
milestones: {
|
||||
total: number;
|
||||
completed: number;
|
||||
current?: {
|
||||
id: string;
|
||||
name: string;
|
||||
status: string;
|
||||
};
|
||||
};
|
||||
tasks: {
|
||||
total: number;
|
||||
done: number;
|
||||
inProgress: number;
|
||||
pending: number;
|
||||
blocked: number;
|
||||
cancelled: number;
|
||||
};
|
||||
nextTaskId?: string;
|
||||
}
|
||||
|
||||
function isNoMissionResponse(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
(error as { statusCode?: unknown }).statusCode === 404
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow runtime shape check for the /api/coord/status payload. `api()` casts
|
||||
* the JSON body without validation, so a 200 carrying parseable JSON of the
|
||||
* wrong shape would otherwise throw during render and take the whole route
|
||||
* (grid included) down via the route error boundary. Only the levels the page
|
||||
* actually dereferences are checked; `milestones.current` is optional per the
|
||||
* contract and is already handled with `?.` at the render site.
|
||||
*/
|
||||
function isCoordMissionStatus(payload: unknown): payload is CoordMissionStatus {
|
||||
if (typeof payload !== 'object' || payload === null) return false;
|
||||
const { mission, milestones, tasks } = payload as {
|
||||
mission?: unknown;
|
||||
milestones?: unknown;
|
||||
tasks?: unknown;
|
||||
};
|
||||
return (
|
||||
typeof mission === 'object' &&
|
||||
mission !== null &&
|
||||
typeof (mission as { id?: unknown }).id === 'string' &&
|
||||
typeof (mission as { status?: unknown }).status === 'string' &&
|
||||
typeof milestones === 'object' &&
|
||||
milestones !== null &&
|
||||
typeof tasks === 'object' &&
|
||||
tasks !== null &&
|
||||
typeof (tasks as { done?: unknown }).done === 'number' &&
|
||||
typeof (tasks as { total?: unknown }).total === 'number'
|
||||
);
|
||||
}
|
||||
|
||||
function MissionStatus(): ReactElement {
|
||||
const [mission, setMission] = useState<CoordMissionStatus | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
void api<CoordMissionStatus>('/api/coord/status')
|
||||
.then((response) => {
|
||||
if (cancelled) return;
|
||||
if (!isCoordMissionStatus(response)) {
|
||||
setError('Mission status response was malformed.');
|
||||
return;
|
||||
}
|
||||
setMission(response);
|
||||
})
|
||||
.catch((caught: unknown) => {
|
||||
if (cancelled) return;
|
||||
if (isNoMissionResponse(caught)) {
|
||||
setMission(null);
|
||||
return;
|
||||
}
|
||||
setError(getErrorMessage(caught, 'Failed to load mission status.'));
|
||||
})
|
||||
.finally(() => {
|
||||
if (cancelled) return;
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<section className="mt-8">
|
||||
<h2 className="mb-4 text-lg font-semibold">Active Mission</h2>
|
||||
{loading ? (
|
||||
<p className="text-sm text-text-muted">Loading mission status...</p>
|
||||
) : error ? (
|
||||
<div role="alert" className="rounded-lg border border-error/40 px-4 py-3 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
) : !mission ? (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-6 text-center">
|
||||
<p className="text-sm text-text-muted">No active mission detected</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<StatCard label="Mission" value={mission.mission.id} />
|
||||
<StatCard label="Phase" value={mission.milestones.current?.name ?? '—'} />
|
||||
<StatCard label="Tasks" value={`${mission.tasks.done} / ${mission.tasks.total}`} />
|
||||
<StatCard label="Status" value={mission.mission.status} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function StatCard({ label, value }: { label: string; value: string }): ReactElement {
|
||||
return (
|
||||
<div className="rounded-lg bg-surface-elevated p-3">
|
||||
<p className="text-xs text-text-muted">{label}</p>
|
||||
<p className="mt-1 text-sm font-medium text-text-primary">{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProjectsPage(): ReactElement {
|
||||
const navigate = useNavigate();
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
@@ -65,6 +200,8 @@ export function ProjectsPage(): ReactElement {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<MissionStatus />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ vi.mock('@/lib/auth-client', () => ({
|
||||
}));
|
||||
|
||||
import { routes } from '@/routes';
|
||||
import { ThemeProvider } from '@/providers/theme-provider';
|
||||
|
||||
function Boom(): never {
|
||||
throw new Error('resource route render blew up');
|
||||
@@ -54,7 +55,7 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
describe('resource route error boundaries', () => {
|
||||
it.each(['/projects', '/projects/:id', '/tasks'])(
|
||||
it.each(['/projects', '/projects/:id', '/tasks', '/settings', '/admin'])(
|
||||
'renders a recoverable fallback when %s throws during route render',
|
||||
async (path) => {
|
||||
useSessionMock.mockReturnValue({ data: { user: { id: 'user-1' } }, isPending: false });
|
||||
@@ -71,7 +72,11 @@ describe('resource route error boundaries', () => {
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
try {
|
||||
await act(async () => {
|
||||
root?.render(<RouterProvider router={router} />);
|
||||
root?.render(
|
||||
<ThemeProvider>
|
||||
<RouterProvider router={router} />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalled();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ReactElement } from 'react';
|
||||
import { useRouteError } from 'react-router-dom';
|
||||
import { SPA_ROUTES } from '@mosaicstack/types';
|
||||
|
||||
interface ResourceRouteErrorBoundaryProps {
|
||||
message: string;
|
||||
@@ -28,7 +29,7 @@ export function ProjectsRouteErrorBoundary(): ReactElement {
|
||||
return (
|
||||
<ResourceRouteErrorBoundary
|
||||
message="Something went wrong loading projects."
|
||||
href="/projects"
|
||||
href={SPA_ROUTES.projects.path}
|
||||
linkLabel="Reload projects"
|
||||
/>
|
||||
);
|
||||
@@ -38,7 +39,7 @@ export function ProjectDetailRouteErrorBoundary(): ReactElement {
|
||||
return (
|
||||
<ResourceRouteErrorBoundary
|
||||
message="Something went wrong loading this project."
|
||||
href="/projects"
|
||||
href={SPA_ROUTES.projects.path}
|
||||
linkLabel="Back to projects"
|
||||
/>
|
||||
);
|
||||
@@ -48,8 +49,28 @@ export function TasksRouteErrorBoundary(): ReactElement {
|
||||
return (
|
||||
<ResourceRouteErrorBoundary
|
||||
message="Something went wrong loading tasks."
|
||||
href="/tasks"
|
||||
href={SPA_ROUTES.tasks.path}
|
||||
linkLabel="Reload tasks"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsRouteErrorBoundary(): ReactElement {
|
||||
return (
|
||||
<ResourceRouteErrorBoundary
|
||||
message="Something went wrong loading settings."
|
||||
href={SPA_ROUTES.settings.path}
|
||||
linkLabel="Reload settings"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function AdminRouteErrorBoundary(): ReactElement {
|
||||
return (
|
||||
<ResourceRouteErrorBoundary
|
||||
message="Something went wrong loading the admin panel."
|
||||
href={SPA_ROUTES.admin.path}
|
||||
linkLabel="Reload admin panel"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import { createMemoryRouter, RouterProvider, type RouteObject } from 'react-router-dom';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { SPA_ROUTES } from '@mosaicstack/types';
|
||||
|
||||
const { apiMock, useSessionMock, updateUserMock } = vi.hoisted(() => ({
|
||||
apiMock: vi.fn(),
|
||||
useSessionMock: vi.fn(),
|
||||
updateUserMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/api', () => ({
|
||||
api: apiMock,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/auth-client', () => ({
|
||||
authClient: { updateUser: updateUserMock },
|
||||
useSession: useSessionMock,
|
||||
}));
|
||||
|
||||
import { SettingsPage } from './settings';
|
||||
|
||||
const sessionFixture = {
|
||||
user: { id: 'user-1', name: 'Ada Lovelace', email: '[email protected]', image: null },
|
||||
};
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
document.body.replaceChildren();
|
||||
root = null;
|
||||
apiMock.mockReset();
|
||||
useSessionMock.mockReset();
|
||||
updateUserMock.mockReset();
|
||||
});
|
||||
|
||||
async function renderSettingsPage(): Promise<ReturnType<typeof createMemoryRouter>> {
|
||||
const routes: RouteObject[] = [
|
||||
{ path: SPA_ROUTES.settings.path, element: <SettingsPage /> },
|
||||
{ path: SPA_ROUTES.root.path, element: <p>Root</p> },
|
||||
];
|
||||
const router = createMemoryRouter(routes, { initialEntries: [SPA_ROUTES.settings.path] });
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(<RouterProvider router={router} />);
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
function clickButtonByText(text: string): void {
|
||||
const button = [...container.querySelectorAll('button')].find((candidate) =>
|
||||
candidate.textContent?.includes(text),
|
||||
);
|
||||
if (!button) {
|
||||
throw new Error(`Button containing "${text}" not found`);
|
||||
}
|
||||
button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
}
|
||||
|
||||
describe('SettingsPage', () => {
|
||||
it('renders the profile tab from the session and saves edits through authClient.updateUser', async () => {
|
||||
useSessionMock.mockReturnValue({ data: sessionFixture });
|
||||
updateUserMock.mockResolvedValue({ data: { user: sessionFixture.user }, error: null });
|
||||
|
||||
await renderSettingsPage();
|
||||
|
||||
expect(apiMock).not.toHaveBeenCalled();
|
||||
|
||||
const nameInput = container.querySelector<HTMLInputElement>('#profile-name');
|
||||
expect(nameInput?.value).toBe('Ada Lovelace');
|
||||
|
||||
const emailInput = container.querySelector<HTMLInputElement>('#profile-email');
|
||||
expect(emailInput?.value).toBe('[email protected]');
|
||||
expect(emailInput?.disabled).toBe(true);
|
||||
|
||||
// React's controlled inputs ignore synthetic values assigned directly, so the
|
||||
// native value setter must run before dispatching the input event.
|
||||
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
|
||||
window.HTMLInputElement.prototype,
|
||||
'value',
|
||||
)?.set;
|
||||
nativeInputValueSetter?.call(nameInput, 'Ada K.');
|
||||
|
||||
await act(async () => {
|
||||
nameInput?.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Save changes');
|
||||
});
|
||||
|
||||
expect(updateUserMock).toHaveBeenCalledWith({ name: 'Ada K.', image: null });
|
||||
expect(container.textContent).toContain('Saved!');
|
||||
});
|
||||
|
||||
it('surfaces a profile save failure from authClient.updateUser as a visible message', async () => {
|
||||
useSessionMock.mockReturnValue({ data: sessionFixture });
|
||||
updateUserMock.mockResolvedValue({
|
||||
data: null,
|
||||
error: { message: 'Profile update rejected' },
|
||||
});
|
||||
|
||||
await renderSettingsPage();
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Save changes');
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain('Profile update rejected');
|
||||
});
|
||||
|
||||
it('loads appearance preferences, reflects the stored theme, and saves them back', async () => {
|
||||
useSessionMock.mockReturnValue({ data: sessionFixture });
|
||||
apiMock.mockImplementation((path: string) => {
|
||||
if (typeof path === 'string' && path.startsWith('/api/memory/preferences?')) {
|
||||
return Promise.resolve([
|
||||
{ key: 'ui.theme', value: 'dark', category: 'appearance' },
|
||||
{ key: 'ui.sidebar_collapsed', value: true, category: 'appearance' },
|
||||
{ key: 'ui.default_model', value: 'ollama/llama3.2', category: 'appearance' },
|
||||
]);
|
||||
}
|
||||
return Promise.resolve([]);
|
||||
});
|
||||
|
||||
await renderSettingsPage();
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Appearance');
|
||||
});
|
||||
|
||||
expect(
|
||||
apiMock.mock.calls.find(([path]) => path === '/api/memory/preferences?category=appearance'),
|
||||
).toBeTruthy();
|
||||
|
||||
expect(container.querySelector('[role="switch"]')?.getAttribute('aria-checked')).toBe('true');
|
||||
expect(container.querySelector<HTMLInputElement>('#default-model')?.value).toBe(
|
||||
'ollama/llama3.2',
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Save changes');
|
||||
});
|
||||
|
||||
const preferencePosts = apiMock.mock.calls
|
||||
.filter(([path]) => path === '/api/memory/preferences')
|
||||
.map(([, init]) => init);
|
||||
expect(preferencePosts.map((init) => init?.body.key)).toEqual([
|
||||
'ui.theme',
|
||||
'ui.sidebar_collapsed',
|
||||
'ui.default_model',
|
||||
]);
|
||||
expect(preferencePosts.every((init) => init?.method === 'POST')).toBe(true);
|
||||
|
||||
expect(container.textContent).toContain('Saved!');
|
||||
});
|
||||
|
||||
it('loads notification preferences, toggles one, and saves all three keys', async () => {
|
||||
useSessionMock.mockReturnValue({ data: sessionFixture });
|
||||
apiMock.mockImplementation((path: string) => {
|
||||
if (typeof path === 'string' && path.startsWith('/api/memory/preferences?')) {
|
||||
return Promise.resolve([
|
||||
{ key: 'notify.email_agent_complete', value: false, category: 'communication' },
|
||||
{ key: 'notify.email_mentions', value: true, category: 'communication' },
|
||||
{ key: 'notify.email_digest', value: false, category: 'communication' },
|
||||
]);
|
||||
}
|
||||
return Promise.resolve([]);
|
||||
});
|
||||
|
||||
await renderSettingsPage();
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Notifications');
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain('Agent task completed');
|
||||
|
||||
const agentCompleteSwitch = [...container.querySelectorAll('[role="switch"]')][0];
|
||||
expect(agentCompleteSwitch?.getAttribute('aria-checked')).toBe('false');
|
||||
|
||||
await act(async () => {
|
||||
agentCompleteSwitch?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
expect(agentCompleteSwitch?.getAttribute('aria-checked')).toBe('true');
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Save changes');
|
||||
});
|
||||
|
||||
const savedValues = Object.fromEntries(
|
||||
apiMock.mock.calls
|
||||
.filter(([path]) => path === '/api/memory/preferences')
|
||||
.map(([, init]) => [init?.body.key, init?.body.value]),
|
||||
);
|
||||
expect(savedValues).toEqual({
|
||||
'notify.email_agent_complete': true,
|
||||
'notify.email_mentions': true,
|
||||
'notify.email_digest': false,
|
||||
});
|
||||
});
|
||||
|
||||
it('renders SSO and LLM providers, expands models, and tests a provider connection', async () => {
|
||||
useSessionMock.mockReturnValue({ data: sessionFixture });
|
||||
apiMock.mockImplementation((path: string) => {
|
||||
if (path === '/api/sso/providers') {
|
||||
return Promise.resolve([
|
||||
{
|
||||
id: 'authentik',
|
||||
name: 'Authentik',
|
||||
protocols: ['oidc'],
|
||||
configured: true,
|
||||
loginMode: 'oidc',
|
||||
callbackPath: '/api/auth/oauth2/callback/authentik',
|
||||
teamSync: { enabled: false, claim: null },
|
||||
samlFallback: { configured: false, loginUrl: null },
|
||||
warnings: [],
|
||||
},
|
||||
]);
|
||||
}
|
||||
if (path === '/api/providers') {
|
||||
return Promise.resolve([
|
||||
{
|
||||
id: 'ollama',
|
||||
name: 'Ollama',
|
||||
available: true,
|
||||
models: [
|
||||
{
|
||||
id: 'llama3.2',
|
||||
provider: 'ollama',
|
||||
name: 'Llama 3.2',
|
||||
reasoning: false,
|
||||
contextWindow: 131_072,
|
||||
maxTokens: 4_096,
|
||||
inputTypes: ['text' as const],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
}
|
||||
if (path === '/api/providers/test') {
|
||||
return Promise.resolve({
|
||||
providerId: 'ollama',
|
||||
reachable: true,
|
||||
latencyMs: 42,
|
||||
discoveredModels: ['llama3.2', 'qwen2.5'],
|
||||
});
|
||||
}
|
||||
return Promise.resolve([]);
|
||||
});
|
||||
|
||||
await renderSettingsPage();
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Providers');
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain('SSO Providers');
|
||||
expect(container.textContent).toContain('Authentik');
|
||||
expect(container.textContent).toContain('Enabled');
|
||||
|
||||
expect(container.textContent).toContain('Ollama');
|
||||
expect(container.textContent).toContain('1 model');
|
||||
expect(container.querySelector('table')).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('▼ Models');
|
||||
});
|
||||
|
||||
expect(container.querySelector('table')?.textContent).toContain('Llama 3.2');
|
||||
expect(container.querySelector('table')?.textContent).toContain('131k');
|
||||
expect(container.querySelector('table')?.textContent).toContain('default');
|
||||
|
||||
await act(async () => {
|
||||
clickButtonByText('Test');
|
||||
});
|
||||
|
||||
expect(apiMock.mock.calls.find(([path]) => path === '/api/providers/test')?.[1]).toEqual({
|
||||
method: 'POST',
|
||||
body: { providerId: 'ollama' },
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain('✓ Reachable');
|
||||
expect(container.textContent).toContain('Connected');
|
||||
expect(container.textContent).toContain('(42ms)');
|
||||
expect(container.textContent).toContain('2 models discovered');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,820 @@
|
||||
import { useCallback, useEffect, useState, type ReactElement, type ReactNode } from 'react';
|
||||
import { api } from '@/lib/api';
|
||||
import { authClient, useSession } from '@/lib/auth-client';
|
||||
import type { SsoProviderDiscovery } from '@/lib/sso';
|
||||
import { SsoProviderSection } from '@/components/settings/sso-provider-section';
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface ModelInfo {
|
||||
id: string;
|
||||
provider: string;
|
||||
name: string;
|
||||
reasoning: boolean;
|
||||
contextWindow: number;
|
||||
maxTokens: number;
|
||||
inputTypes: ('text' | 'image')[];
|
||||
cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
|
||||
}
|
||||
|
||||
interface ProviderInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
available: boolean;
|
||||
models: ModelInfo[];
|
||||
}
|
||||
|
||||
interface TestConnectionResult {
|
||||
providerId: string;
|
||||
reachable: boolean;
|
||||
latencyMs?: number;
|
||||
error?: string;
|
||||
discoveredModels?: string[];
|
||||
}
|
||||
|
||||
type TestState = 'idle' | 'testing' | 'success' | 'error';
|
||||
|
||||
interface ProviderTestStatus {
|
||||
state: TestState;
|
||||
result?: TestConnectionResult;
|
||||
}
|
||||
|
||||
interface Preference {
|
||||
key: string;
|
||||
value: unknown;
|
||||
category: string;
|
||||
}
|
||||
|
||||
type Theme = 'light' | 'dark' | 'system';
|
||||
type SaveState = 'idle' | 'saving' | 'saved' | 'error';
|
||||
type Tab = 'profile' | 'appearance' | 'notifications' | 'providers';
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function prefValue<T>(prefs: Preference[], key: string, fallback: T): T {
|
||||
const p = prefs.find((x) => x.key === key);
|
||||
if (p === undefined) return fallback;
|
||||
return p.value as T;
|
||||
}
|
||||
|
||||
// ─── Main Page ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function SettingsPage(): ReactElement {
|
||||
const { data: session } = useSession();
|
||||
const [activeTab, setActiveTab] = useState<Tab>('profile');
|
||||
|
||||
const tabs: { id: Tab; label: string }[] = [
|
||||
{ id: 'profile', label: 'Profile' },
|
||||
{ id: 'appearance', label: 'Appearance' },
|
||||
{ id: 'notifications', label: 'Notifications' },
|
||||
{ id: 'providers', label: 'Providers' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl space-y-6">
|
||||
<h1 className="text-2xl font-semibold">Settings</h1>
|
||||
|
||||
{/* Tab bar */}
|
||||
<div className="flex gap-1 border-b border-surface-border">
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
type="button"
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`px-4 py-2 text-sm font-medium transition-colors ${
|
||||
activeTab === tab.id
|
||||
? 'border-b-2 border-accent text-accent'
|
||||
: 'text-text-secondary hover:text-text-primary'
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{activeTab === 'profile' && <ProfileTab session={session} />}
|
||||
{activeTab === 'appearance' && <AppearanceTab />}
|
||||
{activeTab === 'notifications' && <NotificationsTab />}
|
||||
{activeTab === 'providers' && <ProvidersTab />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Profile Tab ──────────────────────────────────────────────────────────────
|
||||
|
||||
function ProfileTab({
|
||||
session,
|
||||
}: {
|
||||
session: { user: { id: string; name: string; email: string; image?: string | null } } | null;
|
||||
}): ReactElement {
|
||||
const [name, setName] = useState(session?.user.name ?? '');
|
||||
const [image, setImage] = useState(session?.user.image ?? '');
|
||||
const [saveState, setSaveState] = useState<SaveState>('idle');
|
||||
const [errorMsg, setErrorMsg] = useState('');
|
||||
|
||||
// Sync from session when it loads
|
||||
useEffect(() => {
|
||||
if (session?.user) {
|
||||
setName(session.user.name ?? '');
|
||||
setImage(session.user.image ?? '');
|
||||
}
|
||||
}, [session]);
|
||||
|
||||
const handleSave = async (): Promise<void> => {
|
||||
setSaveState('saving');
|
||||
setErrorMsg('');
|
||||
try {
|
||||
const result = await authClient.updateUser({ name, image: image || null });
|
||||
if (result.error) {
|
||||
setErrorMsg(result.error.message ?? 'Failed to update profile');
|
||||
setSaveState('error');
|
||||
return;
|
||||
}
|
||||
setSaveState('saved');
|
||||
setTimeout(() => setSaveState('idle'), 2000);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to update profile';
|
||||
setErrorMsg(message);
|
||||
setSaveState('error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-lg font-medium text-text-secondary">Profile</h2>
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-6 space-y-4">
|
||||
<FormField label="Display Name" id="profile-name">
|
||||
<input
|
||||
id="profile-name"
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Your name"
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="Email" id="profile-email">
|
||||
<input
|
||||
id="profile-email"
|
||||
type="email"
|
||||
value={session?.user.email ?? ''}
|
||||
disabled
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-muted opacity-60 cursor-not-allowed"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-text-muted">Email cannot be changed here.</p>
|
||||
</FormField>
|
||||
|
||||
<FormField label="Avatar URL" id="profile-image">
|
||||
<input
|
||||
id="profile-image"
|
||||
type="url"
|
||||
value={image}
|
||||
onChange={(e) => setImage(e.target.value)}
|
||||
placeholder="https://example.com/avatar.png"
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
<SaveButton state={saveState} onClick={handleSave} />
|
||||
{saveState === 'error' && errorMsg && <p className="text-sm text-error">{errorMsg}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Appearance Tab ───────────────────────────────────────────────────────────
|
||||
|
||||
function AppearanceTab(): ReactElement {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [theme, setTheme] = useState<Theme>('system');
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
||||
const [defaultModel, setDefaultModel] = useState('');
|
||||
const [saveState, setSaveState] = useState<SaveState>('idle');
|
||||
const [errorMsg, setErrorMsg] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
api<Preference[]>('/api/memory/preferences?category=appearance')
|
||||
.catch(() => [] as Preference[])
|
||||
.then((p) => {
|
||||
setTheme(prefValue<Theme>(p, 'ui.theme', 'system'));
|
||||
setSidebarCollapsed(prefValue<boolean>(p, 'ui.sidebar_collapsed', false));
|
||||
setDefaultModel(prefValue<string>(p, 'ui.default_model', ''));
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const handleSave = async (): Promise<void> => {
|
||||
setSaveState('saving');
|
||||
setErrorMsg('');
|
||||
try {
|
||||
await Promise.all([
|
||||
api('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: { key: 'ui.theme', value: theme, category: 'appearance', source: 'user' },
|
||||
}),
|
||||
api('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
key: 'ui.sidebar_collapsed',
|
||||
value: sidebarCollapsed,
|
||||
category: 'appearance',
|
||||
source: 'user',
|
||||
},
|
||||
}),
|
||||
...(defaultModel
|
||||
? [
|
||||
api('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
key: 'ui.default_model',
|
||||
value: defaultModel,
|
||||
category: 'appearance',
|
||||
source: 'user',
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
setSaveState('saved');
|
||||
setTimeout(() => setSaveState('idle'), 2000);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to save preferences';
|
||||
setErrorMsg(message);
|
||||
setSaveState('error');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<section>
|
||||
<h2 className="mb-4 text-lg font-medium text-text-secondary">Appearance</h2>
|
||||
<p className="text-sm text-text-muted">Loading preferences...</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-lg font-medium text-text-secondary">Appearance</h2>
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-6 space-y-6">
|
||||
{/* Theme */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-primary mb-2">Theme</label>
|
||||
<div className="flex gap-3">
|
||||
{(['system', 'light', 'dark'] as Theme[]).map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
onClick={() => setTheme(t)}
|
||||
className={`rounded-lg border px-4 py-2 text-sm capitalize transition-colors ${
|
||||
theme === t
|
||||
? 'border-accent bg-accent/10 text-accent'
|
||||
: 'border-surface-border bg-surface-elevated text-text-secondary hover:border-accent/50'
|
||||
}`}
|
||||
>
|
||||
{t}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sidebar collapsed default */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-text-primary">Collapse sidebar by default</p>
|
||||
<p className="text-xs text-text-muted">Start with sidebar collapsed on page load</p>
|
||||
</div>
|
||||
<Toggle checked={sidebarCollapsed} onChange={setSidebarCollapsed} />
|
||||
</div>
|
||||
|
||||
{/* Default model */}
|
||||
<FormField label="Default Model" id="default-model">
|
||||
<input
|
||||
id="default-model"
|
||||
type="text"
|
||||
value={defaultModel}
|
||||
onChange={(e) => setDefaultModel(e.target.value)}
|
||||
placeholder="e.g. ollama/llama3.2"
|
||||
className="mt-1 block w-full rounded-lg border border-surface-border bg-surface-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-text-muted">
|
||||
Model ID to pre-select for new conversations.
|
||||
</p>
|
||||
</FormField>
|
||||
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
<SaveButton state={saveState} onClick={handleSave} />
|
||||
{saveState === 'error' && errorMsg && <p className="text-sm text-error">{errorMsg}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Notifications Tab ────────────────────────────────────────────────────────
|
||||
|
||||
function NotificationsTab(): ReactElement {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [emailAgentComplete, setEmailAgentComplete] = useState(false);
|
||||
const [emailMentions, setEmailMentions] = useState(true);
|
||||
const [emailDigest, setEmailDigest] = useState(false);
|
||||
const [saveState, setSaveState] = useState<SaveState>('idle');
|
||||
const [errorMsg, setErrorMsg] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
api<Preference[]>('/api/memory/preferences?category=communication')
|
||||
.catch(() => [] as Preference[])
|
||||
.then((p) => {
|
||||
setEmailAgentComplete(prefValue<boolean>(p, 'notify.email_agent_complete', false));
|
||||
setEmailMentions(prefValue<boolean>(p, 'notify.email_mentions', true));
|
||||
setEmailDigest(prefValue<boolean>(p, 'notify.email_digest', false));
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const handleSave = async (): Promise<void> => {
|
||||
setSaveState('saving');
|
||||
setErrorMsg('');
|
||||
try {
|
||||
await Promise.all([
|
||||
api('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
key: 'notify.email_agent_complete',
|
||||
value: emailAgentComplete,
|
||||
category: 'communication',
|
||||
source: 'user',
|
||||
},
|
||||
}),
|
||||
api('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
key: 'notify.email_mentions',
|
||||
value: emailMentions,
|
||||
category: 'communication',
|
||||
source: 'user',
|
||||
},
|
||||
}),
|
||||
api('/api/memory/preferences', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
key: 'notify.email_digest',
|
||||
value: emailDigest,
|
||||
category: 'communication',
|
||||
source: 'user',
|
||||
},
|
||||
}),
|
||||
]);
|
||||
setSaveState('saved');
|
||||
setTimeout(() => setSaveState('idle'), 2000);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to save preferences';
|
||||
setErrorMsg(message);
|
||||
setSaveState('error');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<section>
|
||||
<h2 className="mb-4 text-lg font-medium text-text-secondary">Notifications</h2>
|
||||
<p className="text-sm text-text-muted">Loading preferences...</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-lg font-medium text-text-secondary">Notifications</h2>
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-6 space-y-6">
|
||||
<p className="text-xs text-text-muted">Configure when you receive email notifications.</p>
|
||||
|
||||
<NotifyRow
|
||||
label="Agent task completed"
|
||||
description="Email when an agent finishes a task"
|
||||
checked={emailAgentComplete}
|
||||
onChange={setEmailAgentComplete}
|
||||
/>
|
||||
<NotifyRow
|
||||
label="Mentions"
|
||||
description="Email when you are mentioned in a conversation"
|
||||
checked={emailMentions}
|
||||
onChange={setEmailMentions}
|
||||
/>
|
||||
<NotifyRow
|
||||
label="Weekly digest"
|
||||
description="Weekly summary of activity"
|
||||
checked={emailDigest}
|
||||
onChange={setEmailDigest}
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
<SaveButton state={saveState} onClick={handleSave} />
|
||||
{saveState === 'error' && errorMsg && <p className="text-sm text-error">{errorMsg}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Providers Tab ────────────────────────────────────────────────────────────
|
||||
|
||||
function ProvidersTab(): ReactElement {
|
||||
const [providers, setProviders] = useState<ProviderInfo[]>([]);
|
||||
const [ssoProviders, setSsoProviders] = useState<SsoProviderDiscovery[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [ssoLoading, setSsoLoading] = useState(true);
|
||||
const [testStatuses, setTestStatuses] = useState<Record<string, ProviderTestStatus>>({});
|
||||
|
||||
useEffect(() => {
|
||||
api<ProviderInfo[]>('/api/providers')
|
||||
.catch(() => [] as ProviderInfo[])
|
||||
.then((p) => setProviders(p))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
api<SsoProviderDiscovery[]>('/api/sso/providers')
|
||||
.catch(() => [] as SsoProviderDiscovery[])
|
||||
.then((providers) => setSsoProviders(providers))
|
||||
.finally(() => setSsoLoading(false));
|
||||
}, []);
|
||||
|
||||
const testConnection = useCallback(async (providerId: string): Promise<void> => {
|
||||
setTestStatuses((prev) => ({
|
||||
...prev,
|
||||
[providerId]: { state: 'testing' },
|
||||
}));
|
||||
try {
|
||||
const result = await api<TestConnectionResult>('/api/providers/test', {
|
||||
method: 'POST',
|
||||
body: { providerId },
|
||||
});
|
||||
setTestStatuses((prev) => ({
|
||||
...prev,
|
||||
[providerId]: { state: result.reachable ? 'success' : 'error', result },
|
||||
}));
|
||||
} catch {
|
||||
setTestStatuses((prev) => ({
|
||||
...prev,
|
||||
[providerId]: {
|
||||
state: 'error',
|
||||
result: { providerId, reachable: false, error: 'Request failed' },
|
||||
},
|
||||
}));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const defaultModel: ModelInfo | undefined = providers
|
||||
.flatMap((p) => p.models)
|
||||
.find((m) => providers.find((p) => p.id === m.provider)?.available);
|
||||
|
||||
return (
|
||||
<section className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-lg font-medium text-text-secondary">SSO Providers</h2>
|
||||
<SsoProviderSection providers={ssoProviders} loading={ssoLoading} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-lg font-medium text-text-secondary">LLM Providers</h2>
|
||||
{loading ? (
|
||||
<p className="text-sm text-text-muted">Loading providers...</p>
|
||||
) : providers.length === 0 ? (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card p-4">
|
||||
<p className="text-sm text-text-muted">
|
||||
No providers configured. Set{' '}
|
||||
<code className="rounded bg-surface-elevated px-1 py-0.5 text-xs">
|
||||
OLLAMA_BASE_URL
|
||||
</code>{' '}
|
||||
or{' '}
|
||||
<code className="rounded bg-surface-elevated px-1 py-0.5 text-xs">
|
||||
MOSAIC_CUSTOM_PROVIDERS
|
||||
</code>{' '}
|
||||
to add providers.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{providers.map((provider) => (
|
||||
<ProviderCard
|
||||
key={provider.id}
|
||||
provider={provider}
|
||||
defaultModel={defaultModel}
|
||||
testStatus={testStatuses[provider.id] ?? { state: 'idle' }}
|
||||
onTest={() => void testConnection(provider.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Shared UI Components ─────────────────────────────────────────────────────
|
||||
|
||||
function FormField({
|
||||
label,
|
||||
id,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
id: string;
|
||||
children: ReactNode;
|
||||
}): ReactElement {
|
||||
return (
|
||||
<div>
|
||||
<label htmlFor={id} className="block text-sm font-medium text-text-primary">
|
||||
{label}
|
||||
</label>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Toggle({
|
||||
checked,
|
||||
onChange,
|
||||
}: {
|
||||
checked: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
}): ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={checked}
|
||||
onClick={() => onChange(!checked)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-accent focus:ring-offset-2 focus:ring-offset-surface-card ${
|
||||
checked ? 'bg-accent' : 'bg-surface-border'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
|
||||
checked ? 'translate-x-6' : 'translate-x-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function NotifyRow({
|
||||
label,
|
||||
description,
|
||||
checked,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
description: string;
|
||||
checked: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
}): ReactElement {
|
||||
return (
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-text-primary">{label}</p>
|
||||
<p className="text-xs text-text-muted">{description}</p>
|
||||
</div>
|
||||
<Toggle checked={checked} onChange={onChange} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SaveButton({ state, onClick }: { state: SaveState; onClick: () => void }): ReactElement {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={state === 'saving'}
|
||||
className="rounded-lg bg-accent px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{state === 'saving' ? 'Saving...' : state === 'saved' ? 'Saved!' : 'Save changes'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Provider Card (from original page) ──────────────────────────────────────
|
||||
|
||||
interface ProviderCardProps {
|
||||
provider: ProviderInfo;
|
||||
defaultModel: ModelInfo | undefined;
|
||||
testStatus: ProviderTestStatus;
|
||||
onTest: () => void;
|
||||
}
|
||||
|
||||
function ProviderCard({
|
||||
provider,
|
||||
defaultModel,
|
||||
testStatus,
|
||||
onTest,
|
||||
}: ProviderCardProps): ReactElement {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-surface-border bg-surface-card">
|
||||
{/* Header row */}
|
||||
<div className="flex items-center justify-between px-4 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<ProviderAvatar id={provider.id} />
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-text-primary">{provider.name}</span>
|
||||
<ProviderStatusBadge available={provider.available} />
|
||||
</div>
|
||||
<p className="text-xs text-text-muted">
|
||||
{provider.models.length} model{provider.models.length !== 1 ? 's' : ''}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<TestConnectionButton status={testStatus} onTest={onTest} />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpanded((v) => !v)}
|
||||
className="rounded px-2 py-1 text-xs text-text-muted transition-colors hover:bg-surface-elevated hover:text-text-primary"
|
||||
aria-expanded={expanded}
|
||||
aria-label={expanded ? 'Collapse models' : 'Expand models'}
|
||||
>
|
||||
{expanded ? '▲ Hide' : '▼ Models'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Test result banner */}
|
||||
{testStatus.state !== 'idle' && testStatus.state !== 'testing' && testStatus.result && (
|
||||
<TestResultBanner result={testStatus.result} />
|
||||
)}
|
||||
|
||||
{/* Model list */}
|
||||
{expanded && (
|
||||
<div className="border-t border-surface-border">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="bg-surface-elevated text-left text-xs text-text-muted">
|
||||
<th className="px-4 py-2 font-medium">Model</th>
|
||||
<th className="hidden px-4 py-2 font-medium md:table-cell">Capabilities</th>
|
||||
<th className="hidden px-4 py-2 font-medium md:table-cell">Context</th>
|
||||
<th className="hidden px-4 py-2 font-medium md:table-cell">Cost (in/out)</th>
|
||||
<th className="px-4 py-2 font-medium">Default</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{provider.models.map((model) => (
|
||||
<ModelRow
|
||||
key={model.id}
|
||||
model={model}
|
||||
isDefault={
|
||||
defaultModel?.id === model.id && defaultModel?.provider === model.provider
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ModelRowProps {
|
||||
model: ModelInfo;
|
||||
isDefault: boolean;
|
||||
}
|
||||
|
||||
function ModelRow({ model, isDefault }: ModelRowProps): ReactElement {
|
||||
return (
|
||||
<tr className="border-t border-surface-border">
|
||||
<td className="px-4 py-2">
|
||||
<span className="text-sm text-text-primary">{model.name}</span>
|
||||
</td>
|
||||
<td className="hidden px-4 py-2 md:table-cell">
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<CapabilityBadge label="chat" />
|
||||
{model.reasoning && <CapabilityBadge label="reasoning" color="purple" />}
|
||||
{model.inputTypes.includes('image') && <CapabilityBadge label="vision" color="blue" />}
|
||||
</div>
|
||||
</td>
|
||||
<td className="hidden px-4 py-2 text-xs text-text-muted md:table-cell">
|
||||
{formatContext(model.contextWindow)}
|
||||
</td>
|
||||
<td className="hidden px-4 py-2 text-xs text-text-muted md:table-cell">
|
||||
{model.cost.input === 0 && model.cost.output === 0
|
||||
? 'free'
|
||||
: `$${model.cost.input} / $${model.cost.output}`}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-center">
|
||||
{isDefault && (
|
||||
<span
|
||||
className="inline-block rounded-full bg-accent/20 px-2 py-0.5 text-xs font-medium text-accent"
|
||||
title="Default model used for new sessions"
|
||||
>
|
||||
default
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
function ProviderAvatar({ id }: { id: string }): ReactElement {
|
||||
const letter = id.charAt(0).toUpperCase();
|
||||
return (
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-surface-elevated text-sm font-semibold text-text-secondary">
|
||||
{letter}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProviderStatusBadge({ available }: { available: boolean }): ReactElement {
|
||||
return (
|
||||
<span
|
||||
className={`rounded-full px-2 py-0.5 text-xs font-medium ${
|
||||
available ? 'bg-success/20 text-success' : 'bg-surface-elevated text-text-muted'
|
||||
}`}
|
||||
>
|
||||
{available ? 'Active' : 'Inactive'}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
interface TestConnectionButtonProps {
|
||||
status: ProviderTestStatus;
|
||||
onTest: () => void;
|
||||
}
|
||||
|
||||
function TestConnectionButton({ status, onTest }: TestConnectionButtonProps): ReactElement {
|
||||
const isTesting = status.state === 'testing';
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onTest}
|
||||
disabled={isTesting}
|
||||
className="rounded px-2 py-1 text-xs transition-colors hover:bg-surface-elevated disabled:cursor-not-allowed disabled:opacity-50"
|
||||
title="Test connection"
|
||||
>
|
||||
{isTesting ? (
|
||||
<span className="text-text-muted">Testing…</span>
|
||||
) : status.state === 'success' ? (
|
||||
<span className="text-success">✓ Reachable</span>
|
||||
) : status.state === 'error' ? (
|
||||
<span className="text-error">✗ Unreachable</span>
|
||||
) : (
|
||||
<span className="text-text-muted">Test</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function TestResultBanner({ result }: { result: TestConnectionResult }): ReactElement {
|
||||
return (
|
||||
<div
|
||||
className={`px-4 py-2 text-xs ${
|
||||
result.reachable ? 'bg-success/10 text-success' : 'bg-error/10 text-error'
|
||||
}`}
|
||||
>
|
||||
{result.reachable ? (
|
||||
<>
|
||||
Connected
|
||||
{result.latencyMs !== undefined && (
|
||||
<span className="ml-1 opacity-70">({result.latencyMs}ms)</span>
|
||||
)}
|
||||
{result.discoveredModels && result.discoveredModels.length > 0 && (
|
||||
<span className="ml-2 opacity-70">
|
||||
— {result.discoveredModels.length} model
|
||||
{result.discoveredModels.length !== 1 ? 's' : ''} discovered
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>Connection failed{result.error ? `: ${result.error}` : ''}</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CapabilityBadge({
|
||||
label,
|
||||
color = 'default',
|
||||
}: {
|
||||
label: string;
|
||||
color?: 'default' | 'purple' | 'blue';
|
||||
}): ReactElement {
|
||||
const colorClass =
|
||||
color === 'purple'
|
||||
? 'bg-purple-500/20 text-purple-400'
|
||||
: color === 'blue'
|
||||
? 'bg-blue-500/20 text-blue-400'
|
||||
: 'bg-surface-elevated text-text-muted';
|
||||
return <span className={`rounded px-1.5 py-0.5 text-xs ${colorClass}`}>{label}</span>;
|
||||
}
|
||||
|
||||
function formatContext(tokens: number): string {
|
||||
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
|
||||
if (tokens >= 1_000) return `${Math.round(tokens / 1_000)}k`;
|
||||
return String(tokens);
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
import { isValidElement } from 'react';
|
||||
import { SPA_ROUTES } from '@mosaicstack/types';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { RouteObject } from 'react-router-dom';
|
||||
import { routes } from '@/routes';
|
||||
import { Placeholder } from '@/spa/placeholder';
|
||||
import { AdminPage } from '@/spa/pages/admin';
|
||||
import { ChatPage } from '@/spa/pages/chat';
|
||||
import { ProjectDetailPage } from '@/spa/pages/project-detail';
|
||||
import { ProjectsPage } from '@/spa/pages/projects';
|
||||
import { SettingsPage } from '@/spa/pages/settings';
|
||||
import { TasksPage } from '@/spa/pages/tasks';
|
||||
|
||||
function collectPaths(routeObjects: RouteObject[]): string[] {
|
||||
@@ -25,21 +28,9 @@ function findRoute(routeObjects: RouteObject[], path: string): RouteObject | und
|
||||
}
|
||||
|
||||
describe('SPA route table', () => {
|
||||
it('covers every v1 parity route from the Phase P RFC', () => {
|
||||
expect(collectPaths(routes).sort()).toEqual(
|
||||
[
|
||||
'/',
|
||||
'/admin',
|
||||
'/auth/provider/:provider',
|
||||
'/chat',
|
||||
'/login',
|
||||
'/projects',
|
||||
'/projects/:id',
|
||||
'/register',
|
||||
'/settings',
|
||||
'/tasks',
|
||||
].sort(),
|
||||
);
|
||||
it('implements every route in the shared Gateway fallback contract', () => {
|
||||
const contractedPaths = Object.values(SPA_ROUTES).map((route) => route.path);
|
||||
expect(collectPaths(routes).sort()).toEqual(contractedPaths.sort());
|
||||
});
|
||||
|
||||
it('separates guest and authenticated route groups', () => {
|
||||
@@ -75,6 +66,8 @@ describe('SPA route table', () => {
|
||||
['/projects', ProjectsPage],
|
||||
['/projects/:id', ProjectDetailPage],
|
||||
['/tasks', TasksPage],
|
||||
['/settings', SettingsPage],
|
||||
['/admin', AdminPage],
|
||||
])(
|
||||
'renders a real authenticated page instead of the P1 placeholder at %s',
|
||||
(path, expectedType) => {
|
||||
@@ -86,7 +79,7 @@ describe('SPA route table', () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.each(['/chat', '/projects', '/projects/:id', '/tasks'])(
|
||||
it.each(['/chat', '/projects', '/projects/:id', '/tasks', '/settings', '/admin'])(
|
||||
'defines an error boundary for %s',
|
||||
(path) => {
|
||||
const route = findRoute(routes, path);
|
||||
|
||||
@@ -21,3 +21,50 @@ for (const target of [globalThis, window]) {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// jsdom ships no matchMedia; the SPA shell components shared with the Next
|
||||
// baseline (SidebarProvider) need it to measure the mobile breakpoint. Default
|
||||
// to the desktop layout; specs exercising the mobile drawer install their own.
|
||||
if (typeof window.matchMedia !== 'function') {
|
||||
window.matchMedia = (query: string): MediaQueryList => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
addListener: () => {},
|
||||
removeListener: () => {},
|
||||
dispatchEvent: () => false,
|
||||
});
|
||||
}
|
||||
|
||||
// Measured under vitest's jsdom environment: `window.localStorage` is an own
|
||||
// ACCESSOR property (get + set, configurable, non-enumerable) whose getter
|
||||
// returns `undefined`; `globalThis.localStorage` likewise. A standalone
|
||||
// `new JSDOM('', { url })` does supply a real Storage, so a probe built that way
|
||||
// does not describe this environment. The SPA's ThemeProvider reads and writes
|
||||
// `mosaic-theme` on mount, so specs rendering it need a working store. Why the
|
||||
// getter returns undefined here is NOT measured — do not add a cause.
|
||||
if (window.localStorage === undefined) {
|
||||
const entries = new Map<string, string>();
|
||||
const memoryStorage: Storage = {
|
||||
get length() {
|
||||
return entries.size;
|
||||
},
|
||||
getItem: (key: string) => entries.get(String(key)) ?? null,
|
||||
setItem: (key: string, value: string) => void entries.set(String(key), String(value)),
|
||||
removeItem: (key: string) => void entries.delete(String(key)),
|
||||
clear: () => void entries.clear(),
|
||||
key: (index: number) => [...entries.keys()][index] ?? null,
|
||||
};
|
||||
|
||||
for (const target of [globalThis, window]) {
|
||||
if ((target as typeof globalThis).localStorage === undefined) {
|
||||
Object.defineProperty(target, 'localStorage', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: memoryStorage,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,11 @@ const gatewayTarget = 'http://localhost:14242';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
build: {
|
||||
// The gateway uses this provenance record, not filename heuristics, to
|
||||
// decide which Vite outputs are safe for immutable caching.
|
||||
manifest: true,
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
|
||||
Reference in new issue
Block a user