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(web,docs): WS-F1 — semantic theme tokens + ThemeProvider + light theme

Beenu Arora15d237383a9a
diff --git a/apps/docs/docs/operations/theming.md b/apps/docs/docs/operations/theming.md
new file mode 100644
index 000000000..b2aba68ed
--- /dev/null
+++ b/apps/docs/docs/operations/theming.md
@@ -0,0 +1,104 @@
+# Theming (light & dark)
+
+The AiSOC console ships dark-by-default and exposes a tri-state theme toggle in
+the top bar (**dark → light → system → dark**). Users who pick **system** get
+their OS-level `prefers-color-scheme` rendered, with live updates if they flip
+their OS theme without reloading.
+
+This page is for operators and contributors who want to know how the theme
+system is wired together, why some surfaces deliberately don't flip, and how to
+migrate a new component to the semantic palette.
+
+## Overview
+
+The theme story is intentionally minimal: one CSS-variable layer, one Tailwind
+config, one `ThemeProvider`, one bootstrap script. There is no runtime CSS-in-JS
+and no per-component theme branching.
+
+| Layer | File | Purpose |
+| --- | --- | --- |
+| Tokens | `apps/web/src/app/globals.css` | Defines `--surface-*`, `--fg-*`, etc. for both `:root` / `[data-theme="dark"]` and `[data-theme="light"]`. |
+| Tailwind | `apps/web/tailwind.config.ts` | Maps `bg-surface-*` / `text-fg-*` utilities onto the CSS variables so they flip automatically. |
+| Provider | `apps/web/src/components/theme/ThemeProvider.tsx` | React context that owns the user's preference, persists it to `localStorage`, and listens to OS-level theme changes. |
+| Bootstrap | `apps/web/src/components/theme/themeScript.ts` | Render-blocking inline script that resolves the theme **before first paint** to avoid FOUC. |
+| Toggle | `apps/web/src/components/theme/ThemeToggle.tsx` | Tri-state button mounted in `TopBar`. |
+
+## How it flips
+
+1. The bootstrap script (rendered as the first child of `<body>`) reads
+ `localStorage["aisoc-theme"]`, defaults to `dark`, resolves `system` against
+ `prefers-color-scheme`, and writes `data-theme` + `color-scheme` onto the
+ `<html>` element.
+2. `<html data-theme="...">` switches which CSS-variable block is in scope.
+3. Tailwind utilities like `bg-surface-card` are compiled to
+ `background-color: var(--surface-card)`, so they automatically pick up the
+ new value — no class swap required.
+4. `ThemeProvider` (mounted in the root layout) keeps React state in sync with
+ the DOM and provides `useTheme()` for components that need to render
+ conditionally.
+
+## Token reference
+
+Use these tokens for chrome surfaces. Severity, status, and brand colours are
+deliberately **theme-agnostic** so a *high-severity* alert looks the same in
+both themes.
+
+| Token | Purpose |
+| --- | --- |
+| `bg-surface-base` | Page background (App shell, marketing root). |
+| `bg-surface-raised` | Topbar, sticky chrome. |
+| `bg-surface-card` | Cards, panels, drawer bodies. |
+| `bg-surface-hover` | Hover state on rows / list items. |
+| `bg-surface-subtle` | Subtle inset surfaces (e.g. code blocks, JSON viewers). |
+| `border-surface-border` | Container borders. |
+| `border-surface-divider` | Separator lines inside cards. |
+| `text-fg-primary` | Body / heading copy. |
+| `text-fg-secondary` | Paragraph copy. |
+| `text-fg-muted` | Captions, labels. |
+| `text-fg-subtle` | Timestamps, helper text. |
+| `text-fg-inverse` | Text on light buttons (rare). |
+
+## Migrating a component
+
+1. Replace `bg-gray-900` / `bg-gray-950` / `bg-[#…]` chrome backgrounds with
+ `bg-surface-card` (or `bg-surface-raised` for sticky chrome).
+2. Replace `text-white` / `text-gray-200` / `text-gray-300` with `text-fg-primary`
+ or `text-fg-secondary`. Keep `text-white` only on coloured backgrounds
+ (e.g. brand buttons, severity chips) where contrast is preserved.
+3. Replace `border-gray-700` / `border-gray-800` with `border-surface-border`.
+4. Leave `bg-brand-*`, `bg-severity-*`, `text-emerald-*`, etc. **as-is**.
+ Brand and severity tokens are intentionally theme-locked.
+5. Run `pnpm tsc --noEmit` and visually verify both themes via the toggle.
+
+If a surface genuinely shouldn't flip (marketing hero with a fixed gradient,
+in-canvas DAG visualisation tuned for dark mode), wrap it in a
+`data-theme="dark"` (or `="light"`) boundary instead of migrating every
+decorative class. The marketing landing in `apps/web/src/app/page.tsx` does
+exactly this.
+
+## Locked surfaces (today)
+
+These surfaces are deliberately dark-only in v1 and require a follow-up to
+become themable. Each one is wrapped in a `data-theme="dark"` boundary so the
+toggle in the chrome doesn't make them look broken.
+
+| Surface | Why dark-locked | Tracked under |
+| --- | --- | --- |
+| `/` marketing landing | Hero/Architecture/Features ride a fixed dark gradient. | WS-F1 follow-up |
+| Playbook DAG canvas | `@xyflow/react` colors are tuned for dark mode. | WS-F1 follow-up |
+
+## Why the bootstrap script is render-blocking
+
+A pure-React theme provider has to wait for hydration before it can apply the
+saved theme, which means the first frame is always rendered with the default.
+Buyers in light mode would see a flash of dark before the React tree mounts —
+exactly the failure mode WS-F1 was meant to eliminate. The synchronous inline
+script runs *before* the browser paints, costs ~600 bytes after gzip, and is
+wrapped in `try/catch` so iOS private-browsing `localStorage` failures fall
+back to dark instead of crashing the page.
+
+## Accessibility
+
+Both palettes are tuned to meet **WCAG AA** for body copy and large text. The
+WCAG AA audit (WS-F2) wires `axe-core` into the test suite to catch
+regressions. See `axe-core` test files under `apps/web/src/test/a11y/`.
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index 4178d7257..1b309634f 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -57,6 +57,7 @@ const sidebars: SidebarsConfig = {
"operations/security",
"operations/credentials",
"operations/airgap",
+ "operations/theming",
"operations/upgrades",
"operations/troubleshooting",
"operations/faq",
diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css
index 0fb6f9aea..9fa3087bc 100644
--- a/apps/web/src/app/globals.css
+++ b/apps/web/src/app/globals.css
@@ -3,9 +3,90 @@
@source "../../src";
@source "../../../../packages/ui/src";
-:root {
- --background: #0a0d14;
- --foreground: #e2e8f0;
+/*
+ * ─────────────────────── Theme tokens (WS-F1) ───────────────────────
+ *
+ * The console ships dark-by-default; light mode is opt-in via the user
+ * preference toggle (mounted in `TopBar`) which writes either:
+ * <html data-theme="dark">
+ * <html data-theme="light">
+ * <html data-theme="system"> ← resolved into "dark" or "light" by the
+ * ThemeProvider before paint.
+ *
+ * The variables below cover the chrome surfaces a buyer encounters first
+ * (body, AppShell, TopBar, Sidebar, marketing landing, dashboard welcome,
+ * playbook gallery). The rest of the app is still dark-only by design —
+ * see `apps/docs/docs/operations/theming.md` for the migration playbook
+ * we use to roll surfaces over without a flag day.
+ *
+ * The tokens are referenced directly by `tailwind.config.ts` so that any
+ * Tailwind utility built on these palettes (e.g. `bg-surface-card`,
+ * `text-fg-secondary`, `border-surface-divider`) flips automatically
+ * when `data-theme` changes.
+ */
+
+:root,
+[data-theme="dark"] {
+ /* Surfaces — page bg up through hovered card */
+ --surface-base: #0a0d14;
+ --surface-raised: #11151f;
+ --surface-card: #141926;
+ --surface-hover: #1a2030;
+ --surface-subtle: #0d1119;
+
+ /* Borders / dividers — slate-400 with low alpha so they tint the surface
+ instead of cutting hard lines. */
+ --surface-border: rgba(148, 163, 184, 0.12);
+ --surface-divider: rgba(148, 163, 184, 0.08);
+
+ /* Foregrounds — high → muted */
+ --fg-primary: #e2e8f0; /* slate-200, body text default */
+ --fg-secondary: #cbd5e1; /* slate-300, paragraph copy */
+ --fg-muted: #9ca3af; /* gray-400, captions, labels */
+ --fg-subtle: #6b7280; /* gray-500, timestamps, helper text */
+ --fg-inverse: #0f172a; /* slate-900, text on light buttons */
+
+ /* Compatibility: legacy --background / --foreground used by `body`. */
+ --background: var(--surface-base);
+ --foreground: var(--fg-primary);
+
+ /* Selection — slightly brand-tinted for both themes. */
+ --selection-bg: rgba(59, 130, 246, 0.35);
+ --selection-fg: #ffffff;
+
+ /* Scrollbar — semi-transparent so the same rule works in both themes. */
+ --scrollbar-thumb: rgba(255, 255, 255, 0.1);
+ --scrollbar-thumb-hover: rgba(255, 255, 255, 0.2);
+}
+
+[data-theme="light"] {
+ /* Surfaces — paper-white base, slightly tinted raised/card so cards have
+ definition without a hard shadow. */
+ --surface-base: #f8fafc; /* slate-50, page bg */
+ --surface-raised: #ffffff; /* card containers */
+ --surface-card: #ffffff; /* same as raised, kept distinct so we
+ can introduce a subtle tint later
+ without touching consumers */
+ --surface-hover: #eef2f7; /* slate-100/200, hovered rows */
+ --surface-subtle: #f1f5f9; /* slate-100, deeper tint */
+
+ --surface-border: rgba(15, 23, 42, 0.12);
+ --surface-divider: rgba(15, 23, 42, 0.06);
+
+ --fg-primary: #0f172a; /* slate-900 */
+ --fg-secondary: #334155; /* slate-700 */
+ --fg-muted: #64748b; /* slate-500 */
+ --fg-subtle: #94a3b8; /* slate-400 */
+ --fg-inverse: #f8fafc;
+
+ --background: var(--surface-base);
+ --foreground: var(--fg-primary);
+
+ --selection-bg: rgba(37, 99, 235, 0.18);
+ --selection-fg: #0f172a;
+
+ --scrollbar-thumb: rgba(15, 23, 42, 0.18);
+ --scrollbar-thumb-hover: rgba(15, 23, 42, 0.32);
}
* {
@@ -14,6 +95,14 @@
html {
scroll-behavior: smooth;
+ /* Tells form controls (date pickers, scroll bars on Safari, etc.) which
+ theme to render. The ThemeProvider keeps `data-theme` in sync, but
+ `color-scheme` lets the UA chrome match without the toggle running. */
+ color-scheme: dark;
+}
+
+[data-theme="light"] {
+ color-scheme: light;
}
body {
@@ -24,6 +113,11 @@ body {
-moz-osx-font-smoothing: grayscale;
}
+::selection {
+ background: var(--selection-bg);
+ color: var(--selection-fg);
+}
+
/* Scrollbar */
::-webkit-scrollbar {
width: 6px;
@@ -35,12 +129,12 @@ body {
}
::-webkit-scrollbar-thumb {
- background: rgba(255, 255, 255, 0.1);
+ background: var(--scrollbar-thumb);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
- background: rgba(255, 255, 255, 0.2);
+ background: var(--scrollbar-thumb-hover);
}
/* Focus */
diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx
index 2474c6d38..46a087bc3 100644
--- a/apps/web/src/app/layout.tsx
+++ b/apps/web/src/app/layout.tsx
@@ -3,6 +3,8 @@ import { Inter, JetBrains_Mono } from 'next/font/google';
import { Toaster } from 'react-hot-toast';
import './globals.css';
import { PwaBootstrap } from '@/components/pwa/PwaBootstrap';
+import { ThemeProvider } from '@/components/theme/ThemeProvider';
+import { themeBootstrapScript } from '@/components/theme/themeScript';
import { DISCOVERY_KEYWORDS, getPublicSiteUrl } from '@/lib/site';
const inter = Inter({
@@ -163,33 +165,51 @@ export default function RootLayout({
children: React.ReactNode;
}) {
return (
- <html lang="en" className={`${inter.variable} ${jetbrainsMono.variable}`}>
- <body className="bg-[#0a0d14] text-gray-100 antialiased">
+ // Default to `data-theme="dark"` for SSR so that the markup React sends
+ // matches what the bootstrap script will write before hydration. The
+ // bootstrap script (rendered first thing inside <body>) flips this to
+ // light/system if the user previously chose so, before any pixels are
+ // painted — that's why we don't see a flash.
+ <html
+ lang="en"
+ data-theme="dark"
+ className={`${inter.variable} ${jetbrainsMono.variable}`}
+ >
+ <body className="bg-surface-base text-fg-primary antialiased">
+ <script
+ // eslint-disable-next-line react/no-danger -- pre-hydration theme bootstrap
+ dangerouslySetInnerHTML={{ __html: themeBootstrapScript }}
+ />
<script
type="application/ld+json"
// eslint-disable-next-line react/no-danger -- JSON-LD for SEO crawlers
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
<PwaBootstrap />
- {children}
- <Toaster
- position="bottom-right"
- toastOptions={{
- duration: 4000,
- style: {
- background: '#11151f',
- color: '#e2e8f0',
- border: '1px solid rgba(59,130,246,0.2)',
- fontSize: '0.875rem',
- },
- success: {
- iconTheme: { primary: '#22c55e', secondary: '#0a0d14' },
- },
- error: {
- iconTheme: { primary: '#ef4444', secondary: '#0a0d14' },
- },
- }}
- />
+ <ThemeProvider>
+ {children}
+ <Toaster
+ position="bottom-right"
+ toastOptions={{
+ duration: 4000,
+ // Toast styles read CSS variables so the toaster flips with
+ // the rest of the chrome. `iconTheme` only takes hex values,
+ // so we pin the brand semantic colors there.
+ style: {
+ background: 'var(--surface-raised)',
+ color: 'var(--fg-primary)',
+ border: '1px solid var(--surface-border)',
+ fontSize: '0.875rem',
+ },
+ success: {
+ iconTheme: { primary: '#22c55e', secondary: '#0a0d14' },
+ },
+ error: {
+ iconTheme: { primary: '#ef4444', secondary: '#0a0d14' },
+ },
+ }}
+ />
+ </ThemeProvider>
</body>
</html>
);
diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx
index 48b7d0159..5212d48ee 100644
--- a/apps/web/src/app/page.tsx
+++ b/apps/web/src/app/page.tsx
@@ -27,8 +27,19 @@ export const metadata: Metadata = {
};
export default function HomePage() {
+ // The marketing landing is intentionally locked to the dark palette via a
+ // nested `data-theme="dark"` boundary. The hero is built around fixed dark
+ // gradient overlays (see `StartHero`, `Architecture`, `Features`) and the
+ // copy was tuned against that backdrop. Migrating every decorative layer
+ // to themable tokens would balloon the WS-F1 diff for negligible buyer
+ // value. The console chrome (TopBar / Sidebar / AppShell) — i.e. the
+ // surfaces a buyer actually inhabits — *does* honour the toggle, which is
+ // the buyer-visible promise. See apps/docs/docs/operations/theming.md.
return (
- <main className="relative min-h-screen overflow-x-hidden bg-surface-base text-white">
+ <main
+ data-theme="dark"
+ className="relative min-h-screen overflow-x-hidden bg-surface-base text-fg-primary"
+ >
<LandingNav />
<StartHero />
<Features />
diff --git a/apps/web/src/components/dashboard/DashboardWelcome.tsx b/apps/web/src/components/dashboard/DashboardWelcome.tsx
index 4ea94a009..ebe976f1a 100644
--- a/apps/web/src/components/dashboard/DashboardWelcome.tsx
+++ b/apps/web/src/components/dashboard/DashboardWelcome.tsx
@@ -48,7 +48,7 @@ export function DashboardWelcome() {
<p className="text-xs font-semibold uppercase tracking-wider text-brand-300">
Welcome to AiSOC
</p>
- <h2 className="mt-1 text-lg font-semibold text-white">
+ <h2 className="mt-1 text-lg font-semibold text-fg-primary">
You&apos;re looking at a clean console. Here&apos;s how to make it useful.
</h2>
</div>
@@ -56,7 +56,7 @@ export function DashboardWelcome() {
type="button"
onClick={dismiss}
aria-label="Dismiss welcome message"
- className="rounded-md p-1.5 text-gray-400 transition hover:bg-white/5 hover:text-white"
+ className="rounded-md p-1.5 text-fg-muted transition hover:bg-surface-hover hover:text-fg-primary"
>
<svg viewBox="0 0 20 20" className="h-4 w-4" fill="currentColor" aria-hidden="true">
<path d="M6.28 5.22a.75.75 0 011.06 0L10 7.88l2.66-2.66a.75.75 0 111.06 1.06L11.06 8.94l2.66 2.66a.75.75 0 11-1.06 1.06L10 10l-2.66 2.66a.75.75 0 11-1.06-1.06l2.66-2.66-2.66-2.66a.75.75 0 010-1.06z" />
@@ -100,14 +100,14 @@ function Tip({
cta: { label: string; href: string };
}) {
return (
- <li className="rounded-lg border border-white/5 bg-surface-card/60 p-4">
+ <li className="rounded-lg border border-surface-border bg-surface-card/60 p-4">
<div className="flex items-center gap-2">
<span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-brand-500/20 text-xs font-bold text-brand-200">
{step}
</span>
- <h3 className="text-sm font-semibold text-white">{title}</h3>
+ <h3 className="text-sm font-semibold text-fg-primary">{title}</h3>
</div>
- <p className="mt-2 text-xs leading-relaxed text-gray-400">{body}</p>
+ <p className="mt-2 text-xs leading-relaxed text-fg-muted">{body}</p>
<Link href={cta.href} className="mt-3 inline-block text-xs font-semibold text-brand-300 hover:text-brand-200">
{cta.label}
</Link>
diff --git a/apps/web/src/components/layout/AppShell.tsx b/apps/web/src/components/layout/AppShell.tsx
index 032d9484b..822ea3d21 100644
--- a/apps/web/src/components/layout/AppShell.tsx
+++ b/apps/web/src/components/layout/AppShell.tsx
@@ -37,7 +37,7 @@ export function AppShell({ children }: AppShellProps) {
No-ops outside demo mode.
*/}
<DemoAutoLogin />
- <div className="min-h-screen bg-[#0a0d14]">
+ <div className="min-h-screen bg-surface-base">
<DemoBanner />
<Sidebar />
<div className="md:ml-60">
diff --git a/apps/web/src/components/layout/Sidebar.tsx b/apps/web/src/components/layout/Sidebar.tsx
index c2744a788..f952faabe 100644
--- a/apps/web/src/components/layout/Sidebar.tsx
+++ b/apps/web/src/components/layout/Sidebar.tsx
@@ -301,7 +301,7 @@ export function Sidebar() {
type="button"
aria-label="Open navigation"
onClick={() => setMobileOpen(true)}
- className="md:hidden fixed top-4 left-4 z-40 p-2 rounded-lg bg-gray-800/90 text-gray-300 hover:text-white"
+ className="md:hidden fixed top-4 left-4 z-40 p-2 rounded-lg bg-surface-card/90 text-fg-secondary hover:text-fg-primary"
>
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
@@ -317,25 +317,25 @@ export function Sidebar() {
)}
<aside className={clsx(
- 'fixed inset-y-0 left-0 w-60 flex flex-col bg-gray-900/95 border-r border-gray-800/60 z-40 transition-transform duration-200',
+ 'fixed inset-y-0 left-0 w-60 flex flex-col bg-surface-raised/95 border-r border-surface-border z-40 transition-transform duration-200',
mobileOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'
)}>
{/* Logo */}
- <div className="flex items-center gap-3 px-5 h-16 border-b border-gray-800/60">
- <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-blue-600/20 border border-blue-600/30 flex items-center justify-center">
- <span className="text-blue-400">
+ <div className="flex items-center gap-3 px-5 h-16 border-b border-surface-border">
+ <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-brand-600/20 border border-brand-600/30 flex items-center justify-center">
+ <span className="text-brand-400">
<ShieldIcon />
</span>
</div>
<div>
- <span className="text-white font-bold text-base tracking-tight">Ai</span>
- <span className="text-blue-400 font-bold text-base tracking-tight">SOC</span>
- <p className="text-xs text-gray-500 -mt-0.5">open-source</p>
+ <span className="text-fg-primary font-bold text-base tracking-tight">Ai</span>
+ <span className="text-brand-400 font-bold text-base tracking-tight">SOC</span>
+ <p className="text-xs text-fg-subtle -mt-0.5">open-source</p>
</div>
{/* Live indicator */}
<div className="ml-auto flex items-center gap-1">
<div className="w-1.5 h-1.5 rounded-full bg-green-400 pulse-dot" />
- <span className="text-xs text-gray-500">Live</span>
+ <span className="text-xs text-fg-subtle">Live</span>
</div>
</div>
@@ -344,7 +344,7 @@ export function Sidebar() {
{navSections.map((section, si) => (
<div key={si}>
{section.title && (
- <p className="px-3 mb-1.5 text-xs font-semibold text-gray-500 uppercase tracking-wider">
+ <p className="px-3 mb-1.5 text-xs font-semibold text-fg-subtle uppercase tracking-wider">
{section.title}
</p>
)}
@@ -359,11 +359,11 @@ export function Sidebar() {
className={clsx(
'flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-150',
active
- ? 'bg-blue-600/15 text-blue-300 border border-blue-600/20'
- : 'text-gray-400 hover:text-gray-200 hover:bg-gray-800/70'
+ ? 'bg-brand-600/15 text-brand-300 border border-brand-600/20'
+ : 'text-fg-muted hover:text-fg-secondary hover:bg-surface-hover'
)}
>
- <span className={active ? 'text-blue-400' : 'text-gray-500'}>{item.icon}</span>
+ <span className={active ? 'text-brand-400' : 'text-fg-subtle'}>{item.icon}</span>
<span>{item.label}</span>
{typeof item.badge === 'number' && item.badge > 0 && (
<span
@@ -382,15 +382,15 @@ export function Sidebar() {
</nav>
{/* Footer */}
- <div className="p-4 border-t border-gray-800/60">
- <div className="flex items-center gap-2 text-xs text-gray-600">
+ <div className="p-4 border-t border-surface-border">
+ <div className="flex items-center gap-2 text-xs text-fg-subtle">
<span className="font-mono">v{APP_VERSION}</span>
<span>·</span>
<a
href="https://github.com/beenuar/AiSOC"
target="_blank"
rel="noopener noreferrer"
- className="hover:text-gray-400 transition-colors"
+ className="hover:text-fg-muted transition-colors"
>
MIT License
</a>
diff --git a/apps/web/src/components/layout/TopBar.tsx b/apps/web/src/components/layout/TopBar.tsx
index f634cf248..fdbf96557 100644
--- a/apps/web/src/components/layout/TopBar.tsx
+++ b/apps/web/src/components/layout/TopBar.tsx
@@ -2,6 +2,7 @@
import { useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';
+import { ThemeToggle } from '@/components/theme/ThemeToggle';
// Order matters: longer/more specific paths first so startsWith() picks
// the right label for nested routes (e.g. /detection/catalog before /detection).
@@ -110,14 +111,14 @@ export function TopBar({ demoOffset = false }: TopBarProps) {
return (
<header
- className={`fixed left-60 right-0 h-16 flex items-center justify-between px-6 bg-gray-900/90 backdrop-blur-sm border-b border-gray-800/60 z-20 ${
+ className={`fixed left-60 right-0 h-16 flex items-center justify-between px-6 bg-surface-raised/90 backdrop-blur-sm border-b border-surface-border z-20 ${
demoOffset ? 'top-9' : 'top-0'
}`}
>
{/* Page title */}
<div>
- <h1 className="text-base font-semibold text-white leading-tight">{routeInfo.title}</h1>
- <p className="text-xs text-gray-500">{routeInfo.description}</p>
+ <h1 className="text-base font-semibold text-fg-primary leading-tight">{routeInfo.title}</h1>
+ <p className="text-xs text-fg-subtle">{routeInfo.description}</p>
</div>
{/* Center: command palette launcher */}
@@ -126,10 +127,10 @@ export function TopBar({ demoOffset = false }: TopBarProps) {
type="button"
onClick={openPalette}
aria-label="Open command palette"
- className="group relative flex w-full items-center gap-3 rounded-lg border border-gray-700/60 bg-gray-800/60 px-3 py-2 text-left text-sm text-gray-400 transition-all hover:border-blue-500/40 hover:bg-gray-800 focus:border-blue-500/60 focus:outline-none focus:ring-2 focus:ring-blue-500/30"
+ className="group relative flex w-full items-center gap-3 rounded-lg border border-surface-border bg-surface-card/60 px-3 py-2 text-left text-sm text-fg-muted transition-all hover:border-brand-500/40 hover:bg-surface-card focus:border-brand-500/60 focus:outline-none focus:ring-2 focus:ring-brand-500/30"
>
<svg
- className="h-4 w-4 text-gray-500 transition-colors group-hover:text-gray-300"
+ className="h-4 w-4 text-fg-subtle transition-colors group-hover:text-fg-secondary"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
@@ -141,39 +142,42 @@ export function TopBar({ demoOffset = false }: TopBarProps) {
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
/>
</svg>
- <span className="flex-1 truncate text-gray-400 group-hover:text-gray-300">
+ <span className="flex-1 truncate text-fg-muted group-hover:text-fg-secondary">
Search alerts, cases, rules, or run a command…
</span>
- <kbd className="pointer-events-none rounded bg-gray-700/60 px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-wide text-gray-300">
+ <kbd className="pointer-events-none rounded bg-surface-hover px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-wide text-fg-secondary">
{shortcut}
</kbd>
</button>
</div>
- {/* Right: clock, notifications, user */}
+ {/* Right: clock, theme toggle, notifications, user */}
<div className="flex items-center gap-4">
{/* Clock */}
<div className="text-right hidden lg:block">
- <p className="text-sm font-mono text-gray-300" suppressHydrationWarning>{timeStr}</p>
- <p className="text-xs text-gray-500" suppressHydrationWarning>{dateStr}</p>
+ <p className="text-sm font-mono text-fg-secondary" suppressHydrationWarning>{timeStr}</p>
+ <p className="text-xs text-fg-subtle" suppressHydrationWarning>{dateStr}</p>
</div>
+ {/* Theme toggle (WS-F1) */}
+ <ThemeToggle />
+
{/* Notifications */}
- <button className="relative p-1.5 text-gray-400 hover:text-gray-200 transition-colors">
+ <button className="relative p-1.5 text-fg-muted hover:text-fg-primary transition-colors">
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" />
</svg>
- <span className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full ring-2 ring-gray-900" />
+ <span className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full ring-2 ring-surface-raised" />
</button>
{/* User avatar */}
<div className="flex items-center gap-2 cursor-pointer group">
- <div className="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center text-xs font-bold text-white">
+ <div className="w-8 h-8 rounded-full bg-brand-600 flex items-center justify-center text-xs font-bold text-white">
SO
</div>
<div className="hidden lg:block">
- <p className="text-xs font-medium text-gray-300">SOC Analyst</p>
- <p className="text-xs text-gray-500">Admin</p>
+ <p className="text-xs font-medium text-fg-secondary">SOC Analyst</p>
+ <p className="text-xs text-fg-subtle">Admin</p>
</div>
</div>
</div>
diff --git a/apps/web/src/components/theme/ThemeProvider.test.tsx b/apps/web/src/components/theme/ThemeProvider.test.tsx
new file mode 100644
index 000000000..0dd1a9410
--- /dev/null
+++ b/apps/web/src/components/theme/ThemeProvider.test.tsx
@@ -0,0 +1,126 @@
+import { describe, it, expect, beforeEach, beforeAll, vi } from 'vitest';
+import { act, render, renderHook } from '@testing-library/react';
+import { ThemeProvider, useTheme } from './ThemeProvider';
+import { THEME_STORAGE_KEY } from './themeScript';
+
+/**
+ * The theme system is the buyer's first interaction with personalisation:
+ * if the toggle doesn't persist, doesn't survive remounts, or paints the
+ * wrong default, the rest of WS-F1 is academic. These tests cover the
+ * surface contract — they intentionally don't pin the visual output.
+ */
+
+// Node 24+ ships a partial built-in `localStorage` (only `removeItem`).
+// Replace it with a complete in-memory store so the suite can write *and*
+// read keys reliably. Scoped to this file so we don't change behaviour for
+// any other test that might be intentionally exercising the partial shim.
+beforeAll(() => {
+ const store = new Map<string, string>();
+ const memoryStorage: Storage = {
+ get length() {
+ return store.size;
+ },
+ clear: () => store.clear(),
+ getItem: (key) => (store.has(key) ? (store.get(key) as string) : null),
+ key: (index) => Array.from(store.keys())[index] ?? null,
+ removeItem: (key) => {
+ store.delete(key);
+ },
+ setItem: (key, value) => {
+ store.set(key, String(value));
+ },
+ };
+ Object.defineProperty(window, 'localStorage', {
+ configurable: true,
+ value: memoryStorage,
+ });
+});
+
+function setSystemPrefersLight(prefersLight: boolean) {
+ // Override the matchMedia stub from setup.ts so we can swap the OS theme.
+ window.matchMedia = (query: string) =>
+ ({
+ matches: query.includes('light') ? prefersLight : !prefersLight,
+ media: query,
+ onchange: null,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ dispatchEvent: vi.fn(() => false),
+ }) as MediaQueryList;
+}
+
+describe('ThemeProvider', () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ document.documentElement.removeAttribute('data-theme');
+ document.documentElement.removeAttribute('data-theme-preference');
+ document.documentElement.style.colorScheme = '';
+ setSystemPrefersLight(false);
+ });
+
+ it('defaults to dark when localStorage is empty', () => {
+ const { result } = renderHook(() => useTheme(), {
+ wrapper: ({ children }) => <ThemeProvider>{children}</ThemeProvider>,
+ });
+ expect(result.current.preference).toBe('dark');
+ expect(result.current.resolved).toBe('dark');
+ });
+
+ it('hydrates from localStorage when set', () => {
+ window.localStorage.setItem(THEME_STORAGE_KEY, 'light');
+ const { result } = renderHook(() => useTheme(), {
+ wrapper: ({ children }) => <ThemeProvider>{children}</ThemeProvider>,
+ });
+ expect(result.current.preference).toBe('light');
+ expect(result.current.resolved).toBe('light');
+ });
+
+ it('resolves "system" against prefers-color-scheme', () => {
+ window.localStorage.setItem(THEME_STORAGE_KEY, 'system');
+ setSystemPrefersLight(true);
+ const { result } = renderHook(() => useTheme(), {
+ wrapper: ({ children }) => <ThemeProvider>{children}</ThemeProvider>,
+ });
+ expect(result.current.preference).toBe('system');
+ expect(result.current.resolved).toBe('light');
+ });
+
+ it('toggle cycles dark → light → system → dark', () => {
+ const { result } = renderHook(() => useTheme(), {
+ wrapper: ({ children }) => <ThemeProvider>{children}</ThemeProvider>,
+ });
+
+ expect(result.current.preference).toBe('dark');
+ act(() => result.current.toggle());
+ expect(result.current.preference).toBe('light');
+ act(() => result.current.toggle());
+ expect(result.current.preference).toBe('system');
+ act(() => result.current.toggle());
+ expect(result.current.preference).toBe('dark');
+ });
+
+ it('persists the choice to localStorage and writes data-theme onto <html>', () => {
+ const { result } = renderHook(() => useTheme(), {
+ wrapper: ({ children }) => <ThemeProvider>{children}</ThemeProvider>,
+ });
+
+ act(() => result.current.setPreference('light'));
+
+ expect(window.localStorage.getItem(THEME_STORAGE_KEY)).toBe('light');
+ expect(document.documentElement.getAttribute('data-theme')).toBe('light');
+ expect(document.documentElement.getAttribute('data-theme-preference')).toBe(
+ 'light',
+ );
+ });
+
+ it('renders children inside the provider boundary', () => {
+ const { getByTestId } = render(
+ <ThemeProvider>
+ <div data-testid="probe">probe</div>
+ </ThemeProvider>,
+ );
+ expect(getByTestId('probe')).toBeInTheDocument();
+ });
+});
diff --git a/apps/web/src/components/theme/ThemeProvider.tsx b/apps/web/src/components/theme/ThemeProvider.tsx
new file mode 100644
index 000000000..4cb47d6a8
--- /dev/null
+++ b/apps/web/src/components/theme/ThemeProvider.tsx
@@ -0,0 +1,122 @@
+'use client';
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+ type ReactNode,
+} from 'react';
+import { THEME_STORAGE_KEY } from './themeScript';
+
+export type ThemePreference = 'light' | 'dark' | 'system';
+export type ResolvedTheme = 'light' | 'dark';
+
+type ThemeContextValue = {
+ /** What the user actually chose (light / dark / system). */
+ preference: ThemePreference;
+ /** What's currently painted (system → resolved against `prefers-color-scheme`). */
+ resolved: ResolvedTheme;
+ setPreference: (next: ThemePreference) => void;
+ toggle: () => void;
+};
+
+const ThemeContext = createContext<ThemeContextValue | null>(null);
+
+const SYSTEM_QUERY = '(prefers-color-scheme: light)';
+
+function readStoredPreference(): ThemePreference {
+ if (typeof window === 'undefined') return 'dark';
+ try {
+ const value = window.localStorage.getItem(THEME_STORAGE_KEY);
+ if (value === 'light' || value === 'dark' || value === 'system') return value;
+ } catch {
+ // localStorage can throw on iOS private mode etc; fall back silently.
+ }
+ return 'dark';
+}
+
+function resolvePreference(preference: ThemePreference): ResolvedTheme {
+ if (preference !== 'system') return preference;
+ if (typeof window === 'undefined') return 'dark';
+ return window.matchMedia(SYSTEM_QUERY).matches ? 'light' : 'dark';
+}
+
+function applyTheme(preference: ThemePreference, resolved: ResolvedTheme) {
+ if (typeof document === 'undefined') return;
+ const root = document.documentElement;
+ root.setAttribute('data-theme', resolved);
+ root.setAttribute('data-theme-preference', preference);
+ root.style.colorScheme = resolved;
+}
+
+export function ThemeProvider({ children }: { children: ReactNode }) {
+ // Initialised with the same default the bootstrap script uses so that the
+ // first React render matches the DOM the script wrote → no hydration
+ // mismatch. The effect below corrects it from localStorage on mount.
+ const [preference, setPreferenceState] = useState<ThemePreference>('dark');
+ const [resolved, setResolved] = useState<ResolvedTheme>('dark');
+
+ // Mount: pick up whatever the bootstrap script already wrote so the React
+ // tree agrees with the DOM. We deliberately do NOT call `applyTheme()` here
+ // — the bootstrap script already did that, and re-applying would be a
+ // no-op write that just churns React.
+ useEffect(() => {
+ const stored = readStoredPreference();
+ const next = resolvePreference(stored);
+ setPreferenceState(stored);
+ setResolved(next);
+ }, []);
+
+ // Track OS-level preference changes while the user is on `system`.
+ useEffect(() => {
+ if (preference !== 'system') return;
+ if (typeof window === 'undefined') return;
+
+ const media = window.matchMedia(SYSTEM_QUERY);
+ const handle = (event: MediaQueryListEvent) => {
+ const next: ResolvedTheme = event.matches ? 'light' : 'dark';
+ setResolved(next);
+ applyTheme('system', next);
+ };
+ media.addEventListener('change', handle);
+ return () => media.removeEventListener('change', handle);
+ }, [preference]);
+
+ const setPreference = useCallback((next: ThemePreference) => {
+ const nextResolved = resolvePreference(next);
+ setPreferenceState(next);
+ setResolved(nextResolved);
+ applyTheme(next, nextResolved);
+ try {
+ window.localStorage.setItem(THEME_STORAGE_KEY, next);
+ } catch {
+ // private mode / quota — accept that the choice doesn't persist.
+ }
+ }, []);
+
+ const toggle = useCallback(() => {
+ // Toggle cycles dark → light → system → dark so users can discover the
+ // OS-following option without an extra UI affordance.
+ setPreference(
+ preference === 'dark' ? 'light' : preference === 'light' ? 'system' : 'dark',
+ );
+ }, [preference, setPreference]);
+
+ const value = useMemo<ThemeContextValue>(
+ () => ({ preference, resolved, setPreference, toggle }),
+ [preference, resolved, setPreference, toggle],
+ );
+
+ return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
+}
+
+export function useTheme(): ThemeContextValue {
+ const ctx = useContext(ThemeContext);
+ if (!ctx) {
+ throw new Error('useTheme() must be used inside <ThemeProvider>');
+ }
+ return ctx;
+}
diff --git a/apps/web/src/components/theme/ThemeToggle.tsx b/apps/web/src/components/theme/ThemeToggle.tsx
new file mode 100644
index 000000000..3efe2b9ec
--- /dev/null
+++ b/apps/web/src/components/theme/ThemeToggle.tsx
@@ -0,0 +1,103 @@
+'use client';
+
+import { useTheme, type ThemePreference } from './ThemeProvider';
+
+type ThemeToggleProps = {
+ className?: string;
+};
+
+const PREFERENCE_LABELS: Record<ThemePreference, string> = {
+ dark: 'Dark theme',
+ light: 'Light theme',
+ system: 'Match system theme',
+};
+
+const PREFERENCE_ORDER: ThemePreference[] = ['dark', 'light', 'system'];
+
+function preferenceIcon(preference: ThemePreference) {
+ switch (preference) {
+ case 'light':
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.6}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="h-4 w-4"
+ aria-hidden
+ >
+ <circle cx="12" cy="12" r="4" />
+ <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" />
+ </svg>
+ );
+ case 'system':
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.6}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="h-4 w-4"
+ aria-hidden
+ >
+ <rect x="3" y="4" width="18" height="12" rx="2" />
+ <path d="M8 20h8M12 16v4" />
+ </svg>
+ );
+ case 'dark':
+ default:
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.6}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="h-4 w-4"
+ aria-hidden
+ >
+ <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z" />
+ </svg>
+ );
+ }
+}
+
+/**
+ * Compact tri-state toggle (dark → light → system → dark). Lives in the
+ * TopBar so a buyer can flip themes without leaving whatever screen they
+ * landed on. Keyboard-accessible (renders as a real `<button>`) and
+ * announces the next state to screen readers via `aria-label`.
+ */
+export function ThemeToggle({ className }: ThemeToggleProps) {
+ const { preference, toggle } = useTheme();
+
+ // The button advertises the *next* state because that's what activating
+ // it will do — clearer than describing the current one.
+ const idx = PREFERENCE_ORDER.indexOf(preference);
+ const next = PREFERENCE_ORDER[(idx + 1) % PREFERENCE_ORDER.length];
+ const label = `Switch to ${PREFERENCE_LABELS[next].toLowerCase()}`;
+
+ return (
+ <button
+ type="button"
+ onClick={toggle}
+ aria-label={label}
+ title={label}
+ className={
+ 'rounded-md p-1.5 text-fg-muted transition-colors hover:bg-surface-hover hover:text-fg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500/50 ' +
+ (className ?? '')
+ }
+ >
+ {preferenceIcon(preference)}
+ <span className="sr-only">{PREFERENCE_LABELS[preference]}</span>
+ </button>
+ );
+}
diff --git a/apps/web/src/components/theme/themeScript.ts b/apps/web/src/components/theme/themeScript.ts
new file mode 100644
index 000000000..504b42483
--- /dev/null
+++ b/apps/web/src/components/theme/themeScript.ts
@@ -0,0 +1,43 @@
+/**
+ * Render-blocking preamble that resolves the active theme before first
+ * paint. This is the only way to avoid a flash-of-wrong-theme — we cannot
+ * wait for React hydration because the body has already been painted by
+ * then.
+ *
+ * The script:
+ * 1. reads `localStorage["aisoc-theme"]` ("light" | "dark" | "system"),
+ * 2. resolves "system" against `prefers-color-scheme`, defaulting to
+ * "dark" when localStorage is empty (the historical default),
+ * 3. writes the resolved theme to `<html data-theme="…">`,
+ * 4. mirrors it to `<html style="color-scheme: …">` so UA chrome
+ * (scrollbars, native form controls) matches.
+ *
+ * Intentionally tiny + dependency-free + try/catch-wrapped: localStorage
+ * can throw on iOS private browsing, and we'd rather render dark than
+ * crash the page.
+ */
+export const THEME_STORAGE_KEY = 'aisoc-theme';
+
+export const themeBootstrapScript = `
+(function () {
+ try {
+ var stored = window.localStorage.getItem('${THEME_STORAGE_KEY}');
+ var preference = stored === 'light' || stored === 'dark' || stored === 'system'
+ ? stored
+ : 'dark';
+ var resolved;
+ if (preference === 'system') {
+ resolved = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
+ } else {
+ resolved = preference;
+ }
+ var root = document.documentElement;
+ root.setAttribute('data-theme', resolved);
+ root.setAttribute('data-theme-preference', preference);
+ root.style.colorScheme = resolved;
+ } catch (_) {
+ document.documentElement.setAttribute('data-theme', 'dark');
+ document.documentElement.style.colorScheme = 'dark';
+ }
+})();
+`.trim();
diff --git a/apps/web/tailwind.config.ts b/apps/web/tailwind.config.ts
index def6fc4a1..875115bc0 100644
--- a/apps/web/tailwind.config.ts
+++ b/apps/web/tailwind.config.ts
@@ -1,5 +1,18 @@
import type { Config } from 'tailwindcss';
+/*
+ * The `surface.*` and `fg.*` palettes below resolve at runtime via CSS
+ * variables defined in `src/app/globals.css`. That layer is what powers
+ * the WS-F1 light theme: when `<html data-theme="light">` is set, the
+ * variables flip and any `bg-surface-card`, `text-fg-primary`, etc. class
+ * automatically follows — no per-component branching required.
+ *
+ * `brand.*`, `severity.*`, and `status.*` are deliberately theme-agnostic
+ * (a "high"-severity alert should look the same in both themes).
+ *
+ * Migration playbook for un-themed surfaces lives in
+ * `apps/docs/docs/operations/theming.md`.
+ */
const config: Config = {
content: [
'./src/pages/**/*.{js,ts,jsx,tsx,mdx}',
@@ -25,16 +38,28 @@ const config: Config = {
800: '#1e40af',
900: '#1e3a8a',
},
- // Surface ramp for the dark console. Avoid raw `gray-*` everywhere — these
- // names communicate intent (page bg, raised card, hover, divider).
+ // Surface ramp — themeable. Resolves to dark hex values on
+ // `[data-theme="dark"]` and slate-tinted whites on
+ // `[data-theme="light"]`.
surface: {
- base: '#0a0d14',
- raised: '#11151f',
- card: '#141926',
- hover: '#1a2030',
- subtle: '#0d1119',
- border: 'rgba(148,163,184,0.12)',
- divider: 'rgba(148,163,184,0.08)',
+ base: 'var(--surface-base)',
+ raised: 'var(--surface-raised)',
+ card: 'var(--surface-card)',
+ hover: 'var(--surface-hover)',
+ subtle: 'var(--surface-subtle)',
+ border: 'var(--surface-border)',
+ divider: 'var(--surface-divider)',
+ },
+ // Foreground ramp — themeable. `fg-primary` is the highest-contrast
+ // token, `fg-subtle` is the lowest. Use these instead of raw
+ // `text-white` / `text-gray-*` on chrome so the text inverts in
+ // light mode.
+ fg: {
+ primary: 'var(--fg-primary)',
+ secondary: 'var(--fg-secondary)',
+ muted: 'var(--fg-muted)',
+ subtle: 'var(--fg-subtle)',
+ inverse: 'var(--fg-inverse)',
},
// Severity scale shared by alerts, cases, dashboard, and detection rules.
// Wired to the same hex values used in `getAlertSeverityColor()` so a