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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
An empty alerts list under a real row count, and two dashboards that invented their own numbers (#790)
Beenu Arora5b5101bfe4e3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ecc4b370e..49d16fc74 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -95,6 +95,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **The alerts list was empty on every deployment, under a row count that was+ real.** `AlertListResponse` returns the rows under `items`; the web client+ read `raw.alerts`, which is never present, so `Array.isArray(undefined)` was+ false and each page resolved to `[]` while `total` carried the true figure.+ The queue therefore rendered "1,247 alerts" above an empty table with no+ error to explain it, and an operator's most reasonable reading of that screen+ was that their estate was quiet. The client now reads `items`, still accepts+ the legacy `alerts` key the responder routes emit, and a test asserts the two+ halves of the contract against each other so they cannot drift apart again.++- **Two dashboards published fabricated security data as tenant state.**+ `DashboardView` and `SOCMetricsDashboard` both wrapped their SWR+ `fallbackData` in `demoFallback()`, which is `undefined` outside the hosted+ demo — and both then defeated that gate a few lines later with an+ unconditional `const resolved = isValid ? data : MOCK`. The mock was+ therefore exactly what rendered during first paint and after any API error,+ which for a self-hoster with an empty or unreachable backend is the whole+ session.++ What that put on screen as the reader's own numbers: a connector inventory+ they do not run (`CrowdStrike EDR`, 412 events), a MITRE tactic ranking, a+ 24-hour alert-volume curve, MTTD 1.4h / MTTR 6.2h, and an LLM spend line of+ $76.65 naming three models they had never configured. Three "vs yesterday"+ trend deltas sat beside the real alert counts as literals — `/metrics/dashboard`+ publishes no period-over-period comparison, so there was nothing to derive+ them from.++ Every panel now renders one of three honest states: real figures, an empty+ state naming what would populate it, or an error state carrying the failure+ and a retry that re-issues the request. Sample data still populates the+ hosted demo, which is the only reason it exists.+- **The lake's tenant isolation could be switched off by resolving adependency one major version higher.** `lake_sql.rewrite_for_tenant` is theonly thing separating one tenant's events from another's in ClickHouse: itdiff --git a/apps/web/src/components/dashboard/DashboardHonesty.test.tsx b/apps/web/src/components/dashboard/DashboardHonesty.test.tsxnew file mode 100644index 000000000..0526b76f7--- /dev/null+++ b/apps/web/src/components/dashboard/DashboardHonesty.test.tsx@@ -0,0 +1,233 @@+/**+ * Data-honesty gate for the two dashboards that carried ungated sample data.+ *+ * Both `DashboardView` and `SOCMetricsDashboard` already wrapped their SWR+ * `fallbackData` in `demoFallback()`, which returns `undefined` outside the+ * hosted demo. Both then defeated that gate a few lines later with an+ * unconditional `const resolved = isValid ? data : MOCK`, so the mock was+ * exactly what rendered during first paint and after any API error — the two+ * states a self-hoster with an empty or unreachable backend spends all their+ * time in.+ *+ * What that published as tenant state: a connector inventory the tenant does+ * not run ("CrowdStrike EDR", 412 events), a MITRE tactic ranking, a 24h+ * volume curve, MTTD/MTTR figures, and an LLM spend line naming models the+ * tenant never configured.+ *+ * These tests assert the negative — that none of those strings can reach the+ * DOM outside demo mode — which is the only form that stays meaningful as the+ * components grow.+ */++import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';+import { cleanup, render, screen } from '@testing-library/react';+import { __setDemoModeForTests } from '@/lib/demoMode';++const swrData = vi.hoisted(() => new Map<string, unknown>());+const swrErrors = vi.hoisted(() => new Map<string, unknown>());++vi.mock('swr', () => ({+ __esModule: true,+ default: (key: unknown) => {+ const k = typeof key === 'string' ? key : JSON.stringify(key);+ return {+ data: swrData.get(k),+ error: swrErrors.get(k),+ isLoading: false,+ mutate: vi.fn(),+ };+ },+}));++vi.mock('@/lib/api', () => ({+ __esModule: true,+ metricsApi: {+ getDashboard: vi.fn(),+ getSOC: vi.fn(),+ getFunnel: vi.fn(),+ getPipelineHealth: vi.fn(),+ },+ investigationsApi: { getCostAggregate: vi.fn() },+}));++vi.mock('next/link', () => ({+ __esModule: true,+ default: ({ children, href }: { children: React.ReactNode; href: string }) => (+ <a href={href}>{children}</a>+ ),+}));++vi.mock('next/navigation', () => ({+ __esModule: true,+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn() }),+ usePathname: () => '/dashboard',+ useSearchParams: () => new URLSearchParams(),+}));++// `next/dynamic` returns a promise-loaded chart in production. Under jsdom we+// only care that no fabricated *numbers* reach the DOM, so render nothing.+vi.mock('next/dynamic', () => ({+ __esModule: true,+ default: () => function DynamicStub() {+ return null;+ },+}));++// Realtime + child widgets are exercised by their own suites.+vi.mock('@/lib/realtime', () => ({+ __esModule: true,+ useRealtimeChannel: () => ({ status: 'disconnected', lastEvent: null, events: [] }),+}));++import { DashboardView } from './DashboardView';+import { SOCMetricsDashboard } from './SOCMetricsDashboard';++/**+ * Every string the fabricated payloads would put on screen. Taken verbatim+ * from `MOCK_METRICS` in DashboardView.tsx and `MOCK_SOC_METRICS` /+ * `MOCK_COST_AGGREGATE` in SOCMetricsDashboard.tsx.+ */+const FABRICATED_SOURCE_NAMES = [+ 'CrowdStrike EDR',+ 'Microsoft Sentinel',+ 'AWS CloudTrail',+ 'Okta Identity',+ 'Google Workspace',+ 'GitHub Audit',+];++const FABRICATED_MODEL_NAMES = ['gpt-4o', 'gpt-4o-mini', 'claude-3.5-sonnet'];++function expectNoFabrication(names: string[]) {+ for (const name of names) {+ expect(+ screen.queryByText(new RegExp(name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')),+ `"${name}" is sample data and must not render outside demo mode`,+ ).toBeNull();+ }+}++beforeEach(() => {+ swrData.clear();+ swrErrors.clear();+ __setDemoModeForTests(false);+});++afterEach(() => {+ cleanup();+ __setDemoModeForTests(null);+});++describe('DashboardView — no fabricated data outside demo mode', () => {+ it('renders an error state, not a mock connector inventory, when the metrics API fails', () => {+ swrErrors.set('dashboard-metrics', new Error('503 Service Unavailable'));++ render(<DashboardView />);++ expectNoFabrication(FABRICATED_SOURCE_NAMES);+ // The failure itself is surfaced rather than swallowed.+ expect(screen.getAllByText(/503 Service Unavailable/i).length).toBeGreaterThan(0);+ });++ it('does not invent a 1247-alert baseline when the API fails', () => {+ swrErrors.set('dashboard-metrics', new Error('network down'));++ render(<DashboardView />);++ expect(screen.queryByText('1247')).toBeNull();+ expect(screen.queryByText('42m')).toBeNull();+ });++ it('shows an honest empty state for sections the API returns empty', () => {+ // A real, reachable API on a tenant that has alerts but no connectors,+ // no technique hits and no trend history yet. Previously each of these+ // empty arrays was swapped for the corresponding mock.+ swrData.set('dashboard-metrics', {+ alerts: { total: 4, new: 1, critical: 0, high: 2, medium: 1, low: 1, resolvedToday: 0, mttr: 11 },+ cases: { open: 0, inProgress: 0, resolvedThisWeek: 0 },+ sources: [],+ topMitre: [],+ alertsTrend: [],+ threatsBySource: [],+ });++ render(<DashboardView />);++ // Real numbers still render.+ expect(screen.getByText('4')).toBeTruthy();+ // Fabricated ones do not.+ expectNoFabrication(FABRICATED_SOURCE_NAMES);+ expect(screen.getByText(/No sources connected/i)).toBeTruthy();+ expect(screen.getByText(/No technique coverage yet/i)).toBeTruthy();+ });++ it('publishes no trend delta it cannot source from the API', () => {+ swrData.set('dashboard-metrics', {+ alerts: { total: 4, new: 1, critical: 0, high: 2, medium: 1, low: 1, resolvedToday: 0, mttr: 11 },+ cases: { open: 0, inProgress: 0, resolvedThisWeek: 0 },+ sources: [],+ topMitre: [],+ alertsTrend: [],+ threatsBySource: [],+ });++ render(<DashboardView />);++ // `/metrics/dashboard` returns no period-over-period comparison, so the+ // "+12% vs yesterday" / "-3% vs yesterday" / "-8% vs last week" literals+ // that used to sit beside the real counts were pure invention.+ expect(screen.queryByText(/vs yesterday/i)).toBeNull();+ expect(screen.queryByText(/vs last week/i)).toBeNull();+ });+});++describe('SOCMetricsDashboard — no fabricated data outside demo mode', () => {+ it('renders no KPI figures when /metrics/soc has not resolved', () => {+ render(<SOCMetricsDashboard />);++ // MOCK_SOC_METRICS values.+ expect(screen.queryByText('1.4')).toBeNull();+ expect(screen.queryByText('6.2')).toBeNull();+ expect(screen.queryByText('14.8')).toBeNull();+ expect(screen.queryByText('1247')).toBeNull();+ expect(screen.getByText(/No SOC performance data yet/i)).toBeTruthy();+ });++ it('never names a model the tenant has not run', () => {+ render(<SOCMetricsDashboard />);++ expectNoFabrication(FABRICATED_MODEL_NAMES);+ expect(screen.queryByText(/\$76\.65/)).toBeNull();+ });++ it('surfaces the API error instead of a baseline', () => {+ swrErrors.set('soc-metrics', new Error('upstream timeout'));++ render(<SOCMetricsDashboard />);++ expect(screen.getByText(/upstream timeout/i)).toBeTruthy();+ expect(screen.queryByText('1.4')).toBeNull();+ });+});++describe('demo mode still populates the dashboards', () => {+ it('renders the sample connector inventory when the build is the hosted demo', () => {+ // The gate must not have become "never show sample data anywhere" — the+ // hosted demo has no backend of its own and is the reason the mocks exist.+ __setDemoModeForTests(true);+ // In demo mode `demoFallback` supplies the mock as SWR fallbackData, which+ // the mocked SWR above models by seeding the same cache key.+ swrData.set('dashboard-metrics', {+ alerts: { total: 1247, new: 89, critical: 12, high: 43, medium: 156, low: 289, resolvedToday: 67, mttr: 42 },+ cases: { open: 23, inProgress: 15, resolvedThisWeek: 34 },+ sources: [{ name: 'CrowdStrike EDR', count: 412, status: 'active' }],+ topMitre: [{ tactic: 'Execution', count: 89 }],+ alertsTrend: [],+ threatsBySource: [],+ });++ render(<DashboardView />);++ expect(screen.getByText('CrowdStrike EDR')).toBeTruthy();+ });+});diff --git a/apps/web/src/components/dashboard/DashboardView.tsx b/apps/web/src/components/dashboard/DashboardView.tsxindex 1139daefa..ba6f4efe1 100644--- a/apps/web/src/components/dashboard/DashboardView.tsx+++ b/apps/web/src/components/dashboard/DashboardView.tsx@@ -19,6 +19,7 @@ import useSWR from 'swr';import { metricsApi, type DashboardMetrics } from '@/lib/api';import { clsx } from 'clsx';import dynamic from 'next/dynamic';+import Link from 'next/link';import { format } from 'date-fns';import { LiveFeedPanel } from './LiveFeedPanel';import { SOCMetricsDashboard } from './SOCMetricsDashboard';@@ -27,6 +28,8 @@ import { FunnelKpiBar } from './FunnelKpiBar';import { EfficiencyReport } from './EfficiencyReport';import { PipelineHealth } from './PipelineHealth';import { demoFallback } from '@/lib/demoFallback';+import { EmptyState } from '@/components/ui/EmptyState';+import { ErrorState } from '@/components/ui/ErrorState';const RechartsArea = dynamic(() => import('recharts').then((m) => {@@ -206,6 +209,55 @@ function MetricCard({ label, value, sub, color = 'blue', trend }: MetricCardProp);}+// ─── Honest data-absent panel ─────────────────────────────────────────────────++/**+ * What a panel shows when it has no numbers to show.+ *+ * Two distinct situations, deliberately rendered differently, because+ * conflating them is how "the estate is quiet" and "the API is down" became+ * indistinguishable on this dashboard:+ *+ * - `error` set → the request failed. Say so, name the failure, offer a+ * retry that actually re-issues the request.+ * - `error` unset → the request succeeded and the tenant genuinely has no+ * data for this panel. Say *that*, and point at the thing+ * that would produce some.+ */+function PanelUnavailable({+ error,+ onRetry,+ emptyTitle,+ emptyDescription,+ action,+}: {+ error?: unknown;+ onRetry?: () => void;+ emptyTitle: string;+ emptyDescription: string;+ action?: ReactNode;+}) {+ if (error) {+ return (+ <ErrorState+ title="Could not load this panel"+ description="The metrics API did not respond. Nothing is rendered here rather than a placeholder number."+ error={error}+ onRetry={onRetry}+ className="px-4 py-6"+ />+ );+ }+ return (+ <EmptyState+ title={emptyTitle}+ description={emptyDescription}+ action={action}+ className="px-4 py-6"+ />+ );+}+// ─── Chart tooltip ────────────────────────────────────────────────────────────function CustomTooltip({ active, payload, label }: any) {@@ -374,7 +426,7 @@ function useDashboardLayout() {// ─── Main Dashboard ───────────────────────────────────────────────────────────export function DashboardView() {- const { data: rawMetrics, error: metricsError } = useSWR(+ const { data: rawMetrics, error: metricsError, mutate: mutateMetrics } = useSWR('dashboard-metrics',() => metricsApi.getDashboard(),{@@ -388,6 +440,10 @@ export function DashboardView() {});+ const retryMetrics = useCallback(() => {+ void mutateMetrics();+ }, [mutateMetrics]);+const metricsErrorMessage =metricsError instanceof Error? metricsError.message@@ -395,46 +451,47 @@ export function DashboardView() {? String(metricsError): null;- // Hybrid: prefer real API fields when present, fall back to mock for missing- // sections (e.g. /metrics/dashboard currently returns alertsTrend: [] and no- // threatsBySource yet, so the charts would render empty without this merge).+ // `MOCK_METRICS` reaches this component through exactly one door: the+ // `demoFallback` above, which returns `undefined` outside the hosted demo.+ //+ // It used to reach it through a second door as well — a per-section merge+ // that substituted the mock whenever the API omitted a section, plus a+ // blanket `: MOCK_METRICS` when the call failed. That published a fabricated+ // connector inventory ("CrowdStrike EDR · 412 events"), a fabricated MITRE+ // tactic ranking, and a fabricated 24h volume curve as tenant state on any+ // self-hosted install whose API was reachable but whose lake was empty.+ // Sections the API does not populate now render an honest empty state.const apiData = rawMetrics as Partial<DashboardMetrics> | undefined;- const hasRealAlerts = !!apiData && typeof apiData.alerts?.total === 'number';- const metrics: DashboardMetrics = hasRealAlerts- ? {- alerts: apiData!.alerts as DashboardMetrics['alerts'],- cases: apiData!.cases ?? MOCK_METRICS.cases,- sources:- Array.isArray(apiData!.sources) && apiData!.sources!.length- ? apiData!.sources!- : MOCK_METRICS.sources,- topMitre:- Array.isArray(apiData!.topMitre) && apiData!.topMitre!.length- ? apiData!.topMitre!- : MOCK_METRICS.topMitre,- alertsTrend:- Array.isArray(apiData!.alertsTrend) && apiData!.alertsTrend!.length- ? apiData!.alertsTrend!- : MOCK_METRICS.alertsTrend,- threatsBySource:- Array.isArray(apiData!.threatsBySource) && apiData!.threatsBySource!.length- ? apiData!.threatsBySource!- : MOCK_METRICS.threatsBySource,- }- : MOCK_METRICS;-- const trendData = metrics.alertsTrend.map((d) => ({+ const metrics: DashboardMetrics | null =+ apiData && typeof apiData.alerts?.total === 'number'+ ? {+ alerts: apiData.alerts,+ cases: apiData.cases ?? { open: 0, inProgress: 0, resolvedThisWeek: 0 },+ sources: apiData.sources ?? [],+ topMitre: apiData.topMitre ?? [],+ alertsTrend: apiData.alertsTrend ?? [],+ threatsBySource: apiData.threatsBySource ?? [],+ }+ : null;++ const sources = metrics?.sources ?? [];+ const topMitre = metrics?.topMitre ?? [];+ const activeSourceCount = sources.filter((s) => s.status === 'active').length;++ const trendData = (metrics?.alertsTrend ?? []).map((d) => ({time: format(new Date(d.timestamp), 'HH:mm'),count: d.count,}));- const SEVERITY_CHART_DATA = [- { name: 'Critical', value: metrics.alerts.critical, color: '#ef4444' },- { name: 'High', value: metrics.alerts.high, color: '#f97316' },- { name: 'Medium', value: metrics.alerts.medium, color: '#eab308' },- { name: 'Low', value: metrics.alerts.low, color: '#3b82f6' },- { name: 'Info', value: metrics.alerts.info ?? 0, color: '#64748b' },- ];+ const SEVERITY_CHART_DATA = metrics+ ? [+ { name: 'Critical', value: metrics.alerts.critical, color: '#ef4444' },+ { name: 'High', value: metrics.alerts.high, color: '#f97316' },+ { name: 'Medium', value: metrics.alerts.medium, color: '#eab308' },+ { name: 'Low', value: metrics.alerts.low, color: '#3b82f6' },+ { name: 'Info', value: metrics.alerts.info ?? 0, color: '#64748b' },+ ]+ : [];// WS-F3: drag-and-drop widget reorderingconst { order, dragState, handleDragStart, handleDragOver, handleDrop } = useDashboardLayout();@@ -464,45 +521,56 @@ export function DashboardView() {<h2 className="text-xl font-semibold text-gray-100">Security Operations Center</h2><p className="text-sm text-gray-500 mt-0.5">Entity-risk alerting, confidence-scored triage, and{' '}- {metrics.sources.filter((s) => s.status === 'active').length} connected sources+ {metrics ? activeSourceCount : '—'}+ {' '}connected sources</p></div></div>- <div className="grid grid-cols-2 sm:grid-cols-5 gap-4">- <MetricCard- label="Active Alerts"- value={metrics.alerts.total}- sub={`${metrics.alerts.new} new today`}- color="blue"- trend={{ value: 12, label: 'vs yesterday' }}- />- <MetricCard- label="Critical"- value={metrics.alerts.critical}- sub="Require immediate action"- color="red"- trend={{ value: -3, label: 'vs yesterday' }}- />- <MetricCard- label="Open Cases"- value={metrics.cases.open}- sub={`${metrics.cases.inProgress} in progress`}- color="orange"- />- <MetricCard- label="MTTR"- value={`${metrics.alerts.mttr}m`}- sub="Mean time to resolve"- color="green"- trend={{ value: -8, label: 'vs last week' }}- />- <MetricCard- label="Connected Sources"- value={metrics.sources.filter(s => s.status === 'active').length}- sub="EDR, SIEM, Cloud, IAM, SaaS"- color="purple"+ {metrics ? (+ <div className="grid grid-cols-2 sm:grid-cols-5 gap-4">+ {/* No `trend` props here. The three that used to sit on these cards+ were literals (+12% / -3% / -8%), not deltas the API returns —+ /metrics/dashboard has no period-over-period comparison. The+ funnel strip above does publish real deltas. */}+ <MetricCard+ label="Active Alerts"+ value={metrics.alerts.total}+ sub={`${metrics.alerts.new} new today`}+ color="blue"+ />+ <MetricCard+ label="Critical"+ value={metrics.alerts.critical}+ sub="Require immediate action"+ color="red"+ />+ <MetricCard+ label="Open Cases"+ value={metrics.cases.open}+ sub={`${metrics.cases.inProgress} in progress`}+ color="orange"+ />+ <MetricCard+ label="MTTR"+ value={`${metrics.alerts.mttr}m`}+ sub="Mean time to resolve"+ color="green"+ />+ <MetricCard+ label="Connected Sources"+ value={activeSourceCount}+ sub="EDR, SIEM, Cloud, IAM, SaaS"+ color="purple"+ />+ </div>+ ) : (+ <PanelUnavailable+ error={metricsError}+ onRetry={retryMetrics}+ emptyTitle="No dashboard metrics yet"+ emptyDescription="Connect a data source to start populating alert, case and MTTR counters."/>- </div>+ )}</div>),@@ -513,22 +581,42 @@ export function DashboardView() {<h3 className="text-sm font-medium text-gray-300">Alert Volume (24h)</h3><span className="text-xs text-gray-500">Last 24 hours</span></div>- <RechartsArea data={trendData} />+ {trendData.length > 0 ? (+ <RechartsArea data={trendData} />+ ) : (+ <PanelUnavailable+ error={metricsError}+ onRetry={retryMetrics}+ emptyTitle="No alerts in the last 24 hours"+ emptyDescription="The volume curve plots hourly alert counts once alerts start arriving."+ />+ )}</div><div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-5"><h3 className="text-sm font-medium text-gray-300 mb-4">Severity Breakdown</h3>- <RechartsPie data={SEVERITY_CHART_DATA} />- <div className="space-y-1.5 mt-2">- {SEVERITY_CHART_DATA.map((d) => (- <div key={d.name} className="flex items-center justify-between text-xs">- <div className="flex items-center gap-1.5">- <span className="w-2 h-2 rounded-full" style={{ background: d.color }} />- <span className="text-gray-400">{d.name}</span>- </div>- <span className="text-gray-300 font-medium">{d.value}</span>+ {metrics ? (+ <>+ <RechartsPie data={SEVERITY_CHART_DATA} />+ <div className="space-y-1.5 mt-2">+ {SEVERITY_CHART_DATA.map((d) => (+ <div key={d.name} className="flex items-center justify-between text-xs">+ <div className="flex items-center gap-1.5">+ <span className="w-2 h-2 rounded-full" style={{ background: d.color }} />+ <span className="text-gray-400">{d.name}</span>+ </div>+ <span className="text-gray-300 font-medium">{d.value}</span>+ </div>+ ))}</div>- ))}- </div>+ </>+ ) : (+ <PanelUnavailable+ error={metricsError}+ onRetry={retryMetrics}+ emptyTitle="No severity data"+ emptyDescription="Severity counts appear once the API returns alert metrics."+ />+ )}</div></div>),@@ -537,13 +625,38 @@ export function DashboardView() {<div className="grid grid-cols-3 gap-4"><div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-5"><h3 className="text-sm font-medium text-gray-300 mb-4">Top MITRE ATT&CK Tactics</h3>- <RechartsBar data={metrics.topMitre} />+ {topMitre.length > 0 ? (+ <RechartsBar data={topMitre} />+ ) : (+ <PanelUnavailable+ error={metricsError}+ onRetry={retryMetrics}+ emptyTitle="No technique coverage yet"+ emptyDescription="Tactics rank by alert count once detections start firing."+ />+ )}</div><div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-5"><h3 className="text-sm font-medium text-gray-300 mb-4">Connected Sources</h3>+ {sources.length === 0 ? (+ <PanelUnavailable+ error={metricsError}+ onRetry={retryMetrics}+ emptyTitle="No sources connected"+ emptyDescription="Connect a data source and its event volume appears here."+ action={+ <Link+ href="/connectors"+ className="text-xs text-blue-400 underline underline-offset-2 hover:text-blue-300"+ >+ Go to connectors+ </Link>+ }+ />+ ) : (<div className="space-y-3">- {metrics.sources.map((src) => {- const maxCount = Math.max(...metrics.sources.map(s => s.count));+ {sources.map((src) => {+ const maxCount = Math.max(...sources.map(s => s.count), 1);const pct = Math.round((src.count / maxCount) * 100);return (<div key={src.name}>@@ -564,6 +677,7 @@ export function DashboardView() {);})}</div>+ )}</div><LiveFeedPanel /></div>@@ -594,8 +708,8 @@ export function DashboardView() {{metricsErrorMessage}</p><p className="mt-1 text-xs text-red-300/60">- Showing baseline mock data while SWR retries every 4s. Refresh the- page if it persists.+ Panels below are blank rather than showing placeholder figures.+ Retrying every 4s.</p></div>)}diff --git a/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx b/apps/web/src/components/dashboard/SOCMetricsDashboard.tsxindex e175a666d..1f80f6453 100644--- a/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx+++ b/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx@@ -12,6 +12,7 @@ import {type CostAggregate,} from "@/lib/api";import { demoFallback } from '@/lib/demoFallback';+import { EmptyState } from '@/components/ui/EmptyState';const MOCK_SOC_METRICS: SOCMetrics = {kpis: {@@ -175,17 +176,21 @@ export function SOCMetricsDashboard() {const refresh = useCallback(() => mutate(), [mutate]);+ // `MOCK_SOC_METRICS` is reachable only through the `demoFallback` above,+ // which is `undefined` outside the hosted demo.+ //+ // It used to also be substituted here, unconditionally, whenever `data` was+ // absent or malformed — which is exactly the first-paint and error case. A+ // self-hoster therefore saw MTTD 1.4h, a populated ATT&CK heatmap and an LLM+ // spend line naming models they had never configured, presented as their own+ // numbers. When there is no payload there are now no numbers.const isValidSOC =!!data &&typeof data.kpis?.mttd_hours === "number" &&Array.isArray(data.attack_heatmap);- const resolved = isValidSOC ? data : MOCK_SOC_METRICS;- const kpis = resolved.kpis;- const heatmap = resolved.attack_heatmap ?? [];- const calibration = resolved.calibration_curve ?? [];- // We surface the error inline rather than swapping the whole panel out for- // a blocking error state — the mock fallback keeps the page legible while- // the user retries.+ const kpis = isValidSOC ? data.kpis : undefined;+ const heatmap = isValidSOC ? (data.attack_heatmap ?? []) : [];+ const calibration = isValidSOC ? (data.calibration_curve ?? []) : [];const errorMessage =error instanceof Error? error.message@@ -209,12 +214,21 @@ export function SOCMetricsDashboard() {{errorMessage && (<div className="rounded border border-red-900/60 bg-red-950/40 px-3 py-2 text-xs text-red-200"><span className="font-semibold">SOC metrics unavailable:</span>{" "}- {errorMessage}. Showing last known mock baseline; the live numbers- will refresh automatically once the API recovers.+ {errorMessage}. No figures are shown below; they will populate once+ the API recovers.</div>)}+ {!kpis && !errorMessage && (+ <EmptyState+ title="No SOC performance data yet"+ description="MTTD, MTTR, escalation and false-positive rates are computed from closed cases. They appear once the first investigations complete."+ className="px-4 py-6"+ />+ )}+{/* KPI Grid */}+ {kpis && (<div className="grid grid-cols-2 md:grid-cols-4 gap-3"><KpiCardlabel="MTTD"@@ -299,6 +313,7 @@ export function SOCMetricsDashboard() {color="text-blue-400"/></div>+ )}{/* Confidence Calibration Curve */}<div className="bg-gray-900 border border-gray-700 rounded-lg p-4">@@ -341,13 +356,15 @@ function CostTelemetryPanel() {},);+ // Same rule as the SOC panel: the mock is the demo fallback and nothing+ // else. Naming `gpt-4o` / `claude-3.5-sonnet` and a $76.65 spend to a+ // tenant that runs neither is a fabricated claim about their own estate.const isValidCost =!!data &&Array.isArray(data.by_model) &&typeof data.window_days === "number";- const resolved = isValidCost ? data : MOCK_COST_AGGREGATE;- const totals = resolved.totals;- const byModel = resolved.by_model ?? [];+ const totals = isValidCost ? data.totals : undefined;+ const byModel = isValidCost ? (data.by_model ?? []) : [];const maxModelCost = Math.max(...byModel.map((m) => m.total_cost_usd), 0.0001);const errorMessage =error instanceof Error@@ -374,11 +391,11 @@ function CostTelemetryPanel() {{errorMessage && (<div className="mb-3 rounded border border-red-900/60 bg-red-950/40 px-3 py-2 text-xs text-red-200"><span className="font-semibold">Cost telemetry unavailable:</span>{" "}- {errorMessage}. Showing baseline projections until the API recovers.+ {errorMessage}. No spend figures are shown until the API recovers.</div>)}- {isLoading && !resolved ? (+ {isLoading && !isValidCost ? (<div className="h-32 animate-pulse bg-gray-800 rounded" />) : !totals || totals.runs === 0 ? (<div className="text-gray-500 text-sm flex items-center justify-center h-24">diff --git a/apps/web/src/lib/api.alerts-list.test.ts b/apps/web/src/lib/api.alerts-list.test.tsnew file mode 100644index 000000000..10fcecf2b--- /dev/null+++ b/apps/web/src/lib/api.alerts-list.test.ts@@ -0,0 +1,92 @@+/**+ * `alertsApi.list` — response-envelope contract.+ *+ * `AlertListResponse` in `services/api/app/api/v1/endpoints/alerts.py` returns+ * the rows under `items`. The client read `raw.alerts`, which is never present,+ * so `Array.isArray(undefined)` was false and every page resolved to `[]` while+ * `total` carried the real count — the queue rendered a row count above an+ * empty table, with no error to explain it.+ *+ * These tests pin the envelope in both directions so the two halves cannot+ * drift apart again silently.+ */++import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';+import { alertsApi } from './api';++const ALERT_ROW = {+ id: '11111111-1111-4111-8111-111111111111',+ title: 'Suspicious PowerShell download cradle',+ severity: 'high',+ status: 'new',+ created_at: '2026-05-06T12:00:00Z',+};++function jsonResponse(body: unknown) {+ return {+ ok: true,+ status: 200,+ statusText: 'OK',+ headers: new Headers({ 'content-type': 'application/json' }),+ json: async () => body,+ text: async () => JSON.stringify(body),+ } as unknown as Response;+}++let fetchMock: ReturnType<typeof vi.fn>;++beforeEach(() => {+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe('alertsApi.list envelope', () => {+ it('reads the rows the API actually sends, under `items`', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({ items: [ALERT_ROW], total: 1, page: 1, page_size: 50, pages: 1 }),+ );++ const result = await alertsApi.list();++ // Against the pre-fix client this is 0: it only looked at `raw.alerts`.+ expect(result.alerts).toHaveLength(1);+ expect(result.alerts[0].id).toBe(ALERT_ROW.id);+ expect(result.total).toBe(1);+ });++ it('never reports a total it has no rows for', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({ items: [ALERT_ROW, { ...ALERT_ROW, id: 'b' }], total: 2, page: 1, page_size: 50 }),+ );++ const result = await alertsApi.list();++ // The symptom users saw: "2 alerts" above an empty table.+ expect(result.alerts.length).toBe(result.total);+ });++ it('still accepts the legacy `alerts` key so responder routes keep working', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({ alerts: [ALERT_ROW], total: 1, page: 1, pageSize: 25 }),+ );++ const result = await alertsApi.list();++ expect(result.alerts).toHaveLength(1);+ expect(result.pageSize).toBe(25);+ });++ it('returns an empty page without throwing when the API sends neither key', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ total: 0, page: 1, page_size: 50 }));++ const result = await alertsApi.list();++ expect(result.alerts).toEqual([]);+ expect(result.total).toBe(0);+ });+});diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 7d9e49280..29a65a3f0 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -763,6 +763,7 @@ export interface AlertFilters {export const alertsApi = {list: async (filters: AlertFilters = {}) => {const raw = await request<{+ items?: unknown[];alerts?: unknown[];total?: number;page?: number;@@ -771,8 +772,18 @@ export const alertsApi = {}>('/api/v1/alerts', {params: filters as Record<string, string>,});+ // `AlertListResponse` puts the rows under `items`, not `alerts`+ // (services/api/app/api/v1/endpoints/alerts.py). Reading only `alerts`+ // resolved every page to [] while `total` reported the real count, so+ // the queue rendered "1,247 alerts" above an empty table. `alerts` is+ // still accepted because the mobile responder routes emit that shape.+ const rows = Array.isArray(raw.items)+ ? raw.items+ : Array.isArray(raw.alerts)+ ? raw.alerts+ : [];return {- alerts: Array.isArray(raw.alerts) ? raw.alerts.map(normalizeAlert) : [],+ alerts: rows.map(normalizeAlert),total: typeof raw.total === 'number' ? raw.total : 0,page: typeof raw.page === 'number' ? raw.page : 1,pageSize: