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.

fix(dashboard): unblock real /metrics data on tryaisoc.com/dashboard (#192)

Beenu Arora1e9f542cae1f
diff --git a/apps/web/src/app/(app)/dashboard/page.tsx b/apps/web/src/app/(app)/dashboard/page.tsx
index 5279e9df8..d8f7cfaf9 100644
--- a/apps/web/src/app/(app)/dashboard/page.tsx
+++ b/apps/web/src/app/(app)/dashboard/page.tsx
@@ -4,6 +4,10 @@ export const metadata = {
title: 'Dashboard',
};
+export const dynamic = 'force-dynamic';
+export const revalidate = 0;
+export const fetchCache = 'force-no-store';
+
export default function DashboardPage() {
return <DashboardView />;
}
diff --git a/apps/web/src/components/dashboard/DashboardView.tsx b/apps/web/src/components/dashboard/DashboardView.tsx
index a40094d15..04834ac73 100644
--- a/apps/web/src/components/dashboard/DashboardView.tsx
+++ b/apps/web/src/components/dashboard/DashboardView.tsx
@@ -373,18 +373,27 @@ function useDashboardLayout() {
// ─── Main Dashboard ───────────────────────────────────────────────────────────
export function DashboardView() {
- const { data: rawMetrics } = useSWR(
+ const { data: rawMetrics, error: metricsError } = useSWR(
'dashboard-metrics',
() => metricsApi.getDashboard(),
{
fallbackData: MOCK_METRICS,
refreshInterval: 60000,
- shouldRetryOnError: false,
- errorRetryCount: 0,
+ revalidateOnMount: true,
revalidateOnFocus: false,
+ shouldRetryOnError: true,
+ errorRetryCount: 3,
+ errorRetryInterval: 4000,
}
);
+ const metricsErrorMessage =
+ metricsError instanceof Error
+ ? metricsError.message
+ : metricsError
+ ? 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).
@@ -577,6 +586,18 @@ export function DashboardView() {
return (
<DashboardErrorBoundary>
<div className="space-y-5">
+ {metricsErrorMessage && (
+ <div className="rounded-xl border border-red-900/60 bg-red-950/40 px-4 py-3 text-sm text-red-200">
+ <p className="font-semibold">Dashboard metrics unavailable</p>
+ <p className="mt-1 text-xs text-red-300/80">
+ {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.
+ </p>
+ </div>
+ )}
{order.map((id) => (
<DraggableWidget
key={id}
diff --git a/apps/web/src/components/dashboard/FunnelKpiBar.tsx b/apps/web/src/components/dashboard/FunnelKpiBar.tsx
index 6cb67b660..fef03b2f2 100644
--- a/apps/web/src/components/dashboard/FunnelKpiBar.tsx
+++ b/apps/web/src/components/dashboard/FunnelKpiBar.tsx
@@ -139,17 +139,41 @@ export function FunnelKpiBar({
{
refreshInterval: 60_000,
revalidateOnFocus: false,
- shouldRetryOnError: false,
+ revalidateOnMount: true,
+ shouldRetryOnError: true,
+ errorRetryCount: 3,
+ errorRetryInterval: 4000,
},
);
- // Error takes priority over loading. SWR with shouldRetryOnError: false leaves
- // `data` undefined on failure, so without this ordering the loading branch wins
- // forever and the user stares at skeleton tiles.
+ // Error takes priority over loading and stale data. Without this ordering
+ // the loading branch wins after a failure and the user stares at skeleton
+ // tiles forever; if we let stale data through silently, the analyst sees
+ // confidently-rendered numbers that may be hours old. Bias toward making
+ // the failure visible — SWR will keep retrying every 4s underneath.
if (error) {
+ const errorMessage =
+ error instanceof Error ? error.message : String(error);
return (
- <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4 text-sm text-gray-400">
- Funnel metrics unavailable.
+ <div>
+ <div className="flex items-center justify-between mb-3">
+ <div>
+ <h2 className="text-base font-semibold text-gray-100">
+ Operations Funnel
+ </h2>
+ <p className="text-xs text-gray-500 mt-0.5">
+ Live tenant pipeline: events → correlations → alerts
+ </p>
+ </div>
+ <span className="text-xs text-gray-500">Last {period}</span>
+ </div>
+ <div className="rounded-xl border border-red-900/60 bg-red-950/40 px-4 py-3 text-sm text-red-200">
+ <p className="font-semibold">Funnel metrics unavailable</p>
+ <p className="mt-1 text-xs text-red-300/80">{errorMessage}</p>
+ <p className="mt-1 text-xs text-red-300/60">
+ SWR will keep retrying every 4s; refresh the page if it persists.
+ </p>
+ </div>
</div>
);
}
diff --git a/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx b/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx
index 4609cf34e..ac8ba518c 100644
--- a/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx
+++ b/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx
@@ -3,68 +3,14 @@
import { useCallback } from "react";
import useSWR from "swr";
-interface SOCKpis {
- mttd_hours: number;
- mttr_hours: number;
- mttc_hours: number;
- false_positive_rate: number;
- escalation_rate: number;
- alert_volume_7d: number;
- cases_opened_7d: number;
- cases_closed_7d: number;
- analyst_overrides_7d: number;
-}
-
-interface AttackHeatmapCell {
- tactic: string;
- technique: string;
- count: number;
-}
-
-interface CalibrationBucket {
- predicted_lower: number;
- predicted_upper: number;
- sample_count: number;
- actual_tp_rate: number;
-}
-
-interface SOCMetrics {
- kpis: SOCKpis;
- attack_heatmap: AttackHeatmapCell[];
- calibration_curve: CalibrationBucket[];
-}
-
-interface CostAggregateRow {
- model: string;
- runs: number;
- calls: number;
- total_prompt_tokens: number;
- total_completion_tokens: number;
- total_cost_usd: number;
- total_latency_ms: number;
- avg_cost_per_run: number;
- avg_latency_per_call_ms: number;
-}
-
-interface CostAggregate {
- window_days: number;
- by_model: CostAggregateRow[];
- totals: CostAggregateRow | null;
-}
-
-async function safeFetcher<T = unknown>(url: string): Promise<T> {
- const r = await fetch(url, { credentials: "include" });
- if (!r.ok) {
- const body = await r.text().catch(() => "");
- throw new Error(`${r.status} ${r.statusText} — ${body.slice(0, 120)}`);
- }
- const text = await r.text();
- try {
- return JSON.parse(text) as T;
- } catch {
- throw new Error(`Invalid JSON from ${url}: ${text.slice(0, 80)}`);
- }
-}
+import {
+ metricsApi,
+ investigationsApi,
+ type SOCMetrics,
+ type AttackHeatmapCell,
+ type CalibrationBucket,
+ type CostAggregate,
+} from "@/lib/api";
const MOCK_SOC_METRICS: SOCMetrics = {
kpis: {
@@ -208,25 +154,43 @@ function AttackHeatmap({ cells }: { cells: AttackHeatmapCell[] }) {
}
export function SOCMetricsDashboard() {
- const { data, mutate } = useSWR<SOCMetrics>(
- "/api/v1/metrics/soc",
- safeFetcher<SOCMetrics>,
+ const { data, error, isLoading, mutate } = useSWR<SOCMetrics>(
+ // Opaque cache key — `metricsApi.getSOC()` routes through the
+ // tenant- and auth-aware `request()` helper, which attaches
+ // `X-Tenant-Id` and `Authorization` headers and is bound to the
+ // same-origin proxy in `next.config.*` rewrites.
+ "soc-metrics",
+ () => metricsApi.getSOC(),
{
refreshInterval: 60_000,
fallbackData: MOCK_SOC_METRICS,
- shouldRetryOnError: false,
- errorRetryCount: 0,
+ shouldRetryOnError: true,
+ errorRetryCount: 3,
+ errorRetryInterval: 4000,
+ revalidateOnMount: true,
revalidateOnFocus: false,
}
);
const refresh = useCallback(() => mutate(), [mutate]);
- const isValidSOC = data && typeof data.kpis?.mttd_hours === "number" && Array.isArray(data.attack_heatmap);
+ 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 errorMessage =
+ error instanceof Error
+ ? error.message
+ : error
+ ? String(error)
+ : null;
return (
<div className="space-y-6">
@@ -241,6 +205,14 @@ export function SOCMetricsDashboard() {
</button>
</div>
+ {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.
+ </div>
+ )}
+
{/* KPI Grid */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<KpiCard
@@ -354,23 +326,34 @@ export function SOCMetricsDashboard() {
}
function CostTelemetryPanel() {
- const { data, isLoading } = useSWR<CostAggregate>(
- "/api/v1/investigations/costs/aggregate?window_days=30",
- safeFetcher<CostAggregate>,
+ const { data, error, isLoading } = useSWR<CostAggregate>(
+ "cost-aggregate:30",
+ () => investigationsApi.getCostAggregate(30),
{
refreshInterval: 60_000,
fallbackData: MOCK_COST_AGGREGATE,
- shouldRetryOnError: false,
- errorRetryCount: 0,
+ shouldRetryOnError: true,
+ errorRetryCount: 3,
+ errorRetryInterval: 4000,
+ revalidateOnMount: true,
revalidateOnFocus: false,
},
);
- const isValidCost = data && Array.isArray(data.by_model) && typeof data.window_days === "number";
+ 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 maxModelCost = Math.max(...byModel.map((m) => m.total_cost_usd), 0.0001);
+ const errorMessage =
+ error instanceof Error
+ ? error.message
+ : error
+ ? String(error)
+ : null;
return (
<div className="bg-gray-900 border border-gray-700 rounded-lg p-4">
@@ -387,6 +370,13 @@ function CostTelemetryPanel() {
each investigation detail view.
</p>
+ {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.
+ </div>
+ )}
+
{isLoading && !resolved ? (
<div className="h-32 animate-pulse bg-gray-800 rounded" />
) : !totals || totals.runs === 0 ? (
diff --git a/apps/web/src/components/soc-insights/SOCInsightsView.test.tsx b/apps/web/src/components/soc-insights/SOCInsightsView.test.tsx
index 098e50cd1..309f6a36b 100644
--- a/apps/web/src/components/soc-insights/SOCInsightsView.test.tsx
+++ b/apps/web/src/components/soc-insights/SOCInsightsView.test.tsx
@@ -12,6 +12,8 @@
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
+import { SWRConfig } from 'swr';
+import type { ReactElement } from 'react';
vi.mock('@/lib/api', () => ({
insightsApi: {
@@ -33,6 +35,23 @@ import { insightsApi, type SOCInsightsResponse } from '@/lib/api';
import { SOCInsightsView } from './SOCInsightsView';
import { pointsToPath } from './Sparkline';
+/**
+ * SWR keeps a process-global cache by default. When one test parks a never-
+ * resolving promise on the key (skeleton case), the next test inherits that
+ * pending state and the new `mockResolvedValue` is ignored — the cache says
+ * "we're already loading, don't re-fetch". Wrapping each render in a fresh
+ * `SWRConfig` provider gives every test its own Map, so the cache cannot
+ * leak across `describe` siblings. This is the standard pattern from the
+ * SWR docs (https://swr.vercel.app/docs/advanced/cache).
+ */
+function renderIsolated(node: ReactElement) {
+ return render(
+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>
+ {node}
+ </SWRConfig>,
+ );
+}
+
const sampleResponse: SOCInsightsResponse = {
window: '24h',
generated_at: '2026-05-13T12:00:00Z',
@@ -116,7 +135,7 @@ describe('SOCInsightsView', () => {
new Promise(() => {}),
);
- render(<SOCInsightsView />);
+ renderIsolated(<SOCInsightsView />);
expect(screen.getByLabelText(/loading soc insights/i)).toBeInTheDocument();
});
@@ -126,7 +145,7 @@ describe('SOCInsightsView', () => {
sampleResponse,
);
- render(<SOCInsightsView />);
+ renderIsolated(<SOCInsightsView />);
// Wait for at least one tile to land — proves the SWR cycle
// completed without re-rendering into the error/loading branch.
@@ -150,7 +169,7 @@ describe('SOCInsightsView', () => {
new Error('500 boom'),
);
- render(<SOCInsightsView />);
+ renderIsolated(<SOCInsightsView />);
await waitFor(() =>
expect(screen.getByRole('alert')).toBeInTheDocument(),
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index a03c9c9bc..26d297c1f 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -1759,6 +1759,68 @@ export interface PipelineHealth {
generated_at: string;
}
+/**
+ * SOC Performance metrics (PR-3 / W2).
+ *
+ * Mirrors ``SOCMetrics`` Pydantic model in
+ * ``services/api/app/api/v1/endpoints/metrics.py``. Drives the SOC
+ * Performance panel + ATT&CK heatmap on /dashboard.
+ */
+export interface SOCKpis {
+ mttd_hours: number;
+ mttr_hours: number;
+ mttc_hours: number;
+ false_positive_rate: number;
+ escalation_rate: number;
+ alert_volume_7d: number;
+ cases_opened_7d: number;
+ cases_closed_7d: number;
+ analyst_overrides_7d: number;
+}
+
+export interface AttackHeatmapCell {
+ tactic: string;
+ technique: string;
+ count: number;
+}
+
+export interface CalibrationBucket {
+ predicted_lower: number;
+ predicted_upper: number;
+ sample_count: number;
+ actual_tp_rate: number;
+}
+
+export interface SOCMetrics {
+ kpis: SOCKpis;
+ attack_heatmap: AttackHeatmapCell[];
+ calibration_curve: CalibrationBucket[];
+}
+
+/**
+ * Investigation cost telemetry (PR-3 / cost panel).
+ *
+ * Mirrors ``CostAggregate`` Pydantic model in
+ * ``services/api/app/api/v1/endpoints/investigations.py``.
+ */
+export interface CostAggregateRow {
+ model: string;
+ runs: number;
+ calls: number;
+ total_prompt_tokens: number;
+ total_completion_tokens: number;
+ total_cost_usd: number;
+ total_latency_ms: number;
+ avg_cost_per_run: number;
+ avg_latency_per_call_ms: number;
+}
+
+export interface CostAggregate {
+ window_days: number;
+ by_model: CostAggregateRow[];
+ totals: CostAggregateRow | null;
+}
+
export const metricsApi = {
getDashboard: () =>
request<DashboardMetrics>('/api/v1/metrics/dashboard'),
@@ -1778,6 +1840,27 @@ export const metricsApi = {
/** Per-stage pipeline health (ingest → normalize → fuse → correlate → alert). */
getPipelineHealth: () =>
request<PipelineHealth>('/api/v1/health/pipeline'),
+
+ /**
+ * SOC Performance KPIs + ATT&CK heatmap + calibration curve.
+ *
+ * Tenant-scoped server-side; the client just needs the bearer token
+ * and X-Tenant-Id header that `request()` already attaches.
+ */
+ getSOC: () => request<SOCMetrics>('/api/v1/metrics/soc'),
+};
+
+// ─── Investigations ─────────────────────────────────────────────────────────
+
+export const investigationsApi = {
+ /**
+ * Investigation cost telemetry aggregated over the last `windowDays`.
+ * Backs the Cost Telemetry panel on /dashboard.
+ */
+ getCostAggregate: (windowDays: number = 30) =>
+ request<CostAggregate>('/api/v1/investigations/costs/aggregate', {
+ params: { window_days: windowDays },
+ }),
};
// ─── SOC Insights (T3.1) ─────────────────────────────────────────────────────
diff --git a/services/api/app/api/v1/endpoints/metrics.py b/services/api/app/api/v1/endpoints/metrics.py
index 468fef9cf..4c515d4ef 100644
--- a/services/api/app/api/v1/endpoints/metrics.py
+++ b/services/api/app/api/v1/endpoints/metrics.py
@@ -286,20 +286,31 @@ async def get_dashboard_metrics(
)
# ── Top MITRE tactics ─────────────────────────────────────────────────────
- mitre_rows = (
+ # Python-side aggregation: avoids set-returning-function-in-SELECT pitfalls
+ # across Postgres versions and gives identical results for our scale
+ # (typically <10k alerts/tenant). Driver tests proved a SQL-level
+ # jsonb_array_elements_text + GROUP BY in the same SELECT 500s on some
+ # Postgres builds.
+ tactic_rows = (
await db.execute(
- select(
- func.jsonb_array_elements_text(Alert.mitre_tactics).label("tactic"),
- func.count().label("cnt"),
+ select(Alert.mitre_tactics).where(
+ and_(Alert.tenant_id == tenant_id, Alert.mitre_tactics.isnot(None))
)
- .where(Alert.tenant_id == tenant_id)
- .group_by("tactic")
- .order_by(func.count().desc())
- .limit(10)
)
).all()
- top_mitre = [MitreTactic(tactic=r.tactic, count=r.cnt) for r in mitre_rows]
+ tactic_counts: dict[str, int] = {}
+ for (tactics,) in tactic_rows:
+ if not tactics:
+ continue
+ for t in tactics:
+ if isinstance(t, str) and t:
+ tactic_counts[t] = tactic_counts.get(t, 0) + 1
+
+ top_mitre = [
+ MitreTactic(tactic=tactic, count=count)
+ for tactic, count in sorted(tactic_counts.items(), key=lambda x: x[1], reverse=True)[:10]
+ ]
# ── 24-hour trend (hourly buckets) ────────────────────────────────────────
trend_start = now - timedelta(hours=24)
@@ -539,21 +550,42 @@ async def get_soc_metrics(
)
# ── ATT&CK heatmap ────────────────────────────────────────────────────────
- heatmap_rows = (
+ # Python-side aggregation. Combining two set-returning functions with
+ # GROUP BY + aggregate in the same SELECT raises on modern Postgres
+ # ("set-returning functions are not allowed in GROUP BY") and was the
+ # root cause of /metrics/soc returning 500. For each alert we pair every
+ # (tactic, technique) Cartesian-style, then aggregate in Python.
+ heatmap_src_rows = (
await db.execute(
- select(
- func.jsonb_array_elements_text(Alert.mitre_tactics).label("tactic"),
- func.jsonb_array_elements_text(Alert.mitre_techniques).label("technique"),
- func.count().label("cnt"),
+ select(Alert.mitre_tactics, Alert.mitre_techniques).where(
+ and_(
+ Alert.tenant_id == tenant_id,
+ Alert.mitre_tactics.isnot(None),
+ Alert.mitre_techniques.isnot(None),
+ )
)
- .where(Alert.tenant_id == tenant_id)
- .group_by("tactic", "technique")
- .order_by(func.count().desc())
- .limit(50)
)
).all()
- heatmap = [AttackHeatmapCell(tactic=r.tactic, technique=r.technique, count=r.cnt) for r in heatmap_rows]
+ pair_counts: dict[tuple[str, str], int] = {}
+ for tactics, techniques in heatmap_src_rows:
+ if not tactics or not techniques:
+ continue
+ for tactic in tactics:
+ if not isinstance(tactic, str) or not tactic:
+ continue
+ for technique in techniques:
+ if not isinstance(technique, str) or not technique:
+ continue
+ key = (tactic, technique)
+ pair_counts[key] = pair_counts.get(key, 0) + 1
+
+ heatmap = [
+ AttackHeatmapCell(tactic=tactic, technique=technique, count=count)
+ for (tactic, technique), count in sorted(
+ pair_counts.items(), key=lambda x: x[1], reverse=True
+ )[:50]
+ ]
# ── Confidence calibration curve ──────────────────────────────────────────
# 5 buckets across [0, 1]. For each bucket, count alerts with ai_score in