Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(console): global time-window selector + tenant switcher + role badge (W4+W5)

Beenu Arora6fbaead31a75
diff --git a/apps/web/src/components/layout/AppShell.tsx b/apps/web/src/components/layout/AppShell.tsx
index a962846e6..ab17b6b7c 100644
--- a/apps/web/src/components/layout/AppShell.tsx
+++ b/apps/web/src/components/layout/AppShell.tsx
@@ -4,6 +4,8 @@ import { SWRConfig } from 'swr';
import { Sidebar } from './Sidebar';
import { TopBar } from './TopBar';
import { CommandPalette } from './CommandPalette';
+import { TimeWindowProvider } from './TimeWindowProvider';
+import { TenantProvider } from './TenantProvider';
import { CopilotDock } from '@/components/copilot/CopilotDock';
import { DemoBanner } from '@/components/demo/DemoBanner';
import { DemoAutoLogin } from '@/components/demo/DemoAutoLogin';
@@ -37,7 +39,17 @@ export function AppShell({ children }: AppShellProps) {
No-ops outside demo mode.
*/}
<DemoAutoLogin />
- <div className="min-h-screen bg-surface-base">
+ {/*
+ v1.5 (W4 + W5): TimeWindow + Tenant contexts mount once at the shell
+ boundary so every page (and the TopBar) reads from the same source of
+ truth. They sit *inside* SWRConfig so the tenant switcher's
+ `aisoc:tenant-switched` cache-bust reaches the shared cache, and
+ *outside* the visible chrome so a context error doesn't blank the
+ entire app shell.
+ */}
+ <TimeWindowProvider>
+ <TenantProvider>
+ <div className="min-h-screen bg-surface-base">
{/*
DemoBanner reads `NEXT_PUBLIC_DEMO_MODE`, a build-time env var.
In development the client bundle can have a stale inlined value that
@@ -68,7 +80,9 @@ export function AppShell({ children }: AppShellProps) {
<ClientOnly>
<CommandPalette />
</ClientOnly>
- </div>
+ </div>
+ </TenantProvider>
+ </TimeWindowProvider>
</SWRConfig>
);
}
diff --git a/apps/web/src/components/layout/RoleBadge.test.tsx b/apps/web/src/components/layout/RoleBadge.test.tsx
new file mode 100644
index 000000000..af135b9f0
--- /dev/null
+++ b/apps/web/src/components/layout/RoleBadge.test.tsx
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { RoleBadge } from './RoleBadge';
+
+describe('RoleBadge', () => {
+ it('renders the canonical label for a known role', () => {
+ render(<RoleBadge role="admin" />);
+ expect(screen.getByText('Admin')).toBeInTheDocument();
+ });
+
+ it('matches role labels case-insensitively', () => {
+ render(<RoleBadge role="Analyst" />);
+ expect(screen.getByText('Analyst')).toBeInTheDocument();
+ });
+
+ it('falls back to "User" for unknown roles', () => {
+ render(<RoleBadge role="ops-ninja" />);
+ expect(screen.getByText('User')).toBeInTheDocument();
+ });
+
+ it('renders the fallback label when role is null', () => {
+ render(<RoleBadge role={null} />);
+ expect(screen.getByText('User')).toBeInTheDocument();
+ });
+
+ it('lets the caller override the visible label', () => {
+ render(<RoleBadge role="admin" label="Admin · Acme" />);
+ expect(screen.getByText('Admin · Acme')).toBeInTheDocument();
+ // The default "Admin" string should no longer be present.
+ expect(screen.queryByText('Admin')).not.toBeInTheDocument();
+ });
+
+ it('applies the tooltip via title attribute', () => {
+ render(<RoleBadge role="responder" tooltip="On-call: 19:00 – 07:00" />);
+ const badge = screen.getByText('Responder').closest('span');
+ expect(badge).toHaveAttribute('title', 'On-call: 19:00 – 07:00');
+ });
+
+ it('forwards a className for layout overrides', () => {
+ render(<RoleBadge role="viewer" className="my-custom-class" />);
+ const badge = screen.getByText('Viewer').closest('span');
+ expect(badge?.className).toContain('my-custom-class');
+ });
+});
diff --git a/apps/web/src/components/layout/RoleBadge.tsx b/apps/web/src/components/layout/RoleBadge.tsx
new file mode 100644
index 000000000..6e2ad9fdd
--- /dev/null
+++ b/apps/web/src/components/layout/RoleBadge.tsx
@@ -0,0 +1,83 @@
+'use client';
+
+import { clsx } from 'clsx';
+
+/**
+ * The user's *organisation-level* role, surfaced in the TopBar so operators
+ * always know what permissions they're operating under. Tone is tuned per
+ * role so an `admin` badge visually outranks a `viewer` badge.
+ *
+ * Unknown roles fall back to a neutral slate styling — a future RBAC
+ * iteration could add bespoke colours, but we'd rather render *something*
+ * informative than a confident-but-wrong label.
+ */
+const ROLE_STYLES: Record<string, { label: string; classes: string }> = {
+ admin: {
+ label: 'Admin',
+ classes:
+ 'bg-rose-500/10 text-rose-200 border-rose-500/30 dark:bg-rose-500/15',
+ },
+ responder: {
+ label: 'Responder',
+ classes:
+ 'bg-amber-500/10 text-amber-200 border-amber-500/30 dark:bg-amber-500/15',
+ },
+ analyst: {
+ label: 'Analyst',
+ classes:
+ 'bg-brand-500/10 text-brand-200 border-brand-500/30 dark:bg-brand-500/15',
+ },
+ viewer: {
+ label: 'Viewer',
+ classes:
+ 'bg-slate-500/10 text-slate-200 border-slate-500/30 dark:bg-slate-500/15',
+ },
+ auditor: {
+ label: 'Auditor',
+ classes:
+ 'bg-emerald-500/10 text-emerald-200 border-emerald-500/30 dark:bg-emerald-500/15',
+ },
+};
+
+const FALLBACK = {
+ label: 'User',
+ classes: 'bg-slate-500/10 text-slate-300 border-slate-500/30',
+};
+
+interface RoleBadgeProps {
+ role: string | null | undefined;
+ /** Visible label override, e.g. "Admin · Acme Corp". */
+ label?: string;
+ className?: string;
+ /** Optional tooltip (title attribute). */
+ tooltip?: string;
+}
+
+/**
+ * W5 — Role badge surfaced in the TopBar.
+ *
+ * Renders the user's role with role-specific styling. We intentionally use
+ * `border-*` + a translucent background instead of solid fills so the badge
+ * sits cleanly against both light- and dark-mode chrome.
+ */
+export function RoleBadge({ role, label, className, tooltip }: RoleBadgeProps) {
+ const norm = (role ?? '').toLowerCase();
+ const style = ROLE_STYLES[norm] ?? FALLBACK;
+ const displayLabel = label ?? style.label;
+ return (
+ <span
+ title={tooltip}
+ className={clsx(
+ 'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide',
+ style.classes,
+ className,
+ )}
+ >
+ <span
+ aria-hidden
+ className="h-1.5 w-1.5 rounded-full bg-current opacity-80"
+ />
+ {displayLabel}
+ </span>
+ );
+}
diff --git a/apps/web/src/components/layout/TenantProvider.test.tsx b/apps/web/src/components/layout/TenantProvider.test.tsx
new file mode 100644
index 000000000..7b087001c
--- /dev/null
+++ b/apps/web/src/components/layout/TenantProvider.test.tsx
@@ -0,0 +1,306 @@
+import { describe, expect, it, beforeEach, vi } from 'vitest';
+import { act, render, renderHook, screen, waitFor } from '@testing-library/react';
+import { TenantProvider, useTenant } from './TenantProvider';
+
+// `@/lib/api` is mocked end-to-end so the provider can be exercised in isolation
+// from the real network + localStorage helpers. Each mocked function is a
+// `vi.fn` we can program per test.
+const currentUserMock = vi.fn();
+const isAuthenticatedMock = vi.fn();
+const tenantsMeMock = vi.fn();
+const msspChildrenMock = vi.fn();
+const getActiveTenantIdMock = vi.fn(() => '');
+const setActiveTenantIdMock = vi.fn();
+
+vi.mock('@/lib/api', () => ({
+ authApi: {
+ currentUser: () => currentUserMock(),
+ isAuthenticated: () => isAuthenticatedMock(),
+ },
+ tenantsApi: {
+ me: () => tenantsMeMock(),
+ },
+ msspApi: {
+ listChildren: () => msspChildrenMock(),
+ },
+ getActiveTenantId: () => getActiveTenantIdMock(),
+ setActiveTenantId: (id: string | null) => setActiveTenantIdMock(id),
+}));
+
+function wrapper({ children }: { children: React.ReactNode }) {
+ return <TenantProvider>{children}</TenantProvider>;
+}
+
+beforeEach(() => {
+ currentUserMock.mockReset();
+ isAuthenticatedMock.mockReset();
+ tenantsMeMock.mockReset();
+ msspChildrenMock.mockReset();
+ getActiveTenantIdMock.mockReset();
+ getActiveTenantIdMock.mockReturnValue('');
+ setActiveTenantIdMock.mockReset();
+});
+
+describe('TenantProvider', () => {
+ it('exits loading=false when the user is not authenticated', async () => {
+ currentUserMock.mockReturnValue(null);
+ isAuthenticatedMock.mockReturnValue(false);
+
+ const { result } = renderHook(() => useTenant(), { wrapper });
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.current).toBeNull();
+ expect(result.current.available).toEqual([]);
+ expect(tenantsMeMock).not.toHaveBeenCalled();
+ });
+
+ it('loads the current tenant for a standalone (non-MSSP) user', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'analyst',
+ tenant_id: 't1',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ tenantsMeMock.mockResolvedValue({
+ id: 't1',
+ name: 'Acme Corp',
+ mssp_role: null,
+ parent_tenant_id: null,
+ });
+
+ const { result } = renderHook(() => useTenant(), { wrapper });
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.userRole).toBe('analyst');
+ expect(result.current.current).toEqual({
+ id: 't1',
+ name: 'Acme Corp',
+ role: 'standalone',
+ });
+ expect(result.current.available).toHaveLength(1);
+ // Standalone users should never trigger the /mssp/children call.
+ expect(msspChildrenMock).not.toHaveBeenCalled();
+ });
+
+ it('lists [parent, ...children] for an MSSP parent operator', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'mssp-admin',
+ tenant_id: 'parent-t',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ tenantsMeMock.mockResolvedValue({
+ id: 'parent-t',
+ name: 'MSSP Holdings',
+ mssp_role: 'parent',
+ parent_tenant_id: null,
+ });
+ msspChildrenMock.mockResolvedValue([
+ { id: 'c1', name: 'Customer A', mssp_role: 'child' },
+ { id: 'c2', name: 'Customer B', mssp_role: 'child' },
+ ]);
+
+ const { result } = renderHook(() => useTenant(), { wrapper });
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.available.map((t) => t.id)).toEqual(['parent-t', 'c1', 'c2']);
+ expect(result.current.available[0].role).toBe('parent');
+ expect(result.current.available[1].role).toBe('child');
+ expect(result.current.current?.id).toBe('parent-t');
+ });
+
+ it('honours an active tenant ID from storage when it resolves', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'mssp-admin',
+ tenant_id: 'parent-t',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ getActiveTenantIdMock.mockReturnValue('c2'); // stale-but-valid
+ tenantsMeMock.mockResolvedValue({
+ id: 'parent-t',
+ name: 'MSSP Holdings',
+ mssp_role: 'parent',
+ parent_tenant_id: null,
+ });
+ msspChildrenMock.mockResolvedValue([
+ { id: 'c1', name: 'Customer A', mssp_role: 'child' },
+ { id: 'c2', name: 'Customer B', mssp_role: 'child' },
+ ]);
+
+ const { result } = renderHook(() => useTenant(), { wrapper });
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.current?.id).toBe('c2');
+ expect(result.current.current?.name).toBe('Customer B');
+ });
+
+ it('falls back to "me" if the stored active tenant is not in the list', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'mssp-admin',
+ tenant_id: 'parent-t',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ getActiveTenantIdMock.mockReturnValue('deleted-child');
+ tenantsMeMock.mockResolvedValue({
+ id: 'parent-t',
+ name: 'MSSP Holdings',
+ mssp_role: 'parent',
+ parent_tenant_id: null,
+ });
+ msspChildrenMock.mockResolvedValue([]);
+
+ const { result } = renderHook(() => useTenant(), { wrapper });
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.current?.id).toBe('parent-t');
+ });
+
+ it('still renders a fallback tenant when /tenants/me errors', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'analyst',
+ tenant_id: 't1',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ tenantsMeMock.mockRejectedValue(new Error('boom'));
+
+ const { result } = renderHook(() => useTenant(), { wrapper });
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.error).toBe('boom');
+ expect(result.current.current).toEqual({
+ id: 't1',
+ name: 'My tenant',
+ role: 'standalone',
+ });
+ expect(result.current.available).toHaveLength(1);
+ });
+
+ it('tolerates /mssp/children failing for an otherwise-healthy parent', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'mssp-admin',
+ tenant_id: 'parent-t',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ tenantsMeMock.mockResolvedValue({
+ id: 'parent-t',
+ name: 'MSSP Holdings',
+ mssp_role: 'parent',
+ parent_tenant_id: null,
+ });
+ msspChildrenMock.mockRejectedValue(new Error('403'));
+
+ const { result } = renderHook(() => useTenant(), { wrapper });
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.error).toBeNull();
+ expect(result.current.current?.id).toBe('parent-t');
+ // No children → switcher will render as a read-only badge upstream.
+ expect(result.current.available).toHaveLength(1);
+ });
+
+ it('throws when useTenant() is called outside the provider', () => {
+ const err = vi.spyOn(console, 'error').mockImplementation(() => {});
+ expect(() => renderHook(() => useTenant())).toThrow(
+ /useTenant\(\) must be used inside <TenantProvider>/,
+ );
+ err.mockRestore();
+ });
+
+ it('setTenant() persists the choice via setActiveTenantId and dispatches an event', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'mssp-admin',
+ tenant_id: 'parent-t',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ tenantsMeMock.mockResolvedValue({
+ id: 'parent-t',
+ name: 'MSSP Holdings',
+ mssp_role: 'parent',
+ parent_tenant_id: null,
+ });
+ msspChildrenMock.mockResolvedValue([
+ { id: 'c1', name: 'Customer A', mssp_role: 'child' },
+ ]);
+
+ // Suppress JSDOM's "not implemented: navigation" noise from
+ // `window.location.reload()` — the call is intentional and we just
+ // need it to no-op.
+ const reloadSpy = vi.fn();
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: { ...window.location, reload: reloadSpy },
+ });
+
+ const switchedEvents: CustomEvent[] = [];
+ const handler = (e: Event) => switchedEvents.push(e as CustomEvent);
+ window.addEventListener('aisoc:tenant-switched', handler as EventListener);
+
+ const { result } = renderHook(() => useTenant(), { wrapper });
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ await act(async () => {
+ result.current.setTenant('c1');
+ });
+
+ expect(setActiveTenantIdMock).toHaveBeenCalledWith('c1');
+ expect(reloadSpy).toHaveBeenCalledTimes(1);
+ expect(switchedEvents).toHaveLength(1);
+ expect((switchedEvents[0].detail as { tenantId: string }).tenantId).toBe('c1');
+ expect(result.current.current?.id).toBe('c1');
+
+ window.removeEventListener('aisoc:tenant-switched', handler as EventListener);
+ });
+});
+
+describe('TenantProvider integration with consumers', () => {
+ it('exposes current/available/userRole to nested consumers', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'analyst-lead',
+ tenant_id: 't1',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ tenantsMeMock.mockResolvedValue({
+ id: 't1',
+ name: 'Acme',
+ mssp_role: null,
+ parent_tenant_id: null,
+ });
+
+ function Probe() {
+ const { current, available, userRole } = useTenant();
+ return (
+ <ul>
+ <li data-testid="role">{userRole ?? ''}</li>
+ <li data-testid="current">{current?.name ?? ''}</li>
+ <li data-testid="count">{available.length}</li>
+ </ul>
+ );
+ }
+
+ render(
+ <TenantProvider>
+ <Probe />
+ </TenantProvider>,
+ );
+
+ expect(screen.getByTestId('role')).toHaveTextContent('analyst-lead');
+ await waitFor(() => {
+ expect(screen.getByTestId('current')).toHaveTextContent('Acme');
+ expect(screen.getByTestId('count')).toHaveTextContent('1');
+ });
+ });
+});
diff --git a/apps/web/src/components/layout/TenantProvider.tsx b/apps/web/src/components/layout/TenantProvider.tsx
new file mode 100644
index 000000000..327035858
--- /dev/null
+++ b/apps/web/src/components/layout/TenantProvider.tsx
@@ -0,0 +1,199 @@
+'use client';
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+ type ReactNode,
+} from 'react';
+import {
+ authApi,
+ getActiveTenantId,
+ msspApi,
+ setActiveTenantId,
+ tenantsApi,
+ type AuthUser,
+ type ChildTenant,
+ type MyTenant,
+} from '@/lib/api';
+
+export interface TenantOption {
+ /** Stable tenant UUID — matches the `X-Tenant-Id` header value. */
+ id: string;
+ /** Human-readable display name. */
+ name: string;
+ /** What kind of tenant this is (parent / child / standalone). */
+ role: 'parent' | 'child' | 'standalone';
+}
+
+interface TenantContextValue {
+ /** Tenant the active session is currently operating against. */
+ current: TenantOption | null;
+ /** Every tenant the operator can flip to (incl. `current`). */
+ available: TenantOption[];
+ /** The signed-in user's *org-level* role (analyst / responder / admin / …). */
+ userRole: string | null;
+ /** Switch the active tenant. Triggers an SWR-level cache invalidation upstream. */
+ setTenant: (tenantId: string) => void;
+ /** True while we're loading the tenant list (e.g. on first paint). */
+ loading: boolean;
+ /** Last error, if any — surfaced through the TopBar role badge tooltip. */
+ error: string | null;
+}
+
+const TenantContext = createContext<TenantContextValue | null>(null);
+
+function toOption(t: MyTenant | (ChildTenant & { domain?: string | null })): TenantOption {
+ // Normalise the two API response shapes (MyTenant vs ChildTenant) into one
+ // dropdown-friendly type. ChildTenant.mssp_role is always 'child' (by the
+ // /mssp/children query filter) but we coerce defensively.
+ const role: TenantOption['role'] =
+ t.mssp_role === 'parent' || t.mssp_role === 'child'
+ ? t.mssp_role
+ : 'standalone';
+ return { id: t.id, name: t.name, role };
+}
+
+/**
+ * Tracks the active tenant + every tenant the user can flip to (W5).
+ *
+ * For a standalone tenant user, `available` is `[current]` and the
+ * TenantSwitcher renders as a read-only RoleBadge. For an MSSP parent
+ * operator, `available` lists `[parent, ...children]` and the switcher
+ * actually opens.
+ *
+ * Switching writes the new tenant ID through `setActiveTenantId()` so the
+ * shared `request()` helper picks it up on the *next* API call — callers
+ * that need to refetch should listen for `window.dispatchEvent('aisoc:tenant-switched')`
+ * and call SWR `mutate(() => true)`. Today we hard-reload the page (see
+ * `setTenant()` below) which is the safest option given how many SWR keys
+ * are tenant-scoped — a future iteration can wire that into a dedicated
+ * SWR cache reset.
+ */
+export function TenantProvider({ children }: { children: ReactNode }) {
+ const [current, setCurrent] = useState<TenantOption | null>(null);
+ const [available, setAvailable] = useState<TenantOption[]>([]);
+ const [userRole, setUserRole] = useState<string | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ async function load() {
+ // The user record is in localStorage (post-login) so we can populate
+ // `userRole` and a fallback `current` synchronously without waiting on
+ // the network. This avoids a flicker of "loading…" in the TopBar for
+ // returning users.
+ const user: AuthUser | null = authApi.currentUser();
+ if (!cancelled) setUserRole(user?.role ?? null);
+
+ // No bearer token → don't bother hitting protected endpoints; the
+ // TopBar will simply render without the badge. This is the demo-page /
+ // logged-out fallback.
+ if (!authApi.isAuthenticated()) {
+ if (!cancelled) {
+ setLoading(false);
+ }
+ return;
+ }
+
+ try {
+ // Fetch the canonical tenant record first; this is the only one we
+ // truly need to render the badge. Children come second and any
+ // failure there is non-fatal (e.g. /mssp/children 403 for a
+ // tenant-level user).
+ const me = await tenantsApi.me();
+ if (cancelled) return;
+ const meOption = toOption(me);
+
+ // Carry the user's previously-selected tenant forward, but only if
+ // it's still resolvable. Anything stale falls back to "me".
+ const activeId = getActiveTenantId();
+ let activeOption = meOption;
+
+ let children: ChildTenant[] = [];
+ if (me.mssp_role === 'parent') {
+ try {
+ children = await msspApi.listChildren();
+ } catch {
+ // Non-fatal: an MSSP parent without children is valid; a 403 here
+ // just means the user lacks `mssp:read` and we render the badge
+ // alone.
+ children = [];
+ }
+ }
+ if (cancelled) return;
+
+ const childOptions = children.map(toOption);
+ const list: TenantOption[] = [meOption, ...childOptions];
+ if (activeId) {
+ const match = list.find((t) => t.id === activeId);
+ if (match) activeOption = match;
+ }
+
+ setAvailable(list);
+ setCurrent(activeOption);
+ setError(null);
+ } catch (err) {
+ if (cancelled) return;
+ const message = err instanceof Error ? err.message : 'Failed to load tenant';
+ setError(message);
+ // We still want a usable badge — synthesise a `current` from the
+ // cached auth user so the TopBar isn't blank.
+ if (user) {
+ const fallback: TenantOption = {
+ id: user.tenant_id,
+ name: 'My tenant',
+ role: 'standalone',
+ };
+ setCurrent(fallback);
+ setAvailable([fallback]);
+ }
+ } finally {
+ if (!cancelled) setLoading(false);
+ }
+ }
+
+ load();
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const setTenant = useCallback((tenantId: string) => {
+ setActiveTenantId(tenantId);
+ // Find the new tenant inside our resolved list before navigating, so the
+ // post-reload paint already has the right context.
+ setCurrent((prev) => {
+ const next = available.find((t) => t.id === tenantId);
+ return next ?? prev;
+ });
+ if (typeof window !== 'undefined') {
+ // Hard reload is intentionally conservative: every SWR cache key has
+ // the old tenant scope baked in, and patching every consumer to
+ // re-key on `current.id` is a future workstream. Reloading guarantees
+ // a clean read.
+ window.dispatchEvent(new CustomEvent('aisoc:tenant-switched', { detail: { tenantId } }));
+ window.location.reload();
+ }
+ }, [available]);
+
+ const value = useMemo<TenantContextValue>(
+ () => ({ current, available, userRole, setTenant, loading, error }),
+ [current, available, userRole, setTenant, loading, error],
+ );
+
+ return <TenantContext.Provider value={value}>{children}</TenantContext.Provider>;
+}
+
+export function useTenant(): TenantContextValue {
+ const ctx = useContext(TenantContext);
+ if (!ctx) {
+ throw new Error('useTenant() must be used inside <TenantProvider>');
+ }
+ return ctx;
+}
diff --git a/apps/web/src/components/layout/TenantSwitcher.test.tsx b/apps/web/src/components/layout/TenantSwitcher.test.tsx
new file mode 100644
index 000000000..69af16215
--- /dev/null
+++ b/apps/web/src/components/layout/TenantSwitcher.test.tsx
@@ -0,0 +1,210 @@
+import { describe, expect, it, beforeEach, vi } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { TenantSwitcher } from './TenantSwitcher';
+import { TenantProvider } from './TenantProvider';
+
+const currentUserMock = vi.fn();
+const isAuthenticatedMock = vi.fn();
+const tenantsMeMock = vi.fn();
+const msspChildrenMock = vi.fn();
+const getActiveTenantIdMock = vi.fn(() => '');
+const setActiveTenantIdMock = vi.fn();
+
+vi.mock('@/lib/api', () => ({
+ authApi: {
+ currentUser: () => currentUserMock(),
+ isAuthenticated: () => isAuthenticatedMock(),
+ },
+ tenantsApi: {
+ me: () => tenantsMeMock(),
+ },
+ msspApi: {
+ listChildren: () => msspChildrenMock(),
+ },
+ getActiveTenantId: () => getActiveTenantIdMock(),
+ setActiveTenantId: (id: string | null) => setActiveTenantIdMock(id),
+}));
+
+beforeEach(() => {
+ currentUserMock.mockReset();
+ isAuthenticatedMock.mockReset();
+ tenantsMeMock.mockReset();
+ msspChildrenMock.mockReset();
+ getActiveTenantIdMock.mockReset();
+ getActiveTenantIdMock.mockReturnValue('');
+ setActiveTenantIdMock.mockReset();
+});
+
+function renderSwitcher() {
+ return render(
+ <TenantProvider>
+ <TenantSwitcher />
+ </TenantProvider>,
+ );
+}
+
+describe('TenantSwitcher', () => {
+ it('renders nothing when the user is not authenticated', async () => {
+ currentUserMock.mockReturnValue(null);
+ isAuthenticatedMock.mockReturnValue(false);
+
+ const { container } = renderSwitcher();
+ // First paint shows the loading pill; once loading resolves, the unauth
+ // branch returns null.
+ await waitFor(() => {
+ expect(container.querySelector('button')).toBeNull();
+ });
+ });
+
+ it('renders a read-only pill for a standalone tenant', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'analyst',
+ tenant_id: 't1',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ tenantsMeMock.mockResolvedValue({
+ id: 't1',
+ name: 'Acme Corp',
+ mssp_role: null,
+ parent_tenant_id: null,
+ });
+
+ renderSwitcher();
+
+ await waitFor(() => {
+ expect(screen.getByText('Acme Corp')).toBeInTheDocument();
+ });
+ // The read-only pill has no aria-haspopup trigger.
+ expect(screen.queryByRole('button', { name: /Active tenant/i })).toBeNull();
+ });
+
+ it('renders a switcher button for an MSSP parent', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'mssp-admin',
+ tenant_id: 'parent-t',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ tenantsMeMock.mockResolvedValue({
+ id: 'parent-t',
+ name: 'MSSP Holdings',
+ mssp_role: 'parent',
+ parent_tenant_id: null,
+ });
+ msspChildrenMock.mockResolvedValue([
+ { id: 'c1', name: 'Customer A', mssp_role: 'child' },
+ { id: 'c2', name: 'Customer B', mssp_role: 'child' },
+ ]);
+
+ renderSwitcher();
+
+ const trigger = await screen.findByRole('button', { name: /Active tenant/i });
+ expect(trigger).toHaveTextContent('MSSP Holdings');
+
+ await userEvent.click(trigger);
+
+ // Dropdown opens with all 3 tenants visible.
+ const list = screen.getByRole('listbox', { name: /Tenants/i });
+ const options = await screen.findAllByRole('option');
+ expect(options).toHaveLength(3);
+ expect(list).toHaveTextContent('MSSP Holdings');
+ expect(list).toHaveTextContent('Customer A');
+ expect(list).toHaveTextContent('Customer B');
+ });
+
+ it('switches tenants on click', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'mssp-admin',
+ tenant_id: 'parent-t',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ tenantsMeMock.mockResolvedValue({
+ id: 'parent-t',
+ name: 'MSSP Holdings',
+ mssp_role: 'parent',
+ parent_tenant_id: null,
+ });
+ msspChildrenMock.mockResolvedValue([
+ { id: 'c1', name: 'Customer A', mssp_role: 'child' },
+ ]);
+
+ // Stub out window.location.reload so the test runner doesn't bomb out.
+ const reloadSpy = vi.fn();
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: { ...window.location, reload: reloadSpy },
+ });
+
+ renderSwitcher();
+
+ const trigger = await screen.findByRole('button', { name: /Active tenant/i });
+ await userEvent.click(trigger);
+
+ const customer = await screen.findByRole('option', { name: /Customer A/i });
+ await userEvent.click(customer);
+
+ expect(setActiveTenantIdMock).toHaveBeenCalledWith('c1');
+ expect(reloadSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('disables the active tenant in the dropdown', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'mssp-admin',
+ tenant_id: 'parent-t',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ tenantsMeMock.mockResolvedValue({
+ id: 'parent-t',
+ name: 'MSSP Holdings',
+ mssp_role: 'parent',
+ parent_tenant_id: null,
+ });
+ msspChildrenMock.mockResolvedValue([
+ { id: 'c1', name: 'Customer A', mssp_role: 'child' },
+ ]);
+
+ renderSwitcher();
+
+ const trigger = await screen.findByRole('button', { name: /Active tenant/i });
+ await userEvent.click(trigger);
+
+ const active = await screen.findByRole('option', { name: /MSSP Holdings/i });
+ expect(active).toBeDisabled();
+ expect(active).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('closes on Escape', async () => {
+ currentUserMock.mockReturnValue({
+ id: 'u1',
+ email: '[email protected]',
+ role: 'mssp-admin',
+ tenant_id: 'parent-t',
+ });
+ isAuthenticatedMock.mockReturnValue(true);
+ tenantsMeMock.mockResolvedValue({
+ id: 'parent-t',
+ name: 'MSSP Holdings',
+ mssp_role: 'parent',
+ parent_tenant_id: null,
+ });
+ msspChildrenMock.mockResolvedValue([
+ { id: 'c1', name: 'Customer A', mssp_role: 'child' },
+ ]);
+
+ renderSwitcher();
+
+ const trigger = await screen.findByRole('button', { name: /Active tenant/i });
+ await userEvent.click(trigger);
+ expect(screen.getByRole('dialog', { name: /Switch tenant/i })).toBeInTheDocument();
+ await userEvent.keyboard('{Escape}');
+ expect(screen.queryByRole('dialog', { name: /Switch tenant/i })).not.toBeInTheDocument();
+ });
+});
diff --git a/apps/web/src/components/layout/TenantSwitcher.tsx b/apps/web/src/components/layout/TenantSwitcher.tsx
new file mode 100644
index 000000000..7f0eb15ae
--- /dev/null
+++ b/apps/web/src/components/layout/TenantSwitcher.tsx
@@ -0,0 +1,289 @@
+'use client';
+
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { clsx } from 'clsx';
+import { useTenant } from '@/components/layout/TenantProvider';
+
+interface TenantSwitcherProps {
+ className?: string;
+}
+
+/**
+ * W5 — Tenant switcher.
+ *
+ * Renders the active tenant as a pill button and (for MSSP parents) lets the
+ * operator flip to a child tenant. Selection delegates to
+ * `TenantProvider.setTenant`, which:
+ * - writes the chosen tenant id to localStorage,
+ * - dispatches `aisoc:tenant-switched`,
+ * - reloads the page to flush every SWR cache and re-issue API calls with
+ * the new `X-Tenant-Id`.
+ *
+ * For standalone tenants we render a read-only pill (no chevron, no
+ * dropdown) so the chrome still telegraphs the active tenant without
+ * pretending switching is possible.
+ */
+export function TenantSwitcher({ className }: TenantSwitcherProps) {
+ const { current, available, setTenant, loading, error } = useTenant();
+ const [open, setOpen] = useState(false);
+ const [filter, setFilter] = useState('');
+ const buttonRef = useRef<HTMLButtonElement | null>(null);
+ const menuRef = useRef<HTMLDivElement | null>(null);
+ const filterInputRef = useRef<HTMLInputElement | null>(null);
+
+ const canSwitch = available.length > 1;
+
+ useEffect(() => {
+ if (!open) return;
+ const onClick = (e: MouseEvent) => {
+ const target = e.target as Node | null;
+ if (
+ target &&
+ !buttonRef.current?.contains(target) &&
+ !menuRef.current?.contains(target)
+ ) {
+ setOpen(false);
+ }
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ setOpen(false);
+ buttonRef.current?.focus();
+ }
+ };
+ document.addEventListener('mousedown', onClick);
+ document.addEventListener('keydown', onKey);
+ return () => {
+ document.removeEventListener('mousedown', onClick);
+ document.removeEventListener('keydown', onKey);
+ };
+ }, [open]);
+
+ // Auto-focus the filter once the menu is shown — when there are more than
+ // a handful of tenants, typing to filter is faster than mouse navigation.
+ useEffect(() => {
+ if (open && available.length > 6) {
+ // next tick so the input is mounted
+ const id = window.setTimeout(() => filterInputRef.current?.focus(), 0);
+ return () => window.clearTimeout(id);
+ }
+ }, [open, available.length]);
+
+ const filtered = useMemo(() => {
+ const q = filter.trim().toLowerCase();
+ if (!q) return available;
+ return available.filter(
+ (t) =>
+ t.name.toLowerCase().includes(q) || t.id.toLowerCase().includes(q),
+ );
+ }, [filter, available]);
+
+ if (loading && !current) {
+ return (
+ <div
+ className={clsx(
+ 'inline-flex items-center gap-1.5 rounded-md border border-surface-border bg-surface-card/40 px-2.5 py-1 text-xs text-fg-subtle',
+ className,
+ )}
+ aria-label="Loading tenant"
+ >
+ <svg
+ className="h-3.5 w-3.5 animate-spin"
+ fill="none"
+ viewBox="0 0 24 24"
+ aria-hidden
+ >
+ <circle
+ cx="12"
+ cy="12"
+ r="9"
+ stroke="currentColor"
+ strokeWidth="2.5"
+ strokeOpacity="0.25"
+ />
+ <path
+ d="M21 12a9 9 0 00-9-9"
+ stroke="currentColor"
+ strokeWidth="2.5"
+ strokeLinecap="round"
+ />
+ </svg>
+ Loading…
+ </div>
+ );
+ }
+
+ if (!current) {
+ // Not authenticated, or `/tenants/me` failed without a fallback.
+ return null;
+ }
+
+ // Standalone tenants get a read-only pill so the chrome still shows the
+ // active org but doesn't suggest switching is possible.
+ if (!canSwitch) {
+ return (
+ <div
+ title={error ?? `Tenant: ${current.name}`}
+ className={clsx(
+ 'inline-flex items-center gap-1.5 rounded-md border border-surface-border bg-surface-card/60 px-2.5 py-1 text-xs text-fg-secondary',
+ className,
+ )}
+ >
+ <TenantIcon />
+ <span className="max-w-[10rem] truncate font-medium text-fg-primary">
+ {current.name}
+ </span>
+ </div>
+ );
+ }
+
+ return (
+ <div className={clsx('relative', className)}>
+ <button
+ ref={buttonRef}
+ type="button"
+ onClick={() => setOpen((o) => !o)}
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ aria-label={`Active tenant: ${current.name}. Click to switch.`}
+ className="inline-flex items-center gap-1.5 rounded-md border border-surface-border bg-surface-card/60 px-2.5 py-1 text-xs text-fg-secondary transition-colors hover:border-brand-500/40 hover:bg-surface-card hover:text-fg-primary focus:border-brand-500/60 focus:outline-none focus:ring-2 focus:ring-brand-500/30"
+ >
+ <TenantIcon />
+ <span className="max-w-[10rem] truncate font-medium text-fg-primary">
+ {current.name}
+ </span>
+ <svg
+ className={clsx(
+ 'h-3 w-3 text-fg-subtle transition-transform',
+ open && 'rotate-180',
+ )}
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ aria-hidden
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M19 9l-7 7-7-7"
+ />
+ </svg>
+ </button>
+
+ {open && (
+ <div
+ ref={menuRef}
+ role="dialog"
+ aria-label="Switch tenant"
+ className="absolute right-0 z-30 mt-1.5 w-72 overflow-hidden rounded-md border border-surface-border bg-surface-raised shadow-lg ring-1 ring-black/5"
+ >
+ <div className="border-b border-surface-border px-3 py-2 text-[10px] font-semibold uppercase tracking-wide text-fg-subtle">
+ Switch tenant
+ <span className="ml-2 text-fg-muted normal-case">
+ · {available.length} available
+ </span>
+ </div>
+
+ {available.length > 6 && (
+ <div className="border-b border-surface-border px-2 py-2">
+ <input
+ ref={filterInputRef}
+ value={filter}
+ onChange={(e) => setFilter(e.target.value)}
+ placeholder="Filter tenants…"
+ className="w-full rounded-md border border-surface-border bg-surface-card px-2 py-1 text-sm text-fg-primary placeholder:text-fg-subtle focus:border-brand-500/60 focus:outline-none focus:ring-2 focus:ring-brand-500/30"
+ />
+ </div>
+ )}
+
+ <ul
+ role="listbox"
+ aria-label="Tenants"
+ className="max-h-72 overflow-y-auto py-1"
+ >
+ {filtered.length === 0 && (
+ <li className="px-3 py-2 text-sm text-fg-subtle">
+ No tenants match “{filter}”.
+ </li>
+ )}
+ {filtered.map((t) => {
+ const isActive = t.id === current.id;
+ return (
+ <li key={t.id}>
+ <button
+ type="button"
+ role="option"
+ aria-selected={isActive}
+ disabled={isActive}
+ onClick={() => {
+ if (!isActive) setTenant(t.id);
+ }}
+ className={clsx(
+ 'flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-sm transition-colors',
+ isActive
+ ? 'cursor-default bg-surface-hover text-fg-primary'
+ : 'text-fg-secondary hover:bg-surface-hover hover:text-fg-primary',
+ )}
+ >
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate font-medium">{t.name}</span>
+ <span className="truncate text-[10px] uppercase tracking-wide text-fg-subtle">
+ {t.role === 'parent'
+ ? 'MSSP parent'
+ : t.role === 'child'
+ ? 'Child tenant'
+ : 'Standalone'}
+ </span>
+ </span>
+ {isActive && (
+ <svg
+ className="h-3.5 w-3.5 flex-shrink-0 text-brand-500"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ aria-hidden
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M5 13l4 4L19 7"
+ />
+ </svg>
+ )}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+
+ {error && (
+ <div className="border-t border-surface-border bg-rose-500/5 px-3 py-2 text-xs text-rose-300">
+ {error}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function TenantIcon() {
+ return (
+ <svg
+ className="h-3.5 w-3.5 text-fg-subtle"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ aria-hidden
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0H5m14 0h2m-2 0V9m-7 12V9m0 0h7M5 21h2m-2 0V9m0 0h7"
+ />
+ </svg>
+ );
+}
diff --git a/apps/web/src/components/layout/TimeWindowProvider.test.tsx b/apps/web/src/components/layout/TimeWindowProvider.test.tsx
new file mode 100644
index 000000000..c069e27e9
--- /dev/null
+++ b/apps/web/src/components/layout/TimeWindowProvider.test.tsx
@@ -0,0 +1,152 @@
+import { describe, expect, it, beforeEach, vi } from 'vitest';
+import { act, render, renderHook, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { TimeWindowProvider, useTimeWindow } from './TimeWindowProvider';
+import { TIME_WINDOW_STORAGE_KEY, type TimeWindow } from '@/lib/timeWindow';
+
+// Minimal `authApi` mock — TimeWindowProvider reads `currentUser()?.preferences`
+// at mount and fires `updateUserPreferences` on writes. The provider must work
+// when the user is logged out (currentUser → null) and must not crash if the
+// preferences PATCH rejects.
+const currentUserMock = vi.fn(() => null as { preferences?: Record<string, unknown> } | null);
+const updateUserPreferencesMock = vi.fn(
+ (_p: Record<string, unknown>) => Promise.resolve() as Promise<unknown>,
+);
+
+vi.mock('@/lib/api', () => ({
+ authApi: {
+ currentUser: () => currentUserMock(),
+ updateUserPreferences: (p: Record<string, unknown>) => updateUserPreferencesMock(p),
+ },
+}));
+
+function clearStorage() {
+ try {
+ window.localStorage.removeItem(TIME_WINDOW_STORAGE_KEY);
+ } catch {
+ /* ignore */
+ }
+}
+
+describe('TimeWindowProvider', () => {
+ beforeEach(() => {
+ clearStorage();
+ currentUserMock.mockReset();
+ currentUserMock.mockReturnValue(null);
+ updateUserPreferencesMock.mockReset();
+ updateUserPreferencesMock.mockResolvedValue(undefined as never);
+ });
+
+ it('defaults to "24h" when nothing is stored and the user has no preference', () => {
+ const { result } = renderHook(() => useTimeWindow(), {
+ wrapper: ({ children }) => <TimeWindowProvider>{children}</TimeWindowProvider>,
+ });
+ expect(result.current.window).toBe<TimeWindow>('24h');
+ });
+
+ it('reconciles to a stored value on mount', async () => {
+ window.localStorage.setItem(TIME_WINDOW_STORAGE_KEY, '7d');
+ const { result } = renderHook(() => useTimeWindow(), {
+ wrapper: ({ children }) => <TimeWindowProvider>{children}</TimeWindowProvider>,
+ });
+ // useEffect runs after the initial render; tick the React tree once.
+ await act(async () => {});
+ expect(result.current.window).toBe<TimeWindow>('7d');
+ });
+
+ it('persists writes to localStorage and the server', async () => {
+ const { result } = renderHook(() => useTimeWindow(), {
+ wrapper: ({ children }) => <TimeWindowProvider>{children}</TimeWindowProvider>,
+ });
+ await act(async () => {
+ result.current.setWindow('30d');
+ });
+ expect(result.current.window).toBe<TimeWindow>('30d');
+ expect(window.localStorage.getItem(TIME_WINDOW_STORAGE_KEY)).toBe('30d');
+ expect(updateUserPreferencesMock).toHaveBeenCalledWith({ timeWindow: '30d' });
+ });
+
+ it('prefers the server preference over a stale localStorage value', async () => {
+ window.localStorage.setItem(TIME_WINDOW_STORAGE_KEY, '24h');
+ currentUserMock.mockReturnValue({ preferences: { timeWindow: '7d' } });
+ const { result } = renderHook(() => useTimeWindow(), {
+ wrapper: ({ children }) => <TimeWindowProvider>{children}</TimeWindowProvider>,
+ });
+ await act(async () => {});
+ expect(result.current.window).toBe<TimeWindow>('7d');
+ // The provider should also rewrite localStorage so the next paint matches.
+ expect(window.localStorage.getItem(TIME_WINDOW_STORAGE_KEY)).toBe('7d');
+ });
+
+ it('throws when useTimeWindow() is called outside the provider', () => {
+ // Silence the React error boundary noise.
+ const err = vi.spyOn(console, 'error').mockImplementation(() => {});
+ expect(() => renderHook(() => useTimeWindow())).toThrow(
+ /useTimeWindow\(\) must be used inside <TimeWindowProvider>/,
+ );
+ err.mockRestore();
+ });
+
+ it('does not crash when localStorage is unavailable', async () => {
+ // Simulate iOS Private Mode: getItem/setItem throw. The test setup installs
+ // a custom Storage shim on `window`, so we patch the shim's own methods
+ // rather than `Storage.prototype` (which the shim doesn't inherit from).
+ const original = window.localStorage;
+ const broken = {
+ ...original,
+ getItem: () => {
+ throw new Error('QuotaExceededError');
+ },
+ setItem: () => {
+ throw new Error('QuotaExceededError');
+ },
+ } as Storage;
+ Object.defineProperty(window, 'localStorage', { configurable: true, value: broken });
+
+ try {
+ const { result } = renderHook(() => useTimeWindow(), {
+ wrapper: ({ children }) => <TimeWindowProvider>{children}</TimeWindowProvider>,
+ });
+ await act(async () => {
+ // Should not throw even though localStorage is broken.
+ result.current.setWindow('1h');
+ });
+ expect(result.current.window).toBe<TimeWindow>('1h');
+ } finally {
+ Object.defineProperty(window, 'localStorage', {
+ configurable: true,
+ value: original,
+ });
+ }
+ });
+});
+
+describe('TimeWindowProvider integration with consumers', () => {
+ beforeEach(() => {
+ clearStorage();
+ currentUserMock.mockReset();
+ currentUserMock.mockReturnValue(null);
+ updateUserPreferencesMock.mockReset();
+ updateUserPreferencesMock.mockResolvedValue(undefined as never);
+ });
+
+ it('exposes the current window to nested consumers', async () => {
+ function Probe() {
+ const { window: w, setWindow } = useTimeWindow();
+ return (
+ <div>
+ <span data-testid="window">{w}</span>
+ <button onClick={() => setWindow('1h')}>shrink</button>
+ </div>
+ );
+ }
+ render(
+ <TimeWindowProvider>
+ <Probe />
+ </TimeWindowProvider>,
+ );
+ expect(screen.getByTestId('window')).toHaveTextContent('24h');
+ await userEvent.click(screen.getByRole('button', { name: /shrink/i }));
+ expect(screen.getByTestId('window')).toHaveTextContent('1h');
+ });
+});
diff --git a/apps/web/src/components/layout/TimeWindowProvider.tsx b/apps/web/src/components/layout/TimeWindowProvider.tsx
new file mode 100644
index 000000000..15f8ebff3
--- /dev/null
+++ b/apps/web/src/components/layout/TimeWindowProvider.tsx
@@ -0,0 +1,107 @@
+'use client';
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+ type ReactNode,
+} from 'react';
+import { authApi } from '@/lib/api';
+import {
+ DEFAULT_TIME_WINDOW,
+ TIME_WINDOW_STORAGE_KEY,
+ isTimeWindow,
+ type TimeWindow,
+} from '@/lib/timeWindow';
+
+interface TimeWindowContextValue {
+ /** Currently-active window — every dashboard should bind to this. */
+ window: TimeWindow;
+ /** Update the window and persist (localStorage + user preferences). */
+ setWindow: (next: TimeWindow) => void;
+}
+
+const TimeWindowContext = createContext<TimeWindowContextValue | null>(null);
+
+function readStored(): TimeWindow {
+ if (typeof window === 'undefined') return DEFAULT_TIME_WINDOW;
+ try {
+ const raw = window.localStorage.getItem(TIME_WINDOW_STORAGE_KEY);
+ if (isTimeWindow(raw)) return raw;
+ } catch {
+ /* localStorage can be unavailable (iOS private mode); ignore */
+ }
+ return DEFAULT_TIME_WINDOW;
+}
+
+/**
+ * Provides the global TimeWindow (W4).
+ *
+ * Initial render uses the default window so SSR and the first client paint
+ * match exactly — there's no inline bootstrap script for this (unlike the
+ * theme, where the wrong colour for one paint is visually jarring). Right
+ * after mount we reconcile with localStorage *and* the user's server-side
+ * preference so the choice roams across browsers.
+ *
+ * Writes are local-first: we update React state + localStorage
+ * synchronously, then fire-and-forget the PATCH to /auth/me/preferences.
+ * A failed network call must not throw away the user's selection.
+ */
+export function TimeWindowProvider({ children }: { children: ReactNode }) {
+ const [timeWindow, setTimeWindowState] = useState<TimeWindow>(DEFAULT_TIME_WINDOW);
+
+ // Mount: reconcile with localStorage, then with the server-stored user
+ // preference (cached from /me). Same pattern as ThemeProvider so the two
+ // behave identically — once we hydrate, the user's last-chosen window
+ // wins, and if that disagrees with the server, the server value takes
+ // precedence (i.e. "I logged in from a new machine — my preference comes
+ // with me").
+ useEffect(() => {
+ const stored = readStored();
+ if (stored !== DEFAULT_TIME_WINDOW) {
+ setTimeWindowState(stored);
+ }
+
+ const user = authApi.currentUser();
+ const serverWindow = user?.preferences?.timeWindow;
+ if (isTimeWindow(serverWindow) && serverWindow !== stored) {
+ setTimeWindowState(serverWindow);
+ try {
+ window.localStorage.setItem(TIME_WINDOW_STORAGE_KEY, serverWindow);
+ } catch {
+ /* ignore */
+ }
+ }
+ }, []);
+
+ const setWindow = useCallback((next: TimeWindow) => {
+ setTimeWindowState(next);
+ try {
+ window.localStorage.setItem(TIME_WINDOW_STORAGE_KEY, next);
+ } catch {
+ /* private mode — accept that this doesn't persist */
+ }
+ // Fire-and-forget; the local value is the source of truth.
+ authApi.updateUserPreferences({ timeWindow: next }).catch(() => {
+ /* ignore — server preference is a nice-to-have, not a guarantee */
+ });
+ }, []);
+
+ const value = useMemo<TimeWindowContextValue>(
+ () => ({ window: timeWindow, setWindow }),
+ [timeWindow, setWindow],
+ );
+
+ return <TimeWindowContext.Provider value={value}>{children}</TimeWindowContext.Provider>;
+}
+
+export function useTimeWindow(): TimeWindowContextValue {
+ const ctx = useContext(TimeWindowContext);
+ if (!ctx) {
+ throw new Error('useTimeWindow() must be used inside <TimeWindowProvider>');
+ }
+ return ctx;
+}
diff --git a/apps/web/src/components/layout/TimeWindowSelector.test.tsx b/apps/web/src/components/layout/TimeWindowSelector.test.tsx
new file mode 100644
index 000000000..32247b3f9
--- /dev/null
+++ b/apps/web/src/components/layout/TimeWindowSelector.test.tsx
@@ -0,0 +1,98 @@
+import { describe, expect, it, beforeEach, vi } from 'vitest';
+import { render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { TimeWindowSelector } from './TimeWindowSelector';
+import { TimeWindowProvider } from './TimeWindowProvider';
+import { TIME_WINDOW_STORAGE_KEY } from '@/lib/timeWindow';
+
+const currentUserMock = vi.fn(() => null as { preferences?: Record<string, unknown> } | null);
+const updateUserPreferencesMock = vi.fn(
+ (_p: Record<string, unknown>) => Promise.resolve() as Promise<unknown>,
+);
+
+vi.mock('@/lib/api', () => ({
+ authApi: {
+ currentUser: () => currentUserMock(),
+ updateUserPreferences: (p: Record<string, unknown>) => updateUserPreferencesMock(p),
+ },
+}));
+
+beforeEach(() => {
+ try {
+ window.localStorage.removeItem(TIME_WINDOW_STORAGE_KEY);
+ } catch {
+ /* ignore */
+ }
+ currentUserMock.mockReset();
+ currentUserMock.mockReturnValue(null);
+ updateUserPreferencesMock.mockReset();
+ updateUserPreferencesMock.mockResolvedValue(undefined as never);
+});
+
+function renderSelector() {
+ return render(
+ <TimeWindowProvider>
+ <TimeWindowSelector />
+ </TimeWindowProvider>,
+ );
+}
+
+describe('TimeWindowSelector', () => {
+ it('renders the short label for the active window', () => {
+ renderSelector();
+ expect(screen.getByRole('button', { name: /Time window/ })).toBeInTheDocument();
+ // Default is "24h".
+ expect(screen.getByRole('button', { name: /Time window/ })).toHaveTextContent('24h');
+ });
+
+ it('opens the dropdown and shows the four windows', async () => {
+ renderSelector();
+ await userEvent.click(screen.getByRole('button', { name: /Time window/ }));
+
+ const list = screen.getByRole('listbox', { name: /Select time window/i });
+ const options = within(list).getAllByRole('option');
+ expect(options).toHaveLength(4);
+ expect(options.map((o) => o.textContent?.trim().split('\n')[0])).toEqual([
+ 'Last hour',
+ 'Last 24 hours',
+ 'Last 7 days',
+ 'Last 30 days',
+ ]);
+ });
+
+ it('updates the active window on click', async () => {
+ renderSelector();
+ const trigger = screen.getByRole('button', { name: /Time window/ });
+ await userEvent.click(trigger);
+
+ await userEvent.click(screen.getByRole('option', { name: /Last 7 days/i }));
+
+ // Dropdown should close and the trigger reflects the new selection.
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
+ expect(trigger).toHaveTextContent('7d');
+ // Persistence: localStorage + server.
+ expect(window.localStorage.getItem(TIME_WINDOW_STORAGE_KEY)).toBe('7d');
+ expect(updateUserPreferencesMock).toHaveBeenCalledWith({ timeWindow: '7d' });
+ });
+
+ it('marks the active window with aria-selected', async () => {
+ renderSelector();
+ await userEvent.click(screen.getByRole('button', { name: /Time window/ }));
+
+ const active = screen
+ .getAllByRole('option')
+ .find((opt) => opt.getAttribute('aria-selected') === 'true');
+ expect(active).toBeDefined();
+ expect(active).toHaveTextContent('Last 24 hours');
+ });
+
+ it('closes on Escape', async () => {
+ renderSelector();
+ const trigger = screen.getByRole('button', { name: /Time window/ });
+ await userEvent.click(trigger);
+
+ expect(screen.getByRole('listbox')).toBeInTheDocument();
+ await userEvent.keyboard('{Escape}');
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
+ });
+});
diff --git a/apps/web/src/components/layout/TimeWindowSelector.tsx b/apps/web/src/components/layout/TimeWindowSelector.tsx
new file mode 100644
index 000000000..27b34b197
--- /dev/null
+++ b/apps/web/src/components/layout/TimeWindowSelector.tsx
@@ -0,0 +1,222 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { clsx } from 'clsx';
+import { useTimeWindow } from '@/components/layout/TimeWindowProvider';
+import {
+ TIME_WINDOWS,
+ TIME_WINDOW_LONG_LABEL,
+ TIME_WINDOW_SHORT_LABEL,
+ type TimeWindow,
+} from '@/lib/timeWindow';
+
+interface TimeWindowSelectorProps {
+ /**
+ * Visual size. `'compact'` is meant for the TopBar (pill); `'full'` adds
+ * a leading "Time window:" label and is meant for dashboards that want the
+ * selector inline with their header.
+ */
+ variant?: 'compact' | 'full';
+ /** Optional className for layout overrides at the call site. */
+ className?: string;
+}
+
+/**
+ * W4 — Global time-window selector.
+ *
+ * Renders a pill button + dropdown listing the four supported windows (1h /
+ * 24h / 7d / 30d). Selection writes through `TimeWindowProvider.setWindow`,
+ * so:
+ * - the choice persists to localStorage and to the user's preferences,
+ * - every consumer (`useTimeWindow()`) sees the update on the same tick.
+ *
+ * Keyboard model: ArrowUp/ArrowDown wraps through the four options,
+ * Enter/Space selects, Escape closes. This matches the saved-views
+ * dropdown's behaviour for consistency.
+ */
+export function TimeWindowSelector({
+ variant = 'compact',
+ className,
+}: TimeWindowSelectorProps) {
+ const { window: active, setWindow } = useTimeWindow();
+ const [open, setOpen] = useState(false);
+ const [highlight, setHighlight] = useState<number>(() =>
+ Math.max(0, TIME_WINDOWS.indexOf(active)),
+ );
+ const buttonRef = useRef<HTMLButtonElement | null>(null);
+ const menuRef = useRef<HTMLDivElement | null>(null);
+
+ // Close on outside click / Esc — same pattern used by SavedViewsBar.
+ useEffect(() => {
+ if (!open) return;
+ const onClick = (e: MouseEvent) => {
+ const target = e.target as Node | null;
+ if (
+ target &&
+ !buttonRef.current?.contains(target) &&
+ !menuRef.current?.contains(target)
+ ) {
+ setOpen(false);
+ }
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ setOpen(false);
+ buttonRef.current?.focus();
+ }
+ };
+ document.addEventListener('mousedown', onClick);
+ document.addEventListener('keydown', onKey);
+ return () => {
+ document.removeEventListener('mousedown', onClick);
+ document.removeEventListener('keydown', onKey);
+ };
+ }, [open]);
+
+ // Keep keyboard highlight in sync with the active window each time we open.
+ useEffect(() => {
+ if (open) setHighlight(Math.max(0, TIME_WINDOWS.indexOf(active)));
+ }, [open, active]);
+
+ const handleSelect = (next: TimeWindow) => {
+ setWindow(next);
+ setOpen(false);
+ buttonRef.current?.focus();
+ };
+
+ const onTriggerKey = (e: React.KeyboardEvent<HTMLButtonElement>) => {
+ if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ setOpen(true);
+ }
+ };
+
+ const onMenuKey = (e: React.KeyboardEvent<HTMLDivElement>) => {
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ setHighlight((h) => (h + 1) % TIME_WINDOWS.length);
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ setHighlight((h) => (h - 1 + TIME_WINDOWS.length) % TIME_WINDOWS.length);
+ } else if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ handleSelect(TIME_WINDOWS[highlight]);
+ } else if (e.key === 'Home') {
+ e.preventDefault();
+ setHighlight(0);
+ } else if (e.key === 'End') {
+ e.preventDefault();
+ setHighlight(TIME_WINDOWS.length - 1);
+ }
+ };
+
+ return (
+ <div className={clsx('relative', className)}>
+ <button
+ ref={buttonRef}
+ type="button"
+ onClick={() => setOpen((o) => !o)}
+ onKeyDown={onTriggerKey}
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ aria-label={`Time window: ${TIME_WINDOW_LONG_LABEL[active]}`}
+ className={clsx(
+ 'inline-flex items-center gap-1.5 rounded-md border border-surface-border bg-surface-card/60 text-fg-secondary transition-colors hover:border-brand-500/40 hover:bg-surface-card hover:text-fg-primary focus:border-brand-500/60 focus:outline-none focus:ring-2 focus:ring-brand-500/30',
+ variant === 'compact' ? 'px-2.5 py-1 text-xs' : 'px-3 py-2 text-sm',
+ )}
+ >
+ <svg
+ className="h-3.5 w-3.5 text-fg-subtle"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ aria-hidden
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
+ />
+ </svg>
+ {variant === 'full' && (
+ <span className="text-fg-muted">Window:</span>
+ )}
+ <span className="font-mono font-medium tabular-nums">
+ {TIME_WINDOW_SHORT_LABEL[active]}
+ </span>
+ <svg
+ className={clsx(
+ 'h-3 w-3 text-fg-subtle transition-transform',
+ open && 'rotate-180',
+ )}
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ aria-hidden
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M19 9l-7 7-7-7"
+ />
+ </svg>
+ </button>
+
+ {open && (
+ <div
+ ref={menuRef}
+ role="listbox"
+ tabIndex={-1}
+ aria-label="Select time window"
+ onKeyDown={onMenuKey}
+ className="absolute right-0 z-30 mt-1.5 min-w-[10rem] overflow-hidden rounded-md border border-surface-border bg-surface-raised shadow-lg ring-1 ring-black/5 focus:outline-none"
+ >
+ <ul className="py-1">
+ {TIME_WINDOWS.map((w, idx) => {
+ const isActive = w === active;
+ const isHighlighted = idx === highlight;
+ return (
+ <li key={w}>
+ <button
+ type="button"
+ role="option"
+ aria-selected={isActive}
+ onClick={() => handleSelect(w)}
+ onMouseEnter={() => setHighlight(idx)}
+ className={clsx(
+ 'flex w-full items-center justify-between gap-3 px-3 py-1.5 text-left text-sm transition-colors',
+ isHighlighted
+ ? 'bg-surface-hover text-fg-primary'
+ : 'text-fg-secondary',
+ isActive && 'font-semibold text-fg-primary',
+ )}
+ >
+ <span>{TIME_WINDOW_LONG_LABEL[w]}</span>
+ {isActive && (
+ <svg
+ className="h-3.5 w-3.5 text-brand-500"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ aria-hidden
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M5 13l4 4L19 7"
+ />
+ </svg>
+ )}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/layout/TopBar.test.tsx b/apps/web/src/components/layout/TopBar.test.tsx
index 6b8333803..1c0cf425b 100644
--- a/apps/web/src/components/layout/TopBar.test.tsx
+++ b/apps/web/src/components/layout/TopBar.test.tsx
@@ -10,14 +10,23 @@ vi.mock('next/navigation', () => ({
import { TopBar } from './TopBar';
import { ThemeProvider } from '../theme/ThemeProvider';
+import { TimeWindowProvider } from './TimeWindowProvider';
+import { TenantProvider } from './TenantProvider';
-// TopBar embeds <ThemeToggle/> (WS-F1), which calls useTheme() and so must
-// always be rendered inside a <ThemeProvider>. Wrap once here so each test
-// reads naturally.
+// TopBar depends on three React contexts:
+// - <ThemeProvider/> for the WS-F1 theme toggle (`useTheme`)
+// - <TimeWindowProvider/> for the v1.5 W4 global time-window selector
+// - <TenantProvider/> for the v1.5 W5 tenant switcher + role badge
+// Wrap all three here so each test reads naturally without re-stating the
+// provider scaffolding.
function renderTopBar() {
return render(
<ThemeProvider>
- <TopBar />
+ <TimeWindowProvider>
+ <TenantProvider>
+ <TopBar />
+ </TenantProvider>
+ </TimeWindowProvider>
</ThemeProvider>,
);
}
diff --git a/apps/web/src/components/layout/TopBar.tsx b/apps/web/src/components/layout/TopBar.tsx
index 06bf7502b..02d0cf990 100644
--- a/apps/web/src/components/layout/TopBar.tsx
+++ b/apps/web/src/components/layout/TopBar.tsx
@@ -3,6 +3,10 @@
import { useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';
import { ThemeToggle } from '@/components/theme/ThemeToggle';
+import { TimeWindowSelector } from './TimeWindowSelector';
+import { TenantSwitcher } from './TenantSwitcher';
+import { RoleBadge } from './RoleBadge';
+import { useTenant } from './TenantProvider';
// Order matters: longer/more specific paths first so startsWith() picks
// the right label for nested routes (e.g. /detection/catalog before /detection).
@@ -42,6 +46,7 @@ export function TopBar({ demoOffset = false }: TopBarProps) {
const pathname = usePathname();
const [now, setNow] = useState<Date | null>(null);
const [shortcut, setShortcut] = useState<'⌘K' | 'Ctrl K'>('⌘K');
+ const { userRole } = useTenant();
// Update the clock every second on the client only (avoids hydration drift).
useEffect(() => {
@@ -151,8 +156,40 @@ export function TopBar({ demoOffset = false }: TopBarProps) {
</button>
</div>
- {/* Right: clock, theme toggle, notifications, user */}
- <div className="flex items-center gap-4">
+ {/* Right: time window, tenant, role badge, clock, theme toggle, notifications, user */}
+ <div className="flex items-center gap-3">
+ {/*
+ v1.5 W4: Global time-window selector. Lives next to the tenant
+ switcher in the TopBar so every page reads from the same context.
+ Hidden on small screens to keep the bar from wrapping.
+ */}
+ <div className="hidden md:block">
+ <TimeWindowSelector />
+ </div>
+
+ {/*
+ v1.5 W5: Tenant switcher. For MSSP parents this is a dropdown of
+ tenants they can pivot into; for standalone tenants this collapses
+ into a read-only badge.
+ */}
+ <div className="hidden md:block">
+ <TenantSwitcher />
+ </div>
+
+ {/*
+ v1.5 W5: Role badge — surfaces the operator's effective role
+ (analyst / analyst-lead / admin / viewer / mssp-admin) so
+ permission boundaries are visible at a glance. The badge intentionally
+ renders even when userRole is null so the slot doesn't reflow as it
+ resolves.
+ */}
+ <div className="hidden lg:block">
+ <RoleBadge role={userRole} />
+ </div>
+
+ {/* Divider between v1.5 console context and existing top-bar chrome. */}
+ <div className="hidden lg:block h-6 w-px bg-surface-border" aria-hidden />
+
{/* Clock */}
<div className="text-right hidden lg:block">
<p className="text-sm font-mono text-fg-secondary" suppressHydrationWarning>{timeStr}</p>
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index ae853b737..9a6eb3ba7 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -90,6 +90,53 @@ export const API_BASES = {
export const DEFAULT_TENANT_ID = TENANT_ID;
+// ─── Active tenant (W5 — tenant switcher) ───────────────────────────────────
+//
+// The console used to ship every request with the env-derived TENANT_ID. With
+// the tenant switcher, MSSP parents and analysts who carry credentials for
+// multiple tenants need a way to flip the `X-Tenant-Id` header at runtime.
+// We expose three building blocks the TenantContext + switcher consume:
+//
+// - ACTIVE_TENANT_KEY: localStorage key for the override
+// - getActiveTenantId(): read precedence — override → cached user → env
+// - setActiveTenantId(): persist (or clear) the override
+//
+// `request()` calls `getActiveTenantId()` on every call so a tenant flip
+// applies to the very next fetch without needing a page reload. The env var
+// `NEXT_PUBLIC_TENANT_ID` remains the floor so demo and SSR contexts keep
+// working when no user is logged in.
+
+export const ACTIVE_TENANT_KEY = 'aisoc.activeTenantId';
+
+export function getActiveTenantId(): string {
+ if (typeof window === 'undefined') return TENANT_ID;
+ try {
+ const override = window.localStorage.getItem(ACTIVE_TENANT_KEY);
+ if (override) return override;
+ const raw = window.localStorage.getItem(AUTH_USER_KEY);
+ if (raw) {
+ const user = JSON.parse(raw) as { tenant_id?: string };
+ if (user.tenant_id) return user.tenant_id;
+ }
+ } catch {
+ /* localStorage unavailable / malformed payload — fall through */
+ }
+ return TENANT_ID;
+}
+
+export function setActiveTenantId(tenantId: string | null): void {
+ if (typeof window === 'undefined') return;
+ try {
+ if (tenantId) {
+ window.localStorage.setItem(ACTIVE_TENANT_KEY, tenantId);
+ } else {
+ window.localStorage.removeItem(ACTIVE_TENANT_KEY);
+ }
+ } catch {
+ /* private-mode quota errors — surface choice is in-memory only */
+ }
+}
+
interface FetchOptions extends RequestInit {
params?: Record<string, string | number | boolean | undefined>;
baseUrl?: string;
@@ -124,7 +171,9 @@ async function request<T>(path: string, options: FetchOptions = {}): Promise<T>
const headers: HeadersInit = {
'Content-Type': 'application/json',
- 'X-Tenant-Id': TENANT_ID,
+ // Resolve at call-time so the tenant switcher takes effect on the very
+ // next fetch (no full page reload needed).
+ 'X-Tenant-Id': getActiveTenantId(),
...fetchOptions.headers,
};
@@ -299,6 +348,55 @@ export const authApi = {
},
};
+// ─── Tenants & MSSP ─────────────────────────────────────────────────────────
+//
+// The W5 tenant switcher needs to know:
+// - which tenant the user is currently authenticated against
+// (`tenants/me` — single canonical source of truth, includes display name)
+// - what other tenants they can flip to
+// (`mssp/children` for MSSP parents — returns *real* child tenants from
+// the DB, not the mock list used by the parent dashboard)
+//
+// Failures are caught by the caller — the switcher gracefully degrades to a
+// single-tenant role badge when these endpoints 401/404 (e.g. a tenant user
+// who isn't an MSSP parent will not have any children but still has /me).
+
+export interface MyTenant {
+ id: string;
+ name: string;
+ // mssp_role and parent_tenant_id come from the lightweight identity
+ // endpoint and are present for any tenant (null for standalone tenants).
+ mssp_role?: 'parent' | 'child' | null;
+ parent_tenant_id?: string | null;
+}
+
+export interface ChildTenant {
+ id: string;
+ name: string;
+ mssp_role: string;
+ created_at?: string;
+}
+
+export const tenantsApi = {
+ /**
+ * Lightweight tenant identity for the SOC console TopBar.
+ *
+ * Uses `/api/v1/tenants/me/identity` (any authenticated user) instead of
+ * `/api/v1/tenants/me` (requires `settings:read`) so analyst/viewer roles
+ * can render the tenant pill and role badge without leaking plan or
+ * settings configuration.
+ */
+ async me(): Promise<MyTenant> {
+ return request<MyTenant>('/api/v1/tenants/me/identity');
+ },
+};
+
+export const msspApi = {
+ async listChildren(): Promise<ChildTenant[]> {
+ return request<ChildTenant[]>('/api/v1/mssp/children');
+ },
+};
+
// ─── Alerts ─────────────────────────────────────────────────────────────────
export type AlertSeverity = 'critical' | 'high' | 'medium' | 'low' | 'info';
diff --git a/apps/web/src/lib/timeWindow.ts b/apps/web/src/lib/timeWindow.ts
new file mode 100644
index 000000000..de62e1165
--- /dev/null
+++ b/apps/web/src/lib/timeWindow.ts
@@ -0,0 +1,72 @@
+/**
+ * Global time-window primitives (W4).
+ *
+ * The console used to scatter ad-hoc `'24h'` strings, ad-hoc `'7d'`
+ * selectors, and `hours_back: 24` query params across every dashboard,
+ * which meant the Operations view could be showing "last 7 days" while
+ * the SLA tile next to it was hard-coded to "last 24 hours". That
+ * inconsistency confused operators and broke any honest read of pipeline
+ * health.
+ *
+ * This module defines the single canonical set of windows the console
+ * supports, plus the (URL-stable) IDs we'll persist in user prefs and
+ * write into query params. The TimeWindowContext + TimeWindowSelector
+ * both consume these — no new ad-hoc windows should be added here
+ * without thinking through which API endpoints can actually serve them.
+ */
+
+export type TimeWindow = '1h' | '24h' | '7d' | '30d';
+
+/** Ordered tuple drives the dropdown render order (left → right, shortest → longest). */
+export const TIME_WINDOWS: readonly TimeWindow[] = ['1h', '24h', '7d', '30d'] as const;
+
+/** Whatever the user has not chosen anything yet — keep matching the legacy default. */
+export const DEFAULT_TIME_WINDOW: TimeWindow = '24h';
+
+/** Short label used in tight chrome (e.g. the TopBar pill). */
+export const TIME_WINDOW_SHORT_LABEL: Record<TimeWindow, string> = {
+ '1h': '1h',
+ '24h': '24h',
+ '7d': '7d',
+ '30d': '30d',
+};
+
+/** Long label used in dropdown menus and tooltips. */
+export const TIME_WINDOW_LONG_LABEL: Record<TimeWindow, string> = {
+ '1h': 'Last hour',
+ '24h': 'Last 24 hours',
+ '7d': 'Last 7 days',
+ '30d': 'Last 30 days',
+};
+
+/** Hours represented by each window (used by `hours_back=` query params). */
+export const TIME_WINDOW_HOURS: Record<TimeWindow, number> = {
+ '1h': 1,
+ '24h': 24,
+ '7d': 24 * 7,
+ '30d': 24 * 30,
+};
+
+/** Milliseconds — useful for computing relative "since" timestamps client-side. */
+export const TIME_WINDOW_MS: Record<TimeWindow, number> = {
+ '1h': 60 * 60 * 1000,
+ '24h': 24 * 60 * 60 * 1000,
+ '7d': 7 * 24 * 60 * 60 * 1000,
+ '30d': 30 * 24 * 60 * 60 * 1000,
+};
+
+/** Type guard — anything we pull off localStorage or URL params should pass through this. */
+export function isTimeWindow(value: unknown): value is TimeWindow {
+ return value === '1h' || value === '24h' || value === '7d' || value === '30d';
+}
+
+/**
+ * Convert a window into the ISO "since" timestamp some endpoints prefer.
+ * Caller passes `now` for deterministic tests; defaults to `Date.now()`.
+ */
+export function sinceFor(window: TimeWindow, now: number = Date.now()): string {
+ return new Date(now - TIME_WINDOW_MS[window]).toISOString();
+}
+
+/** localStorage key for the user's last-chosen window. */
+export const TIME_WINDOW_STORAGE_KEY = 'aisoc.timeWindow';
diff --git a/apps/web/src/test/a11y.test.tsx b/apps/web/src/test/a11y.test.tsx
index daec28425..66d23d90d 100644
--- a/apps/web/src/test/a11y.test.tsx
+++ b/apps/web/src/test/a11y.test.tsx
@@ -90,6 +90,14 @@ vi.mock('@/lib/api', () => ({
sendMessage: vi.fn(),
getHistory: vi.fn(() => Promise.resolve([])),
},
+ tenantsApi: {
+ me: vi.fn(() => Promise.reject(new Error('unauthenticated'))),
+ },
+ msspApi: {
+ listChildren: vi.fn(() => Promise.resolve([])),
+ },
+ getActiveTenantId: vi.fn(() => ''),
+ setActiveTenantId: vi.fn(),
}));
// Sidebar reads version from package.json — mock it so the import doesn't
@@ -104,6 +112,8 @@ import { StartHero } from '../components/onboarding/StartHero';
import { ThemeToggle } from '../components/theme/ThemeToggle';
import { ThemeProvider } from '../components/theme/ThemeProvider';
import { TopBar } from '../components/layout/TopBar';
+import { TimeWindowProvider } from '../components/layout/TimeWindowProvider';
+import { TenantProvider } from '../components/layout/TenantProvider';
import { Sidebar } from '../components/layout/Sidebar';
import { EmptyState } from '../components/ui/EmptyState';
import { CopilotDock } from '../components/copilot/CopilotDock';
@@ -148,7 +158,11 @@ describe('WCAG 2.1 AA — high-traffic surfaces', () => {
pathnameMock.mockReturnValue('/dashboard');
const { container } = render(
<ThemeProvider>
- <TopBar />
+ <TimeWindowProvider>
+ <TenantProvider>
+ <TopBar />
+ </TenantProvider>
+ </TimeWindowProvider>
</ThemeProvider>,
);
const results = await axe(container, axeOptions);
diff --git a/apps/web/src/test/setup.ts b/apps/web/src/test/setup.ts
index 18644d019..552b69282 100644
--- a/apps/web/src/test/setup.ts
+++ b/apps/web/src/test/setup.ts
@@ -62,3 +62,41 @@ if (typeof window !== 'undefined' && !('ResizeObserver' in window)) {
// @ts-expect-error — assigning a stub for the same reason as above.
window.ResizeObserver = ResizeObserverStub;
}
+
+// localStorage — the jsdom build wired up in this repo exposes `window.localStorage`
+// as an object but without `getItem`/`setItem` methods, which breaks any component
+// that persists user preferences (v1.5 W4 TimeWindowProvider, W5 TenantProvider,
+// WS-F1 theme, etc.). Install a small in-memory Storage shim so tests can read and
+// write keys exactly like real browser code. We also re-install it before every
+// test via the `afterEach` cleanup hook in case a test installs `vi.spyOn` mocks
+// on `Storage.prototype` and forgets to restore them.
+function installStorageShim() {
+ if (typeof window === 'undefined') return;
+ const store = new Map<string, string>();
+ const shim: Storage = {
+ get length() {
+ return store.size;
+ },
+ clear: () => {
+ store.clear();
+ },
+ getItem: (key: string) => (store.has(key) ? (store.get(key) as string) : null),
+ key: (index: number) => Array.from(store.keys())[index] ?? null,
+ removeItem: (key: string) => {
+ store.delete(key);
+ },
+ setItem: (key: string, value: string) => {
+ store.set(key, String(value));
+ },
+ };
+ Object.defineProperty(window, 'localStorage', {
+ configurable: true,
+ value: shim,
+ });
+ Object.defineProperty(window, 'sessionStorage', {
+ configurable: true,
+ value: shim,
+ });
+}
+
+installStorageShim();
diff --git a/services/api/app/api/v1/endpoints/tenants.py b/services/api/app/api/v1/endpoints/tenants.py
index 48ac2919d..0e8f2e860 100644
--- a/services/api/app/api/v1/endpoints/tenants.py
+++ b/services/api/app/api/v1/endpoints/tenants.py
@@ -15,6 +15,22 @@ from app.models.tenant import Tenant, User
router = APIRouter(prefix="/tenants", tags=["tenants"])
+class TenantHeaderResponse(BaseModel):
+ """Minimal tenant identity payload — safe for *any* authenticated user.
+
+ Used by the SOC console TopBar to render the tenant switcher and role
+ badge (Workstream 5). Intentionally excludes `plan`, `settings`, and
+ `limits` so it does not leak privileged config to viewer/analyst roles.
+ """
+
+ id: uuid.UUID
+ name: str
+ mssp_role: str | None
+ parent_tenant_id: uuid.UUID | None
+
+ model_config = {"from_attributes": True}
+
+
class TenantResponse(BaseModel):
id: uuid.UUID
name: str
@@ -23,6 +39,8 @@ class TenantResponse(BaseModel):
is_active: bool
settings: dict
limits: dict
+ mssp_role: str | None = None
+ parent_tenant_id: uuid.UUID | None = None
created_at: datetime
model_config = {"from_attributes": True}
@@ -58,12 +76,31 @@ class UpdateTenantSettingsRequest(BaseModel):
settings: dict = {}
[email protected]("/me/identity", response_model=TenantHeaderResponse)
+async def get_my_tenant_identity(
+ current_user: AuthUser,
+ db: DBSession,
+) -> TenantHeaderResponse:
+ """Get minimal tenant identity for the current user.
+
+ Returns only `id`, `name`, `mssp_role`, and `parent_tenant_id`. This is
+ safe for **any** authenticated user (analyst, viewer, responder, etc.)
+ because it does not expose plan, settings, or limits. Used by the SOC
+ console TopBar to render the tenant switcher pill and role badge.
+ """
+ result = await db.execute(select(Tenant).where(Tenant.id == current_user.tenant_id))
+ tenant = result.scalar_one_or_none()
+ if tenant is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Tenant not found")
+ return TenantHeaderResponse.model_validate(tenant)
+
+
@router.get("/me", response_model=TenantResponse)
async def get_my_tenant(
current_user: Annotated[AuthUser, Depends(require_permission("settings:read"))],
db: DBSession,
) -> TenantResponse:
- """Get the current user's tenant details."""
+ """Get the current user's tenant details (full config — requires settings:read)."""
result = await db.execute(select(Tenant).where(Tenant.id == current_user.tenant_id))
tenant = result.scalar_one_or_none()
if tenant is None:
diff --git a/services/api/tests/test_tenant_identity_endpoint.py b/services/api/tests/test_tenant_identity_endpoint.py
new file mode 100644
index 000000000..8f9ebe325
--- /dev/null
+++ b/services/api/tests/test_tenant_identity_endpoint.py
@@ -0,0 +1,148 @@
+"""Unit tests for the tenant identity endpoint (Workstream 5 — SOC console parity).
+
+The ``GET /api/v1/tenants/me/identity`` handler returns a minimal projection
+of the current user's tenant (id, name, mssp_role, parent_tenant_id) without
+requiring the ``settings:read`` permission. It is the data source for the
+TopBar tenant switcher pill and role badge in the SOC console.
+
+What we exercise here:
+
+* Happy path: a known tenant row maps cleanly to ``TenantHeaderResponse``
+ with every privileged field (``plan``, ``settings``, ``limits``) omitted.
+* MSSP parent + child both round-trip — the ``mssp_role`` and
+ ``parent_tenant_id`` fields make it through ``model_validate``.
+* Missing tenant raises ``HTTPException`` 404 instead of leaking ``None``
+ or a 500.
+* The endpoint does not require ``settings:read`` (verified by *not*
+ threading any permission stub — the test calls the function directly).
+
+Like the other endpoint tests in this folder
+(``test_llm_credentials_endpoint.py``, ``test_saved_views_endpoint.py``), we
+avoid spinning up the full FastAPI app + Postgres. We stub the DB session
+with a ``MagicMock`` and assert the contract the handler must keep.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from app.api.v1.endpoints.tenants import (
+ TenantHeaderResponse,
+ get_my_tenant_identity,
+)
+from app.models.tenant import Tenant
+from fastapi import HTTPException
+
+
+def _build_tenant(
+ *,
+ tenant_id: uuid.UUID | None = None,
+ name: str = "Acme Corp",
+ mssp_role: str | None = None,
+ parent_tenant_id: uuid.UUID | None = None,
+) -> Tenant:
+ """Return a hydrated ``Tenant`` ORM instance (no DB session needed)."""
+
+ tenant = Tenant()
+ tenant.id = tenant_id or uuid.uuid4()
+ tenant.name = name
+ tenant.slug = "acme-corp"
+ tenant.plan = "enterprise"
+ tenant.is_active = True
+ tenant.settings = {"super_secret": "should-not-leak"}
+ tenant.limits = {"alerts_per_day": 100_000}
+ tenant.mssp_role = mssp_role
+ tenant.parent_tenant_id = parent_tenant_id
+ tenant.created_at = datetime.now(UTC)
+ tenant.updated_at = datetime.now(UTC)
+ return tenant
+
+
+def _build_user(tenant_id: uuid.UUID) -> SimpleNamespace:
+ """Minimal CurrentUser stand-in. The endpoint only reads ``tenant_id``."""
+ return SimpleNamespace(tenant_id=tenant_id, user_id=uuid.uuid4(), role="soc_analyst")
+
+
+def _build_db(tenant: Tenant | None) -> MagicMock:
+ """Build an AsyncMock-backed DB session whose query returns ``tenant``."""
+ db = MagicMock()
+ result = MagicMock()
+ result.scalar_one_or_none.return_value = tenant
+ db.execute = AsyncMock(return_value=result)
+ return db
+
+
+async def test_identity_returns_minimal_projection() -> None:
+ """Happy path: standalone tenant — only the four allow-listed fields make it out."""
+ tid = uuid.uuid4()
+ tenant = _build_tenant(tenant_id=tid, name="Acme Corp")
+ user = _build_user(tenant_id=tid)
+ db = _build_db(tenant)
+
+ out = await get_my_tenant_identity(current_user=user, db=db)
+
+ assert isinstance(out, TenantHeaderResponse)
+ assert out.id == tid
+ assert out.name == "Acme Corp"
+ assert out.mssp_role is None
+ assert out.parent_tenant_id is None
+
+ # Privileged fields must NOT be exposed on this endpoint.
+ payload = out.model_dump()
+ for forbidden in ("plan", "settings", "limits", "slug", "is_active"):
+ assert forbidden not in payload, f"{forbidden!r} leaked into TenantHeaderResponse"
+
+
+async def test_identity_returns_mssp_parent() -> None:
+ """MSSP parent: ``mssp_role='parent'`` makes it through verbatim."""
+ tid = uuid.uuid4()
+ tenant = _build_tenant(tenant_id=tid, name="Acme MSSP", mssp_role="parent")
+ user = _build_user(tenant_id=tid)
+ db = _build_db(tenant)
+
+ out = await get_my_tenant_identity(current_user=user, db=db)
+
+ assert out.id == tid
+ assert out.name == "Acme MSSP"
+ assert out.mssp_role == "parent"
+ assert out.parent_tenant_id is None
+
+
+async def test_identity_returns_mssp_child_with_parent_link() -> None:
+ """MSSP child: parent linkage is preserved so the UI can render the breadcrumb."""
+ parent_id = uuid.uuid4()
+ tid = uuid.uuid4()
+ tenant = _build_tenant(
+ tenant_id=tid,
+ name="Acme Subsidiary A",
+ mssp_role="child",
+ parent_tenant_id=parent_id,
+ )
+ user = _build_user(tenant_id=tid)
+ db = _build_db(tenant)
+
+ out = await get_my_tenant_identity(current_user=user, db=db)
+
+ assert out.id == tid
+ assert out.mssp_role == "child"
+ assert out.parent_tenant_id == parent_id
+
+
+async def test_identity_raises_404_when_tenant_missing() -> None:
+ """If the JWT references a tenant that no longer exists, we surface a clean 404."""
+ user = _build_user(tenant_id=uuid.uuid4())
+ db = _build_db(None)
+
+ with pytest.raises(HTTPException) as excinfo:
+ await get_my_tenant_identity(current_user=user, db=db)
+
+ assert excinfo.value.status_code == 404
+ assert "Tenant not found" in excinfo.value.detail