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.

A console for the federated SIEM search that already existed, and a dashboard for whether the pipeline is working (#797)

Beenu Arora0968323adafc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 49d16fc74..c4b30ab30 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -196,6 +196,60 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **A SOC operations dashboard at `/dashboards/operations`.** `/dashboard`
+ answers what is happening in the estate; this answers whether the machine
+ that reports it is working. The distinction matters because every failure
+ mode of a detection pipeline makes it *quieter* — a connector stops polling,
+ a schema changes and events bounce, a token expires — and an alert-centric
+ view reports all three as good news.
+
+ Six panels, each backed by one endpoint and owning its own fetch, loading,
+ empty and error state: connector fleet staleness (`/health/fleet`), rejected
+ events by reason (`/health/dead-letters`), alert severity and disposition
+ (`/alerts/stats`), detection coverage counting only *enabled* rules
+ (`/detection/coverage`), agent runs/tokens/spend (`/costs/dashboard`), and
+ response actions paused for approval (`/approvals`). The first three had no
+ web client at all.
+
+ Fleet staleness is reported against each connector's own cadence — "3.2
+ intervals behind" rather than an absolute age, because a daily connector and
+ a five-minute connector are not late at the same wall-clock time. One dead
+ endpoint blanks one panel and names the failure; it does not take the page
+ down and does not substitute plausible figures.
+
+- **Federated SIEM search has a console surface.** `/api/v1/federated/backends`
+ and `/api/v1/federated/search` have fanned one query out to Splunk, Microsoft
+ Sentinel, Elastic and QRadar — in parallel, against each tenant's own
+ vault-encrypted credentials — for some time. `apps/web` had no client for
+ either, so the capability was reachable only from the SDK. `/federated-search`
+ now exposes it: pick which connected SIEMs to query, describe the search once
+ in free text plus optional `field operator value` filters, and read the merged
+ rows.
+
+ The design constraint the page is built around is the endpoint's per-source
+ isolation. It deliberately never fails the whole call because one backend is
+ slow, 401s or 5xxs; it returns a verdict per backend instead. A UI that
+ renders only the merged rows discards that, and the analyst cannot tell
+ "Sentinel has nothing" from "Sentinel did not answer" — opposite conclusions
+ mid-incident. So the per-backend strip renders above the rows, always, with
+ each backend's own row count, latency and error message. A backend that
+ failed shows no row count, because "0 rows" beside a timeout reads as
+ "nothing matched". An empty result set is labelled "No matching events" when
+ a backend answered and matched nothing, and "No backend returned results"
+ when every backend failed.
+
+ Recognised entities in a row deep-link to `/graph?entity=<type>:<value>`.
+ Recognition is a fixed per-vendor field-name list rather than a heuristic:
+ `src_ip`, `source.ip` and `SourceIP` all resolve to the same IP pivot, while
+ `zip`, `recipient` and `description` resolve to none.
+
+- **`/graph` honours `?entity=` and selects the node it names.** Three callers
+ already built that URL — the Investigation Rail's entity chips, `HuntView`'s
+ "Pivot to graph" button, and now federated search — and nothing read it, so
+ every pivot navigated to the graph and dropped the entity, leaving the
+ analyst to find the node by eye. Both the typed form (`host:WIN-DC01`) and
+ the bare form `HuntView` emits are accepted, matching on node id then label.
+
- **The Splunk warehouse driver executes.** It previously raised
`HuntNotConfigured("provider scaffolded but live SPL execution not yet
shipped")` on every call, so the SPL every hunt was translated into was
diff --git a/apps/docs/docs/console/federated-search.md b/apps/docs/docs/console/federated-search.md
new file mode 100644
index 000000000..96df36413
--- /dev/null
+++ b/apps/docs/docs/console/federated-search.md
@@ -0,0 +1,140 @@
+---
+sidebar_position: 6
+title: Federated search across your SIEMs
+description: Query Splunk, Microsoft Sentinel, Elastic and QRadar with one search from the AiSOC console, using your own stored credentials, and read a separate verdict for each backend.
+---
+
+# Federated search across your SIEMs
+
+Most SOCs run more than one place to search. An identity question lives in one system, endpoint telemetry in another, cloud audit logs in a third, and the answer to "where else did this account appear in the last hour" is spread across all of them. The usual cost is a tab per tool and a manual reconciliation at the end.
+
+`/federated-search` collapses that into one query. You describe what you are looking for once; AiSOC translates it per backend, runs the searches in parallel against the credentials that tenant already stored, and merges the rows.
+
+## What it queries
+
+Any connector instance the tenant has **enabled** whose type speaks a supported query language:
+
+| Connector type | Query language |
+| --- | --- |
+| `splunk` | SPL |
+| `microsoft_sentinel` | KQL |
+| `elastic` | ES\|QL |
+| `qradar` | AQL |
+
+You never write vendor syntax. The page takes a free-text string plus optional `field operator value` filters and the translator layer emits the right dialect for each backend.
+
+Connectors of other categories (EDR, IAM, SaaS) are not queried and are not listed on the page — they have no search surface to fan out to.
+
+## Reading the result
+
+The page is built around one property of the underlying endpoint that is easy to lose: **a slow or broken backend does not fail the search**. Each backend is queried inside its own error boundary and reports its own verdict. The response carries a `sources[]` array alongside the merged rows.
+
+That distinction matters more than it first appears. "Sentinel returned nothing" and "Sentinel did not answer" lead to opposite conclusions during an incident, and a UI that shows only merged rows renders them identically. So the per-backend strip sits **above** the rows and is always present:
+
+```
+Per-backend result 1 of 2 answered, 1 failed
+
+┌────────────────────────────┐ ┌────────────────────────────────────────┐
+│ Prod Splunk Answered │ │ Corp Sentinel Failed │
+│ Splunk · 1 row · 812 ms │ │ Microsoft Sentinel · 30000 ms │
+└────────────────────────────┘ │ connectors service unreachable: │
+ │ ReadTimeout │
+ └────────────────────────────────────────┘
+```
+
+Three rules the page follows so a partial answer cannot be misread as a complete one:
+
+- A backend with `status: error` shows **no row count**. Printing "0 rows" next to a timeout reads as "nothing matched", which is the one conclusion you must not draw from a failure.
+- When any backend fails, a banner states that the results are partial and that absence of rows from those sources is not evidence of absence of activity.
+- An empty result set is labelled differently depending on why it is empty: **"No matching events"** when at least one backend answered and matched nothing, **"No backend returned results"** when every backend failed.
+
+Each backend also reports its own latency, so a SIEM that is technically answering but taking 28 seconds is visible rather than hidden inside an aggregate.
+
+### Row caps
+
+`limit` applies per backend, then the merged set is capped again at the same figure. When that second cap trims rows the page says so explicitly — a silently truncated result is indistinguishable from a complete one.
+
+## Choosing backends
+
+By default every enabled, federated-capable connector is queried. Untick one to scope the search.
+
+The health dot next to each connector is its **last recorded poll status**, not a live probe. A connector that is healthy for ingest can still fail this particular query — wrong index, expired search token, a workspace the credential cannot read. The per-backend verdict after you run the search is the authoritative answer; the dot is only a hint about where to start.
+
+## Pivoting out of a result
+
+Recognised entities in a row render as pivot chips that deep-link into the attack graph at `/graph?entity=<type>:<value>` — the same URL shape the [Investigation Rail](./investigation-rail.md) entity chips use. The graph selects the node named by the parameter.
+
+Recognition is a fixed list of field names per entity type (`host`, `user`, `ip`, `domain`), covering the common spellings across vendors: `src_ip`, `source.ip` and `SourceIP` all resolve to the same IP pivot. It is deliberately not a heuristic — a substring rule that treats "anything containing `ip`" as an address also matches `zip`, `recipient` and `description`, and a pivot onto the wrong entity is worse than no pivot because it quietly widens the picture while looking correct. Columns that are not recognised render as plain text.
+
+Vendor placeholders for "field present but unset" (`-`, `null`, `n/a`, `unknown`) are skipped rather than linked.
+
+## Enabling it
+
+Federated search is behind a flag on the API service:
+
+```bash
+AISOC_FEATURE_FED_SEARCH=true
+```
+
+With the flag unset, `/api/v1/federated/*` answers `404` and the console page says the feature is turned off and names the variable, rather than showing a generic not-found. No query is sent while it is disabled.
+
+You also need at least one enabled connector of a supported type. With none, the page says so and links to `/connectors`.
+
+## Permissions and tenancy
+
+Both endpoints require `connectors:read`.
+
+Credentials never leave the API service. `POST /api/v1/federated/search` decrypts each connector's stored `auth_config` through the credential vault, forwards it to the stateless connectors service over the internal network, and the plaintext never round-trips to the browser. Connector selection is tenant-scoped in the query itself, so a `connector_id` belonging to another tenant resolves to "not found" rather than being queried.
+
+Every search writes an audit row recording the **shape** of the query — which fields were filtered, which backends were queried, how many rows came back, how long each took — and never the filter values. A federated query can legitimately contain regulated identifiers, and the audit log is shared across the tenant.
+
+## API
+
+```http
+GET /api/v1/federated/backends
+```
+
+```json
+{
+ "backends": [
+ {
+ "connector_id": "…",
+ "connector_type": "splunk",
+ "name": "Prod Splunk",
+ "health_status": "healthy",
+ "is_enabled": true
+ }
+ ]
+}
+```
+
+```http
+POST /api/v1/federated/search
+```
+
+```json
+{
+ "free_text": "failed logon",
+ "indicators": [{ "field": "user", "operator": "in", "value": ["alice", "bob"] }],
+ "since_seconds": 3600,
+ "limit": 100,
+ "connector_ids": null
+}
+```
+
+`connector_ids: null` (or omitted) means every enabled, federated-capable connector. Supplying a list scopes the fan-out; an id that is missing, disabled, or not federated-capable returns `404` naming it rather than being silently dropped, because a typo should be loud.
+
+Operators: `eq`, `ne`, `contains`, `starts_with`, `ends_with`, `gt`, `gte`, `lt`, `lte`, `in`. Indicators are AND-joined with each other and with `free_text`. `since_seconds` is capped at 7 days — use a SIEM-native search for longer windows.
+
+The response merges the rows and stamps each with its origin:
+
+```json
+{
+ "rows": [{ "host": "WIN-DC01", "_aisoc_source": { "connector_name": "Prod Splunk", "…": "…" } }],
+ "row_count": 1,
+ "sources": [{ "connector_id": "…", "status": "ok", "row_count": 1, "duration_ms": 812, "error": null }],
+ "truncated": false
+}
+```
+
+`sources[].status` is `ok`, `error` or `unsupported`. A non-`ok` entry never fails the request.
diff --git a/apps/docs/docs/console/operations-dashboard.md b/apps/docs/docs/console/operations-dashboard.md
new file mode 100644
index 000000000..e94748136
--- /dev/null
+++ b/apps/docs/docs/console/operations-dashboard.md
@@ -0,0 +1,87 @@
+---
+sidebar_position: 7
+title: SOC operations dashboard
+description: Whether the detection pipeline is working, independent of whether it is finding anything — connector staleness, rejected events, alert posture, detection coverage, agent spend and pending response actions.
+---
+
+# SOC operations dashboard
+
+`/dashboard` answers *what is happening in the estate*. `/dashboards/operations` answers a different question: **is the machine that tells me what is happening actually working?**
+
+That distinction matters because every failure mode of a detection pipeline makes it **quieter**. A connector stops polling, a schema changes and events start bouncing, an API token expires — and the alert queue gets calmer. An alert-centric dashboard reports that as good news. The only way to tell "the estate is quiet" from "the pipeline stopped" is to watch the pipeline directly.
+
+## Panels
+
+Each panel is backed by exactly one endpoint, owns its own fetch, and renders one of three states: real figures, an honest empty state, or an error state with a retry. **No panel substitutes sample data.** One dead endpoint blanks one panel and says why; it does not take the page down and does not quietly degrade its neighbours.
+
+### Connector fleet
+
+`GET /api/v1/health/fleet`
+
+Per-connector state, with the server's own operator-actionable wording (`No successful sync for 3.2 poll intervals`) rendered verbatim rather than re-derived into a generic "unhealthy".
+
+Staleness is measured **against each connector's own configured cadence**, which is why the panel reports "3.2 intervals behind" rather than an absolute age. A single global threshold would page constantly on a daily connector and stay silent on a five-minute one, and a surface that pages constantly is a surface that gets muted. Below one missed interval the panel falls back to wall-clock ("synced 12m ago"), which is the more useful reading when nothing is actually late.
+
+Rows sort worst-first. The header badge counts `failed + degraded`, because the fleet is as healthy as its least healthy connector — averaging would let nineteen working connectors hide the one that stopped, and the one that stopped is the whole question.
+
+### Pipeline health
+
+`GET /api/v1/health/pipeline`
+
+The existing per-stage widget (ingest → normalize → fuse → correlate → alert), reused rather than reimplemented.
+
+### Rejected events
+
+`GET /api/v1/health/dead-letters?hours=24`
+
+The companion to fleet health. A connector can poll happily while everything it produces is refused downstream for a schema mismatch, and the symptom from the alert queue is identical: nothing arrives.
+
+Grouped by reason, so the fix is visible from the panel. "Nothing rejected" renders as its own explicit state rather than an empty list, because zero is a real answer here and should not look like a panel that failed to load.
+
+### Alert posture
+
+`GET /api/v1/alerts/stats`
+
+Total, new in 24h, critical still open, plus severity and disposition distributions.
+
+This is a **snapshot, not a trend**, and the panel says so. No endpoint in the tree buckets disposition over time, so there is no series to draw. Period-over-period movement is published by `/metrics/funnel` and rendered by the funnel strip at the top of the page; nothing here duplicates it with an arrow it cannot source.
+
+### Detection coverage
+
+`GET /api/v1/detection/coverage`
+
+Techniques with at least one **enabled** rule, over total techniques. The active-versus-total distinction is the point: a corpus of 800 rules with half disabled covers far less than the headline suggests, and a disabled rule is exactly as useful as no rule. Disabled rules are named explicitly rather than folded into a total.
+
+"Thinnest tactics" ranks by active-coverage ratio — the part an operator can act on this week. Techniques with no tactic attribution are counted in the summary but not ranked, because inventing an "Unknown" bucket would imply a gap in a tactic that does not exist.
+
+### Agent throughput and spend
+
+`GET /api/v1/costs/dashboard?window_days=7`
+
+Real recorded token counts and spend, joined from `aisoc_run_costs` to `investigation_runs` — measured usage, not a projection or a list price.
+
+The counter is labelled **runs**, because `total_runs` counts investigation runs. Labelling it "alerts triaged" would be a different measurement than the one the endpoint takes. The average cost per run is rendered only when the server supplies it; dividing locally when the server returned `null` would manufacture a figure it declined to state.
+
+### Actions awaiting approval
+
+`GET /api/v1/approvals?status=pending`
+
+The agent pauses before a high-risk action — isolate a host, disable an account, revoke a session — and waits. Until someone decides, the containment has not happened, so an approval sitting unnoticed for two hours is an incident still running. The panel sorts by risk then age, and shows how long each has been waiting.
+
+Deciding happens on `/responder/approvals`, which already does it properly with full context and deny-with-comment. This panel links there rather than growing a second approve button: a one-tap irreversible action inside a dashboard tile is a worse affordance than a link to the surface built for it.
+
+## Permissions
+
+| Panel | Permission |
+| --- | --- |
+| Connector fleet, rejected events, pipeline health | authenticated |
+| Alert posture | `alerts:read` |
+| Detection coverage | `rules:read` |
+| Agent throughput and spend | `reports:read` |
+| Actions awaiting approval | authenticated |
+
+A panel whose permission the caller lacks shows its error state with the API's own message, rather than disappearing — a missing panel is indistinguishable from a healthy one.
+
+## Refresh cadences
+
+Fleet health, rejected events, alert posture: 60s. Pending approvals: 30s. Agent spend: 120s. Detection coverage: 5 minutes. These are chosen against how fast each figure can meaningfully change, not set uniformly.
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index 17e4af554..c3da54698 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -53,6 +53,8 @@ const sidebars: SidebarsConfig = {
"console/queue",
"console/rule-tuning",
"console/investigation-rail",
+ "console/federated-search",
+ "console/operations-dashboard",
"console/public-replay",
],
},
diff --git a/apps/web/src/app/(app)/dashboards/operations/page.tsx b/apps/web/src/app/(app)/dashboards/operations/page.tsx
new file mode 100644
index 000000000..60f86c4c3
--- /dev/null
+++ b/apps/web/src/app/(app)/dashboards/operations/page.tsx
@@ -0,0 +1,15 @@
+import { OperationsDashboard } from '@/components/dashboard/operations/OperationsDashboard';
+
+export const metadata = {
+ title: 'SOC operations',
+ description:
+ 'Connector staleness, rejected events, alert posture, detection coverage, agent spend and pending response actions — whether the pipeline is working, independent of what it is finding.',
+};
+
+export const dynamic = 'force-dynamic';
+export const revalidate = 0;
+export const fetchCache = 'force-no-store';
+
+export default function OperationsDashboardPage() {
+ return <OperationsDashboard />;
+}
diff --git a/apps/web/src/app/(app)/federated-search/page.tsx b/apps/web/src/app/(app)/federated-search/page.tsx
new file mode 100644
index 000000000..4ffaf240c
--- /dev/null
+++ b/apps/web/src/app/(app)/federated-search/page.tsx
@@ -0,0 +1,17 @@
+import { FederatedSearchView } from '@/components/federated/FederatedSearchView';
+
+export const metadata = {
+ title: 'Federated search',
+ description:
+ 'Query every connected SIEM in one place, with a per-backend verdict for each.',
+};
+
+// The view issues tenant-scoped, credential-backed queries. Nothing about it
+// is cacheable across requests.
+export const dynamic = 'force-dynamic';
+export const revalidate = 0;
+export const fetchCache = 'force-no-store';
+
+export default function FederatedSearchPage() {
+ return <FederatedSearchView />;
+}
diff --git a/apps/web/src/components/dashboard/operations/AgentThroughputPanel.tsx b/apps/web/src/components/dashboard/operations/AgentThroughputPanel.tsx
new file mode 100644
index 000000000..01d70cc1a
--- /dev/null
+++ b/apps/web/src/components/dashboard/operations/AgentThroughputPanel.tsx
@@ -0,0 +1,139 @@
+'use client';
+
+/**
+ * What the agents actually did, and what it cost.
+ *
+ * `GET /api/v1/costs/dashboard` joins `aisoc_run_costs` to `investigation_runs`
+ * — real recorded token counts and spend from real runs, not a projection. The
+ * client existed (`costsApi.dashboard`) and was used only by the admin cost
+ * page; the throughput reading it supports belongs next to pipeline health,
+ * because "the agents triaged nothing today" and "the agents cost nothing
+ * today" are the same row of data read two ways.
+ *
+ * `total_runs` is investigation runs, not alerts triaged. The panel labels it
+ * as runs. Calling it "alerts triaged" would be a different measurement than
+ * the one the endpoint makes.
+ */
+
+import useSWR from 'swr';
+import { costsApi } from '@/lib/api';
+import { EmptyState } from '@/components/ui/EmptyState';
+import { ErrorState } from '@/components/ui/ErrorState';
+
+const WINDOW_DAYS = 7;
+
+function formatUsd(value: number): string {
+ if (!Number.isFinite(value)) return '—';
+ return value < 1 ? `$${value.toFixed(4)}` : `$${value.toFixed(2)}`;
+}
+
+function formatCompact(value: number): string {
+ if (!Number.isFinite(value)) return '—';
+ if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
+ if (value >= 1_000) return `${(value / 1_000).toFixed(1)}k`;
+ return value.toLocaleString();
+}
+
+export function AgentThroughputPanel() {
+ const { data, error, isLoading, mutate } = useSWR(
+ `ops-agent-cost:${WINDOW_DAYS}`,
+ () => costsApi.dashboard({ window_days: WINDOW_DAYS }),
+ { refreshInterval: 120_000, revalidateOnFocus: false },
+ );
+
+ const headline = data?.headline;
+ const byModel = data?.by_model ?? [];
+ const maxModelCost = Math.max(...byModel.map((m) => m.total_cost_usd), 0.0001);
+
+ return (
+ <section
+ aria-labelledby="ops-agent-heading"
+ className="rounded-xl border border-gray-800/60 bg-gray-900/40"
+ >
+ <div className="px-4 py-3">
+ <h2 id="ops-agent-heading" className="text-sm font-medium text-gray-300">
+ Agent throughput and spend
+ </h2>
+ <p className="mt-0.5 text-[11px] text-gray-500">
+ Recorded token usage from the last {WINDOW_DAYS} days of investigation runs.
+ </p>
+ </div>
+
+ {isLoading && !data ? (
+ <div className="m-4 h-28 animate-pulse rounded bg-gray-800/40" />
+ ) : error ? (
+ <ErrorState
+ title="Agent telemetry unavailable"
+ error={error}
+ onRetry={() => {
+ void mutate();
+ }}
+ className="m-4"
+ />
+ ) : !headline || headline.total_runs === 0 ? (
+ <EmptyState
+ title="No agent runs in this window"
+ description={`Nothing has been investigated in the last ${WINDOW_DAYS} days, so there is no token usage to report.`}
+ className="m-4"
+ />
+ ) : (
+ <div className="space-y-4 px-4 pb-4">
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ <Stat label="Runs" value={headline.total_runs.toLocaleString()} />
+ <Stat label="LLM calls" value={formatCompact(headline.total_calls)} />
+ <Stat label="Tokens" value={formatCompact(headline.total_tokens)} />
+ <Stat label="Spend" value={formatUsd(headline.total_cost_usd)} />
+ </div>
+
+ {/* Only render the derived per-run figure the server computed. When
+ it is null the server had no basis for it, and dividing here
+ would invent one. */}
+ {headline.avg_cost_per_run_usd != null && (
+ <p className="text-[11px] text-gray-500">
+ {`${formatUsd(headline.avg_cost_per_run_usd)} per run on average.`}
+ </p>
+ )}
+
+ {byModel.length > 0 && (
+ <div>
+ <p className="mb-2 text-[11px] uppercase tracking-wider text-gray-500">
+ By model
+ </p>
+ <ul className="space-y-2">
+ {byModel.map((m) => (
+ <li key={m.model}>
+ <div className="mb-1 flex items-baseline justify-between gap-3">
+ <span className="truncate font-mono text-[11px] text-gray-300">
+ {m.model}
+ </span>
+ <span className="shrink-0 text-[11px] text-gray-500">
+ {`${m.runs} runs · ${formatUsd(m.total_cost_usd)}`}
+ </span>
+ </div>
+ <div className="h-1 rounded-full bg-gray-800">
+ <div
+ className="h-1 rounded-full bg-indigo-500/60"
+ style={{
+ width: `${Math.round((m.total_cost_usd / maxModelCost) * 100)}%`,
+ }}
+ />
+ </div>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ )}
+ </section>
+ );
+}
+
+function Stat({ label, value }: { label: string; value: string }) {
+ return (
+ <div>
+ <p className="text-[11px] uppercase tracking-wider text-gray-500">{label}</p>
+ <p className="text-xl font-semibold text-gray-100">{value}</p>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/dashboard/operations/AlertPosturePanel.tsx b/apps/web/src/components/dashboard/operations/AlertPosturePanel.tsx
new file mode 100644
index 000000000..0a3e8f473
--- /dev/null
+++ b/apps/web/src/components/dashboard/operations/AlertPosturePanel.tsx
@@ -0,0 +1,197 @@
+'use client';
+
+/**
+ * Where the alert backlog actually sits.
+ *
+ * `GET /api/v1/alerts/stats` returns the severity and status distributions
+ * plus the two counters worth acting on: what arrived in the last 24 hours,
+ * and how many critical alerts are still open.
+ *
+ * The status distribution is the disposition picture. It is a point-in-time
+ * snapshot rather than a series — no endpoint in the tree buckets disposition
+ * over time — and the panel says so instead of implying a trend it cannot
+ * source. `/metrics/funnel` publishes real period-over-period deltas for the
+ * funnel stages and is rendered by `FunnelKpiBar`; nothing here duplicates it
+ * with invented arrows.
+ */
+
+import useSWR from 'swr';
+import { clsx } from 'clsx';
+import { operationsApi } from '@/lib/api';
+import { EmptyState } from '@/components/ui/EmptyState';
+import { ErrorState } from '@/components/ui/ErrorState';
+
+const SEVERITY_ORDER = ['critical', 'high', 'medium', 'low', 'info'] as const;
+
+const SEVERITY_COLOR: Record<string, string> = {
+ critical: 'bg-red-500',
+ high: 'bg-orange-500',
+ medium: 'bg-yellow-500',
+ low: 'bg-blue-500',
+ info: 'bg-slate-500',
+};
+
+/** Statuses the API is known to emit, in workflow order. Unknown keys append. */
+const STATUS_ORDER = [
+ 'new',
+ 'triaged',
+ 'investigating',
+ 'escalated',
+ 'resolved',
+ 'false_positive',
+ 'suppressed',
+] as const;
+
+function orderedEntries(
+ counts: Record<string, number>,
+ preferred: readonly string[],
+): Array<[string, number]> {
+ const known = preferred.filter((k) => k in counts).map<[string, number]>((k) => [k, counts[k]]);
+ const rest = Object.entries(counts)
+ .filter(([k]) => !preferred.includes(k))
+ .sort((a, b) => b[1] - a[1]);
+ return [...known, ...rest];
+}
+
+function humanise(key: string): string {
+ return key.replace(/_/g, ' ').replace(/^\w/, (c) => c.toUpperCase());
+}
+
+export function AlertPosturePanel() {
+ const { data, error, isLoading, mutate } = useSWR(
+ 'ops-alert-stats',
+ () => operationsApi.alertStats(),
+ { refreshInterval: 60_000, revalidateOnFocus: false },
+ );
+
+ const severities = data ? orderedEntries(data.by_severity ?? {}, SEVERITY_ORDER) : [];
+ const statuses = data ? orderedEntries(data.by_status ?? {}, STATUS_ORDER) : [];
+ const severityTotal = severities.reduce((sum, [, n]) => sum + n, 0);
+ const statusTotal = statuses.reduce((sum, [, n]) => sum + n, 0);
+
+ return (
+ <section
+ aria-labelledby="ops-posture-heading"
+ className="rounded-xl border border-gray-800/60 bg-gray-900/40"
+ >
+ <div className="px-4 py-3">
+ <h2 id="ops-posture-heading" className="text-sm font-medium text-gray-300">
+ Alert posture
+ </h2>
+ <p className="mt-0.5 text-[11px] text-gray-500">
+ Current distribution. A snapshot, not a trend — no endpoint buckets
+ disposition over time.
+ </p>
+ </div>
+
+ {isLoading && !data ? (
+ <div className="m-4 h-28 animate-pulse rounded bg-gray-800/40" />
+ ) : error ? (
+ <ErrorState
+ title="Alert statistics unavailable"
+ error={error}
+ onRetry={() => {
+ void mutate();
+ }}
+ className="m-4"
+ />
+ ) : !data || data.total === 0 ? (
+ <EmptyState
+ title="No alerts recorded"
+ description="Severity and disposition counts populate once the pipeline promotes its first alert."
+ className="m-4"
+ />
+ ) : (
+ <div className="space-y-4 px-4 pb-4">
+ <div className="grid grid-cols-3 gap-3">
+ <div>
+ <p className="text-[11px] uppercase tracking-wider text-gray-500">Total</p>
+ <p className="text-2xl font-semibold text-gray-100">
+ {data.total.toLocaleString()}
+ </p>
+ </div>
+ <div>
+ <p className="text-[11px] uppercase tracking-wider text-gray-500">New (24h)</p>
+ <p className="text-2xl font-semibold text-blue-300">
+ {data.new_last_24h.toLocaleString()}
+ </p>
+ </div>
+ <div>
+ <p className="text-[11px] uppercase tracking-wider text-gray-500">Critical open</p>
+ <p
+ className={clsx(
+ 'text-2xl font-semibold',
+ data.critical_open > 0 ? 'text-red-300' : 'text-gray-100',
+ )}
+ >
+ {data.critical_open.toLocaleString()}
+ </p>
+ </div>
+ </div>
+
+ <StackedBar
+ label="By severity"
+ entries={severities}
+ total={severityTotal}
+ colorFor={(k) => SEVERITY_COLOR[k] ?? 'bg-slate-600'}
+ />
+ <StackedBar
+ label="By disposition"
+ entries={statuses}
+ total={statusTotal}
+ colorFor={(k) => (k === 'false_positive' ? 'bg-violet-500' : 'bg-teal-500')}
+ />
+ </div>
+ )}
+ </section>
+ );
+}
+
+function StackedBar({
+ label,
+ entries,
+ total,
+ colorFor,
+}: {
+ label: string;
+ entries: Array<[string, number]>;
+ total: number;
+ colorFor: (key: string) => string;
+}) {
+ if (entries.length === 0 || total === 0) {
+ return (
+ <div>
+ <p className="mb-1.5 text-[11px] uppercase tracking-wider text-gray-500">{label}</p>
+ <p className="text-xs text-gray-600">No breakdown reported.</p>
+ </div>
+ );
+ }
+
+ return (
+ <div>
+ <p className="mb-1.5 text-[11px] uppercase tracking-wider text-gray-500">{label}</p>
+ <div className="flex h-2 overflow-hidden rounded-full bg-gray-800">
+ {entries.map(([key, n]) => (
+ <div
+ key={key}
+ className={colorFor(key)}
+ style={{ width: `${(n / total) * 100}%` }}
+ // One template literal, one text node. Several adjacent JSX
+ // children here would get `<!-- -->` separators injected during
+ // SSR that the client does not reproduce (React #418).
+ title={`${humanise(key)}: ${n}`}
+ />
+ ))}
+ </div>
+ <ul className="mt-2 flex flex-wrap gap-x-4 gap-y-1">
+ {entries.map(([key, n]) => (
+ <li key={key} className="flex items-center gap-1.5 text-[11px]">
+ <span className={clsx('h-1.5 w-1.5 rounded-full', colorFor(key))} aria-hidden="true" />
+ <span className="text-gray-400">{humanise(key)}</span>
+ <span className="text-gray-300">{n.toLocaleString()}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/dashboard/operations/ConnectorFleetPanel.tsx b/apps/web/src/components/dashboard/operations/ConnectorFleetPanel.tsx
new file mode 100644
index 000000000..a84ce0178
--- /dev/null
+++ b/apps/web/src/components/dashboard/operations/ConnectorFleetPanel.tsx
@@ -0,0 +1,164 @@
+'use client';
+
+/**
+ * Connector fleet health.
+ *
+ * This is the panel the alert-centric dashboards structurally cannot provide.
+ * When a connector stops polling, alerts from that source stop arriving, and
+ * every alert-shaped widget in the console gets *quieter*. An absence of
+ * alerts is indistinguishable from an absence of threats unless something is
+ * watching the sources themselves.
+ *
+ * `GET /api/v1/health/fleet` has been writing that answer for a while with
+ * nothing reading it. It judges staleness per connector against that
+ * connector's own configured cadence, which is why this panel reports
+ * "3.2 intervals missed" rather than an absolute age: a daily connector and a
+ * five-minute connector are not late at the same wall-clock time.
+ */
+
+import useSWR from 'swr';
+import Link from 'next/link';
+import { clsx } from 'clsx';
+import { operationsApi, type FleetConnectorHealth, type FleetHealthState } from '@/lib/api';
+import { EmptyState } from '@/components/ui/EmptyState';
+import { ErrorState } from '@/components/ui/ErrorState';
+
+const STATE_STYLE: Record<FleetHealthState, { dot: string; text: string; label: string }> = {
+ healthy: { dot: 'bg-green-500', text: 'text-green-300', label: 'Healthy' },
+ degraded: { dot: 'bg-yellow-500', text: 'text-yellow-300', label: 'Degraded' },
+ failed: { dot: 'bg-red-500', text: 'text-red-300', label: 'Failed' },
+ unproven: { dot: 'bg-blue-500', text: 'text-blue-300', label: 'Never synced' },
+ disabled: { dot: 'bg-gray-600', text: 'text-gray-400', label: 'Disabled' },
+};
+
+/** Order worst-first so the answer is the first thing read. */
+const STATE_ORDER: FleetHealthState[] = ['failed', 'degraded', 'unproven', 'healthy', 'disabled'];
+
+export function formatStaleness(row: FleetConnectorHealth): string {
+ if (row.last_sync === null) return 'never synced';
+
+ const missed = row.missed_intervals;
+ if (missed !== null && missed >= 1) {
+ // Cadence-relative is the actionable framing: "two intervals late" tells
+ // an operator it is genuinely behind, where "22 minutes" does not unless
+ // they also remember the interval.
+ return `${missed.toFixed(1)} intervals behind`;
+ }
+
+ const secs = row.seconds_since_sync;
+ if (secs === null) return 'sync time unknown';
+ if (secs < 90) return 'synced just now';
+ if (secs < 3600) return `synced ${Math.round(secs / 60)}m ago`;
+ if (secs < 86_400) return `synced ${Math.round(secs / 3600)}h ago`;
+ return `synced ${Math.round(secs / 86_400)}d ago`;
+}
+
+function ConnectorRow({ row }: { row: FleetConnectorHealth }) {
+ const style = STATE_STYLE[row.state] ?? STATE_STYLE.unproven;
+ return (
+ <li
+ className="flex items-start gap-3 border-t border-gray-800/40 px-4 py-2.5 first:border-t-0"
+ data-testid={`fleet-row-${row.connector_id}`}
+ >
+ <span className={clsx('mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full', style.dot)} aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-baseline gap-x-2">
+ <span className="truncate text-sm text-gray-200">{row.name}</span>
+ <span className="text-[11px] text-gray-500">{row.connector_type}</span>
+ <span className={clsx('text-[11px]', style.text)}>{style.label}</span>
+ </div>
+ {/* The server writes operator-actionable wording; render it verbatim
+ rather than re-deriving a status string from the same fields. */}
+ <p className="mt-0.5 text-[11px] text-gray-500">{row.reason}</p>
+ </div>
+ <div className="shrink-0 text-right text-[11px] text-gray-500">
+ <div>{formatStaleness(row)}</div>
+ <div className="mt-0.5">
+ {row.events_ingested.toLocaleString()} events
+ {row.error_count > 0 ? ` · ${row.error_count} errors` : ''}
+ </div>
+ </div>
+ </li>
+ );
+}
+
+export function ConnectorFleetPanel() {
+ const { data, error, isLoading, mutate } = useSWR(
+ 'ops-fleet-health',
+ () => operationsApi.fleetHealth(),
+ { refreshInterval: 60_000, revalidateOnFocus: false },
+ );
+
+ const connectors = data?.connectors ?? [];
+ const sorted = [...connectors].sort(
+ (a, b) => STATE_ORDER.indexOf(a.state) - STATE_ORDER.indexOf(b.state),
+ );
+ const counts = data?.counts;
+ const needsAttention = (counts?.failed ?? 0) + (counts?.degraded ?? 0);
+
+ return (
+ <section
+ aria-labelledby="ops-fleet-heading"
+ className="rounded-xl border border-gray-800/60 bg-gray-900/40"
+ >
+ <div className="flex items-baseline justify-between px-4 py-3">
+ <div>
+ <h2 id="ops-fleet-heading" className="text-sm font-medium text-gray-300">
+ Connector fleet
+ </h2>
+ <p className="mt-0.5 text-[11px] text-gray-500">
+ Staleness measured against each connector&apos;s own poll cadence.
+ </p>
+ </div>
+ {data && (
+ <span
+ className={clsx(
+ 'shrink-0 rounded-full px-2 py-0.5 text-[11px] font-medium',
+ needsAttention > 0
+ ? 'bg-red-500/10 text-red-300'
+ : 'bg-green-500/10 text-green-300',
+ )}
+ >
+ {needsAttention > 0
+ ? `${needsAttention} need attention`
+ : 'All sources reporting'}
+ </span>
+ )}
+ </div>
+
+ {isLoading && !data ? (
+ <div className="m-4 h-24 animate-pulse rounded bg-gray-800/40" />
+ ) : error ? (
+ <ErrorState
+ title="Fleet health unavailable"
+ description="Connector staleness is unknown right now. Treat a quiet alert queue as unexplained until this recovers."
+ error={error}
+ onRetry={() => {
+ void mutate();
+ }}
+ className="m-4"
+ />
+ ) : connectors.length === 0 ? (
+ <EmptyState
+ title="No connectors configured"
+ description="Nothing is feeding the pipeline yet, so an empty alert queue is expected."
+ action={
+ <Link
+ href="/connectors"
+ className="text-sm text-blue-400 underline underline-offset-2 hover:text-blue-300"
+ >
+ Connect a source
+ </Link>
+ }
+ className="m-4"
+ />
+ ) : (
+ <ul>
+ {sorted.map((row) => (
+ <ConnectorRow key={row.connector_id} row={row} />
+ ))}
+ </ul>
+ )}
+ </section>
+ );
+}
diff --git a/apps/web/src/components/dashboard/operations/DetectionCoveragePanel.tsx b/apps/web/src/components/dashboard/operations/DetectionCoveragePanel.tsx
new file mode 100644
index 000000000..da760a356
--- /dev/null
+++ b/apps/web/src/components/dashboard/operations/DetectionCoveragePanel.tsx
@@ -0,0 +1,162 @@
+'use client';
+
+/**
+ * Detection coverage, as a ratio of techniques with at least one *active* rule.
+ *
+ * `GET /api/v1/detection/coverage` distinguishes total rules from active ones
+ * and counts techniques covered by an active rule. That distinction is the
+ * whole point: a corpus of 800 rules with half of them disabled covers far
+ * less than the headline rule count implies, and a disabled rule is exactly as
+ * useful as no rule.
+ *
+ * The panel therefore leads with covered-vs-total techniques, names the number
+ * of inactive rules explicitly rather than folding them into a total, and
+ * lists the tactics with the thinnest active coverage — which is the part an
+ * operator can act on this week.
+ */
+
+import useSWR from 'swr';
+import Link from 'next/link';
+import { clsx } from 'clsx';
+import { detectionApi, type DetectionCoverage } from '@/lib/api';
+import { EmptyState } from '@/components/ui/EmptyState';
+import { ErrorState } from '@/components/ui/ErrorState';
+
+/** Tactics ranked by how little active coverage they have. */
+export function thinnestTactics(
+ coverage: DetectionCoverage,
+ take = 5,
+): Array<{ tactic: string; covered: number; total: number }> {
+ const byTactic = new Map<string, { covered: number; total: number }>();
+
+ for (const cell of coverage.cells) {
+ // Cells carry `tactic: string | null`. A technique with no tactic cannot
+ // be attributed to one, so it is counted in the summary above but not
+ // ranked here — inventing an "Unknown" bucket would imply a gap in a
+ // tactic that does not exist.
+ if (!cell.tactic) continue;
+ const entry = byTactic.get(cell.tactic) ?? { covered: 0, total: 0 };
+ entry.total += 1;
+ if (cell.activeRules > 0) entry.covered += 1;
+ byTactic.set(cell.tactic, entry);
+ }
+
+ return [...byTactic.entries()]
+ .map(([tactic, v]) => ({ tactic, ...v }))
+ .sort((a, b) => a.covered / Math.max(a.total, 1) - b.covered / Math.max(b.total, 1))
+ .slice(0, take);
+}
+
+export function DetectionCoveragePanel() {
+ const { data, error, isLoading, mutate } = useSWR(
+ 'ops-detection-coverage',
+ () => detectionApi.coverage(),
+ { refreshInterval: 300_000, revalidateOnFocus: false },
+ );
+
+ const summary = data?.summary;
+ const ratio =
+ summary && summary.techniques > 0 ? summary.coveredTechniques / summary.techniques : null;
+
+ return (
+ <section
+ aria-labelledby="ops-coverage-heading"
+ className="rounded-xl border border-gray-800/60 bg-gray-900/40"
+ >
+ <div className="px-4 py-3">
+ <h2 id="ops-coverage-heading" className="text-sm font-medium text-gray-300">
+ Detection coverage
+ </h2>
+ <p className="mt-0.5 text-[11px] text-gray-500">
+ Techniques with at least one enabled rule. A disabled rule covers nothing.
+ </p>
+ </div>
+
+ {isLoading && !data ? (
+ <div className="m-4 h-24 animate-pulse rounded bg-gray-800/40" />
+ ) : error ? (
+ <ErrorState
+ title="Coverage unavailable"
+ error={error}
+ onRetry={() => {
+ void mutate();
+ }}
+ className="m-4"
+ />
+ ) : !summary || summary.techniques === 0 ? (
+ <EmptyState
+ title="No detection rules loaded"
+ description="Coverage is computed from the rules this tenant has enabled."
+ action={
+ <Link
+ href="/detection"
+ className="text-sm text-blue-400 underline underline-offset-2 hover:text-blue-300"
+ >
+ Browse detection rules
+ </Link>
+ }
+ className="m-4"
+ />
+ ) : (
+ <div className="space-y-4 px-4 pb-4">
+ <div className="flex items-end gap-6">
+ <div>
+ <p className="text-[11px] uppercase tracking-wider text-gray-500">
+ Techniques covered
+ </p>
+ <p className="text-2xl font-semibold text-gray-100">
+ {`${summary.coveredTechniques} / ${summary.techniques}`}
+ </p>
+ </div>
+ <div>
+ <p className="text-[11px] uppercase tracking-wider text-gray-500">Active rules</p>
+ <p className="text-2xl font-semibold text-gray-100">
+ {summary.activeRules.toLocaleString()}
+ </p>
+ {summary.inactiveRules > 0 && (
+ <p className="text-[11px] text-amber-300/80">
+ {`${summary.inactiveRules.toLocaleString()} disabled`}
+ </p>
+ )}
+ </div>
+ </div>
+
+ {ratio !== null && (
+ <div>
+ <div className="h-1.5 rounded-full bg-gray-800">
+ <div
+ className={clsx(
+ 'h-1.5 rounded-full',
+ ratio >= 0.6 ? 'bg-green-500/70' : ratio >= 0.3 ? 'bg-yellow-500/70' : 'bg-red-500/70',
+ )}
+ style={{ width: `${Math.round(ratio * 100)}%` }}
+ />
+ </div>
+ <p className="mt-1 text-[11px] text-gray-500">
+ {`${Math.round(ratio * 100)}% of known techniques have an enabled rule.`}
+ </p>
+ </div>
+ )}
+
+ {data && (
+ <div>
+ <p className="mb-2 text-[11px] uppercase tracking-wider text-gray-500">
+ Thinnest tactics
+ </p>
+ <ul className="space-y-1.5">
+ {thinnestTactics(data).map((t) => (
+ <li key={t.tactic} className="flex items-baseline justify-between gap-3">
+ <span className="truncate text-xs text-gray-300">{t.tactic}</span>
+ <span className="shrink-0 text-[11px] text-gray-500">
+ {`${t.covered}/${t.total} covered`}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx b/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx
new file mode 100644
index 000000000..3b7289987
--- /dev/null
+++ b/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx
@@ -0,0 +1,442 @@
+/**
+ * SOC operations dashboard.
+ *
+ * Two properties under test.
+ *
+ * **Honesty.** Each panel renders real figures, an honest empty state, or an
+ * error state — never a plausible-looking number it did not receive. These
+ * dashboards have shipped the third option before, so the assertions are
+ * written as negatives against the specific failure: nothing numeric on the
+ * screen when the API is down.
+ *
+ * **Isolation.** Each panel owns its own fetch. One dead endpoint must blank
+ * one panel and say why, not take the page down and not silently degrade the
+ * others. That is asserted directly by failing one endpoint and checking the
+ * rest still render their real values.
+ */
+
+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
+import { cleanup, render, screen, within } from '@testing-library/react';
+import { SWRConfig } from 'swr';
+import { axe } from 'vitest-axe';
+
+const fleetHealth = vi.hoisted(() => vi.fn());
+const deadLetters = vi.hoisted(() => vi.fn());
+const alertStats = vi.hoisted(() => vi.fn());
+const costDashboard = vi.hoisted(() => vi.fn());
+const listApprovals = vi.hoisted(() => vi.fn());
+const coverage = vi.hoisted(() => vi.fn());
+const getFunnel = vi.hoisted(() => vi.fn());
+const getPipelineHealth = vi.hoisted(() => vi.fn());
+
+vi.mock('@/lib/api', () => ({
+ __esModule: true,
+ operationsApi: { fleetHealth, deadLetters, alertStats },
+ costsApi: { dashboard: costDashboard },
+ responderApi: { listApprovals },
+ detectionApi: { coverage },
+ metricsApi: { getFunnel, getPipelineHealth },
+}));
+
+vi.mock('next/link', () => ({
+ __esModule: true,
+ default: ({ children, href }: { children: React.ReactNode; href: string }) => (
+ <a href={href}>{children}</a>
+ ),
+}));
+
+import { OperationsDashboard } from './OperationsDashboard';
+import { formatStaleness } from './ConnectorFleetPanel';
+import { formatWaitingFor } from './ResponseActionsPanel';
+import { thinnestTactics } from './DetectionCoveragePanel';
+
+const FLEET = {
+ generated_at: '2026-05-06T12:00:00Z',
+ state: 'degraded',
+ counts: { healthy: 1, degraded: 1, failed: 0, unproven: 0, disabled: 0 },
+ connectors: [
+ {
+ connector_id: 'c-healthy',
+ name: 'Prod CloudTrail',
+ connector_type: 'aws_cloudtrail',
+ state: 'healthy' as const,
+ reason: 'Synced 2 minutes ago, within its 5 minute cadence.',
+ last_sync: '2026-05-06T11:58:00Z',
+ seconds_since_sync: 120,
+ poll_interval_seconds: 300,
+ missed_intervals: 0.4,
+ error_count: 0,
+ events_ingested: 48_120,
+ oauth_refresh_failures: 0,
+ schema_drift_at: null,
+ },
+ {
+ connector_id: 'c-stale',
+ name: 'Corp Okta',
+ connector_type: 'okta',
+ state: 'degraded' as const,
+ reason: 'No successful sync for 3.2 poll intervals.',
+ last_sync: '2026-05-06T11:44:00Z',
+ seconds_since_sync: 960,
+ poll_interval_seconds: 300,
+ missed_intervals: 3.2,
+ error_count: 4,
+ events_ingested: 900,
+ oauth_refresh_failures: 1,
+ schema_drift_at: null,
+ },
+ ],
+};
+
+const DEAD_LETTERS = {
+ window_hours: 24,
+ total: 17,
+ by_reason: [
+ { reason: 'schema_validation_failed', count: 12 },
+ { reason: 'unknown_tenant', count: 5 },
+ ],
+ truncated: false,
+ dead_letters: [],
+};
+
+const ALERT_STATS = {
+ total: 128,
+ by_severity: { critical: 3, high: 14, medium: 60, low: 51 },
+ by_status: { new: 22, investigating: 9, resolved: 80, false_positive: 17 },
+ new_last_24h: 22,
+ critical_open: 3,
+};
+
+const COSTS = {
+ tenant_id: 't',
+ period: { start: '', end: '', window_days: 7, label: '7d' },
+ headline: {
+ total_cost_usd: 4.21,
+ total_tokens: 1_840_000,
+ total_calls: 612,
+ total_runs: 96,
+ avg_cost_per_run_usd: 0.0438,
+ },
+ daily_costs: [],
+ by_model: [
+ {
+ model: 'local-llm',
+ runs: 96,
+ calls: 612,
+ total_prompt_tokens: 1_500_000,
+ total_completion_tokens: 340_000,
+ total_cost_usd: 4.21,
+ imputed_public_cost_usd: 9.1,
+ avg_latency_ms: 880,
+ },
+ ],
+ top_cases: [],
+ action_counts: [],
+ byok_savings: {
+ is_byok_active: true,
+ provider: 'local',
+ recorded_cost_usd: 4.21,
+ imputed_public_cost_usd: 9.1,
+ savings_usd: 4.89,
+ },
+};
+
+const APPROVALS = {
+ items: [
+ {
+ id: 'ap-1',
+ tenant_id: 't',
+ run_id: null,
+ case_id: 'INC-1',
+ alert_id: null,
+ requested_by: 'agent',
+ required_user_id: null,
+ required_topic: null,
+ title: 'Isolate WIN-DC01',
+ summary: 'Ransomware encryption behaviour observed.',
+ risk_level: 'critical' as const,
+ action: {},
+ status: 'pending' as const,
+ decided_by_id: null,
+ decided_at: null,
+ decision_comment: null,
+ expires_at: null,
+ created_at: new Date(Date.now() - 45 * 60_000).toISOString(),
+ updated_at: '',
+ },
+ ],
+ total: 1,
+ page: 1,
+ page_size: 25,
+ pages: 1,
+};
+
+const COVERAGE = {
+ tactics: ['Execution', 'Persistence'],
+ cells: [
+ { techniqueId: 'T1059', tactic: 'Execution', totalRules: 3, activeRules: 2, inactiveRules: 1 },
+ { techniqueId: 'T1547', tactic: 'Persistence', totalRules: 2, activeRules: 0, inactiveRules: 2 },
+ { techniqueId: 'T1053', tactic: 'Persistence', totalRules: 1, activeRules: 1, inactiveRules: 0 },
+ { techniqueId: 'T9999', tactic: null, totalRules: 1, activeRules: 1, inactiveRules: 0 },
+ ],
+ summary: {
+ totalRules: 7,
+ activeRules: 4,
+ inactiveRules: 3,
+ techniques: 4,
+ coveredTechniques: 3,
+ },
+ generatedAt: '2026-05-06T12:00:00Z',
+};
+
+const FUNNEL = {
+ period: '24h',
+ events_of_interest: 1234,
+ correlation_instances: 87,
+ alerts_generated: 42,
+ signal_to_noise: 0.83,
+ mttd_seconds: 480,
+ analyst_queue_depth: 9,
+ correlation_efficiency: 0.48,
+ alert_yield: 0.03,
+ mitre_coverage: { covered: 3, total: 4, ratio: 0.75 },
+ deltas: {
+ events_of_interest: 0.1,
+ correlation_instances: 0,
+ alerts_generated: -0.05,
+ signal_to_noise: 0.02,
+ mttd_seconds: -0.1,
+ analyst_queue_depth: 0,
+ },
+ generated_at: '2026-05-06T12:00:00Z',
+};
+
+const PIPELINE = {
+ overall_status: 'green',
+ stages: [],
+ generated_at: '2026-05-06T12:00:00Z',
+};
+
+function renderDashboard() {
+ return render(
+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>
+ <OperationsDashboard />
+ </SWRConfig>,
+ );
+}
+
+/** All endpoints healthy. Individual tests override one. */
+function happyPath() {
+ fleetHealth.mockResolvedValue(FLEET);
+ deadLetters.mockResolvedValue(DEAD_LETTERS);
+ alertStats.mockResolvedValue(ALERT_STATS);
+ costDashboard.mockResolvedValue(COSTS);
+ listApprovals.mockResolvedValue(APPROVALS);
+ coverage.mockResolvedValue(COVERAGE);
+ getFunnel.mockResolvedValue(FUNNEL);
+ getPipelineHealth.mockResolvedValue(PIPELINE);
+}
+
+beforeEach(() => {
+ for (const m of [
+ fleetHealth, deadLetters, alertStats, costDashboard, listApprovals, coverage,
+ getFunnel, getPipelineHealth,
+ ]) {
+ m.mockReset();
+ }
+ happyPath();
+});
+
+afterEach(() => cleanup());
+
+describe('panels render real API values', () => {
+ it('reports connector staleness against each connector\u2019s own cadence', async () => {
+ renderDashboard();
+
+ expect(await screen.findByText('Corp Okta')).toBeTruthy();
+ // Cadence-relative, not wall-clock: 960s is only late because the
+ // interval is 300s.
+ expect(screen.getByText('3.2 intervals behind')).toBeTruthy();
+ expect(screen.getByText(/No successful sync for 3.2 poll intervals/)).toBeTruthy();
+ expect(screen.getByText('1 need attention')).toBeTruthy();
+ });
+
+ it('groups rejected events by the reason the pipeline gave', async () => {
+ renderDashboard();
+
+ expect(await screen.findByText('schema_validation_failed')).toBeTruthy();
+ const panel = within(
+ screen.getByRole('region', { name: /Rejected events/i }),
+ );
+ expect(panel.getByText('unknown_tenant')).toBeTruthy();
+ expect(panel.getByText('17')).toBeTruthy();
+ expect(panel.getByText('12')).toBeTruthy();
+ });
+
+ it('shows alert posture with the two counters worth acting on', async () => {
+ renderDashboard();
+
+ expect(await screen.findByText('128')).toBeTruthy();
+ expect(screen.getByText(/By disposition/i)).toBeTruthy();
+ expect(screen.getByText('False positive')).toBeTruthy();
+ });
+
+ it('labels agent throughput as runs, which is what the endpoint measures', async () => {
+ renderDashboard();
+
+ expect(await screen.findByText('Runs')).toBeTruthy();
+ expect(screen.getByText('96')).toBeTruthy();
+ expect(screen.getByText('$4.21')).toBeTruthy();
+ // `total_runs` is investigation runs, not alerts triaged. Calling it the
+ // latter would be a different measurement than the one taken.
+ expect(screen.queryByText(/alerts triaged/i)).toBeNull();
+ });
+
+ it('surfaces pending containment with its age and links to where it is decided', async () => {
+ renderDashboard();
+
+ expect(await screen.findByText('Isolate WIN-DC01')).toBeTruthy();
+ expect(screen.getByText('waiting 45m')).toBeTruthy();
+ expect(
+ screen.getAllByRole('link').some((a) => a.getAttribute('href') === '/responder/approvals'),
+ ).toBe(true);
+ });
+
+ it('counts disabled rules against coverage rather than folding them into a total', async () => {
+ renderDashboard();
+
+ expect(await screen.findByText('3 / 4')).toBeTruthy();
+ expect(screen.getByText('3 disabled')).toBeTruthy();
+ });
+});
+
+describe('one dead endpoint does not degrade the rest', () => {
+ it('blanks only the failing panel and names the failure', async () => {
+ fleetHealth.mockRejectedValue(new Error('API 503 Service Unavailable'));
+ renderDashboard();
+
+ // The failing panel says so.
+ expect(await screen.findByText(/Fleet health unavailable/i)).toBeTruthy();
+ expect(screen.getByText(/API 503 Service Unavailable/)).toBeTruthy();
+ // And invents nothing in its place.
+ expect(screen.queryByText('Corp Okta')).toBeNull();
+
+ // Neighbouring panels still show their real values.
+ expect(screen.getByText('schema_validation_failed')).toBeTruthy();
+ expect(screen.getByText('Isolate WIN-DC01')).toBeTruthy();
+ });
+
+ it('shows no figures at all when every endpoint is down', async () => {
+ const down = new Error('network unreachable');
+ for (const m of [
+ fleetHealth, deadLetters, alertStats, costDashboard, listApprovals, coverage,
+ getFunnel, getPipelineHealth,
+ ]) {
+ m.mockRejectedValue(down);
+ }
+ renderDashboard();
+
+ await screen.findByText(/Fleet health unavailable/i);
+ // Every figure that would otherwise render is sourced from a payload that
+ // never arrived, so none of them may appear.
+ for (const fabricated of ['128', '96', '$4.21', '3 / 4', '17']) {
+ expect(screen.queryByText(fabricated), fabricated).toBeNull();
+ }
+ });
+});
+
+describe('first paint shows nothing rather than something plausible', () => {
+ // The bug this repo shipped twice was not in the error branch — error was
+ // handled — it was that `data` is also undefined on first paint, so a
+ // `data ?? MOCK` expression rendered the mock silently, with no banner,
+ // for as long as the request took. On a deployment whose API is slow or
+ // unreachable that is the whole session. A test that only fails the
+ // endpoint never reaches this state, so it has to be asserted directly.
+ it('renders a skeleton, not sample data, while requests are in flight', async () => {
+ for (const m of [
+ fleetHealth, deadLetters, alertStats, costDashboard, listApprovals, coverage,
+ getFunnel, getPipelineHealth,
+ ]) {
+ m.mockReturnValue(new Promise(() => {})); // never settles
+ }
+
+ renderDashboard();
+ // Let SWR flush its initial render.
+ await new Promise((r) => setTimeout(r, 0));
+
+ for (const value of ['Corp Okta', 'Prod CloudTrail', 'schema_validation_failed', '128', '96', '$4.21']) {
+ expect(screen.queryByText(value), value).toBeNull();
+ }
+ });
+});
+
+describe('honest empty states', () => {
+ it('distinguishes "nothing rejected" from "the panel failed"', async () => {
+ deadLetters.mockResolvedValue({ ...DEAD_LETTERS, total: 0, by_reason: [] });
+ renderDashboard();
+
+ expect(await screen.findByText(/Nothing rejected/i)).toBeTruthy();
+ expect(screen.queryByText(/Dead-letter counts unavailable/i)).toBeNull();
+ });
+
+ it('explains an empty alert queue when no connector is configured', async () => {
+ fleetHealth.mockResolvedValue({ ...FLEET, connectors: [], counts: {} });
+ alertStats.mockResolvedValue({ ...ALERT_STATS, total: 0, by_severity: {}, by_status: {} });
+ renderDashboard();
+
+ expect(await screen.findByText(/No connectors configured/i)).toBeTruthy();
+ expect(screen.getByText(/No alerts recorded/i)).toBeTruthy();
+ });
+
+ it('says nothing is waiting rather than rendering an empty list', async () => {
+ listApprovals.mockResolvedValue({ ...APPROVALS, items: [], total: 0 });
+ renderDashboard();
+
+ expect(await screen.findByText(/Nothing waiting on a human/i)).toBeTruthy();
+ });
+});
+
+describe('derived helpers', () => {
+ it('formatStaleness prefers cadence-relative wording once a poll is missed', () => {
+ const base = FLEET.connectors[0];
+ expect(formatStaleness({ ...base, missed_intervals: 3.24 })).toBe('3.2 intervals behind');
+ // Under one interval, wall-clock is the more useful reading.
+ expect(formatStaleness({ ...base, missed_intervals: 0.2, seconds_since_sync: 60 })).toBe(
+ 'synced just now',
+ );
+ expect(formatStaleness({ ...base, missed_intervals: 0.2, seconds_since_sync: 7200 })).toBe(
+ 'synced 2h ago',
+ );
+ expect(formatStaleness({ ...base, last_sync: null })).toBe('never synced');
+ expect(
+ formatStaleness({ ...base, missed_intervals: null, seconds_since_sync: null }),
+ ).toBe('sync time unknown');
+ });
+
+ it('formatWaitingFor reads an approval age without inventing precision', () => {
+ const now = Date.parse('2026-05-06T12:00:00Z');
+ expect(formatWaitingFor('2026-05-06T11:59:40Z', now)).toBe('waiting <1m');
+ expect(formatWaitingFor('2026-05-06T11:15:00Z', now)).toBe('waiting 45m');
+ expect(formatWaitingFor('2026-05-06T09:00:00Z', now)).toBe('waiting 3h');
+ expect(formatWaitingFor('not-a-date', now)).toBe('waiting');
+ });
+
+ it('thinnestTactics ranks by active coverage and skips untagged techniques', () => {
+ const ranked = thinnestTactics(COVERAGE);
+ // Persistence is 1/2 covered, Execution 1/1. The `tactic: null` cell is
+ // counted in the summary but cannot be attributed to a tactic here.
+ expect(ranked[0]).toEqual({ tactic: 'Persistence', covered: 1, total: 2 });
+ expect(ranked.some((t) => t.tactic === null || t.tactic === 'Unknown')).toBe(false);
+ });
+});
+
+describe('accessibility (WCAG 2.1 AA)', () => {
+ const axeOptions = { rules: { 'color-contrast': { enabled: false } } };
+
+ it('has no violations with every panel populated', async () => {
+ const { container } = renderDashboard();
+ await screen.findByText('Corp Okta');
+
+ expect(await axe(container, axeOptions)).toHaveNoViolations();
+ });
+});
diff --git a/apps/web/src/components/dashboard/operations/OperationsDashboard.tsx b/apps/web/src/components/dashboard/operations/OperationsDashboard.tsx
new file mode 100644
index 000000000..b68ac5627
--- /dev/null
+++ b/apps/web/src/components/dashboard/operations/OperationsDashboard.tsx
@@ -0,0 +1,70 @@
+'use client';
+
+/**
+ * SOC operations dashboard.
+ *
+ * `/dashboard` answers "what is happening in the estate". This one answers
+ * "is the machine that tells me what is happening actually working" — a
+ * different question, and the one an alert-centric view structurally cannot
+ * answer, because every failure mode of the pipeline makes it *quieter*.
+ *
+ * Five panels, each backed by one real endpoint:
+ *
+ * - connector fleet staleness GET /api/v1/health/fleet
+ * - rejected events by reason GET /api/v1/health/dead-letters
+ * - alert severity + disposition GET /api/v1/alerts/stats
+ * - agent runs, tokens, spend GET /api/v1/costs/dashboard
+ * - actions awaiting approval GET /api/v1/approvals?status=pending
+ *
+ * Plus the existing funnel strip and detection-coverage summary, which are
+ * already real-data-driven and are reused rather than re-implemented.
+ *
+ * Every panel owns its own fetch, loading, empty and error state. One dead
+ * endpoint blanks one panel and says why, rather than taking the page down or
+ * — the failure mode this codebase has shipped before — quietly substituting
+ * plausible numbers.
+ */
+
+import { FunnelKpiBar } from '../FunnelKpiBar';
+import { PipelineHealth } from '../PipelineHealth';
+import { ConnectorFleetPanel } from './ConnectorFleetPanel';
+import { RejectedEventsPanel } from './RejectedEventsPanel';
+import { AlertPosturePanel } from './AlertPosturePanel';
+import { AgentThroughputPanel } from './AgentThroughputPanel';
+import { ResponseActionsPanel } from './ResponseActionsPanel';
+import { DetectionCoveragePanel } from './DetectionCoveragePanel';
+
+export function OperationsDashboard() {
+ return (
+ <div className="space-y-5">
+ <header>
+ <h1 className="text-xl font-semibold text-gray-100">SOC operations</h1>
+ <p className="mt-1 text-sm text-gray-500">
+ Whether the detection pipeline is working, independent of whether it is
+ finding anything. Every panel is driven by a live API response; a panel
+ with no data says so rather than showing a placeholder.
+ </p>
+ </header>
+
+ <FunnelKpiBar period="24h" />
+
+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
+ <ConnectorFleetPanel />
+ <div className="space-y-4">
+ <PipelineHealth />
+ <RejectedEventsPanel />
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
+ <AlertPosturePanel />
+ <DetectionCoveragePanel />
+ </div>
+
+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
+ <AgentThroughputPanel />
+ <ResponseActionsPanel />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/dashboard/operations/RejectedEventsPanel.tsx b/apps/web/src/components/dashboard/operations/RejectedEventsPanel.tsx
new file mode 100644
index 000000000..6a883593d
--- /dev/null
+++ b/apps/web/src/components/dashboard/operations/RejectedEventsPanel.tsx
@@ -0,0 +1,97 @@
+'use client';
+
+/**
+ * Events the pipeline refused, grouped by why.
+ *
+ * The companion to connector fleet health. A connector can be polling happily
+ * while every event it produces is rejected downstream for a schema mismatch,
+ * and the symptom is identical from the alert queue: nothing arrives.
+ *
+ * `GET /api/v1/health/dead-letters` returns `by_reason` even when it is empty,
+ * deliberately, so "no dead letters" reads as a real answer rather than a
+ * panel that failed to load. This component preserves that distinction.
+ */
+
+import useSWR from 'swr';
+import { operationsApi } from '@/lib/api';
+import { EmptyState } from '@/components/ui/EmptyState';
+import { ErrorState } from '@/components/ui/ErrorState';
+
+const WINDOW_HOURS = 24;
+
+export function RejectedEventsPanel() {
+ const { data, error, isLoading, mutate } = useSWR(
+ `ops-dead-letters:${WINDOW_HOURS}`,
+ () => operationsApi.deadLetters({ hours: WINDOW_HOURS, limit: 50 }),
+ { refreshInterval: 60_000, revalidateOnFocus: false },
+ );
+
+ const byReason = data?.by_reason ?? [];
+ const maxCount = Math.max(...byReason.map((r) => r.count), 1);
+
+ return (
+ <section
+ aria-labelledby="ops-dlq-heading"
+ className="rounded-xl border border-gray-800/60 bg-gray-900/40"
+ >
+ <div className="flex items-baseline justify-between px-4 py-3">
+ <div>
+ <h2 id="ops-dlq-heading" className="text-sm font-medium text-gray-300">
+ Rejected events
+ </h2>
+ <p className="mt-0.5 text-[11px] text-gray-500">
+ Last {WINDOW_HOURS} hours, grouped by reason.
+ </p>
+ </div>
+ {data && (
+ <span className="shrink-0 text-sm font-medium text-gray-200">
+ {data.total.toLocaleString()}
+ </span>
+ )}
+ </div>
+
+ {isLoading && !data ? (
+ <div className="m-4 h-20 animate-pulse rounded bg-gray-800/40" />
+ ) : error ? (
+ <ErrorState
+ title="Dead-letter counts unavailable"
+ error={error}
+ onRetry={() => {
+ void mutate();
+ }}
+ className="m-4"
+ />
+ ) : data && data.total === 0 ? (
+ <EmptyState
+ title="Nothing rejected"
+ description={`Every event the pipeline received in the last ${WINDOW_HOURS} hours was accepted.`}
+ className="m-4"
+ />
+ ) : (
+ <ul className="space-y-2 px-4 pb-4">
+ {byReason.map((row) => (
+ <li key={row.reason}>
+ <div className="mb-1 flex items-baseline justify-between gap-3">
+ <span className="truncate text-xs text-gray-300">{row.reason}</span>
+ <span className="shrink-0 text-xs text-gray-500">
+ {row.count.toLocaleString()}
+ </span>
+ </div>
+ <div className="h-1 rounded-full bg-gray-800">
+ <div
+ className="h-1 rounded-full bg-amber-500/60"
+ style={{ width: `${Math.round((row.count / maxCount) * 100)}%` }}
+ />
+ </div>
+ </li>
+ ))}
+ {data?.truncated && (
+ <li className="pt-1 text-[11px] text-gray-600">
+ Sample capped; counts above are complete for the window.
+ </li>
+ )}
+ </ul>
+ )}
+ </section>
+ );
+}
diff --git a/apps/web/src/components/dashboard/operations/ResponseActionsPanel.tsx b/apps/web/src/components/dashboard/operations/ResponseActionsPanel.tsx
new file mode 100644
index 000000000..b9d5fe29d
--- /dev/null
+++ b/apps/web/src/components/dashboard/operations/ResponseActionsPanel.tsx
@@ -0,0 +1,151 @@
+'use client';
+
+/**
+ * Response actions the agent has stopped on, waiting for a human.
+ *
+ * The agent pauses before a high-risk action — isolate a host, disable an
+ * account, revoke a session — and writes an approval request. Until someone
+ * decides, the containment has not happened. An approval sitting unnoticed
+ * for two hours is an incident still running, so the count and the age of the
+ * oldest one belong on an operations dashboard rather than only inside the
+ * on-call queue.
+ *
+ * Deciding happens on `/responder/approvals`, which already does it properly
+ * (full context, deny-with-comment, optimistic reconciliation). This panel
+ * links there rather than growing a cramped second approve button: a
+ * one-tap irreversible action in a dashboard tile is a worse affordance than
+ * a link to the surface built for it.
+ */
+
+import useSWR from 'swr';
+import Link from 'next/link';
+import { clsx } from 'clsx';
+import { responderApi, type ApprovalRequest } from '@/lib/api';
+import { EmptyState } from '@/components/ui/EmptyState';
+import { ErrorState } from '@/components/ui/ErrorState';
+
+const RISK_STYLE: Record<ApprovalRequest['risk_level'], string> = {
+ critical: 'bg-red-500/10 text-red-300 border-red-500/30',
+ high: 'bg-orange-500/10 text-orange-300 border-orange-500/30',
+ medium: 'bg-yellow-500/10 text-yellow-300 border-yellow-500/30',
+ low: 'bg-blue-500/10 text-blue-300 border-blue-500/30',
+};
+
+const RISK_ORDER: ReadonlyArray<ApprovalRequest['risk_level']> = [
+ 'critical',
+ 'high',
+ 'medium',
+ 'low',
+];
+
+export function formatWaitingFor(createdAt: string, now: number = Date.now()): string {
+ const started = new Date(createdAt).getTime();
+ if (!Number.isFinite(started)) return 'waiting';
+ const secs = Math.max(0, Math.round((now - started) / 1000));
+ if (secs < 60) return 'waiting <1m';
+ if (secs < 3600) return `waiting ${Math.round(secs / 60)}m`;
+ if (secs < 86_400) return `waiting ${Math.round(secs / 3600)}h`;
+ return `waiting ${Math.round(secs / 86_400)}d`;
+}
+
+export function ResponseActionsPanel() {
+ const { data, error, isLoading, mutate } = useSWR(
+ 'ops-pending-approvals',
+ () => responderApi.listApprovals({ status: 'pending', page_size: 25 }),
+ { refreshInterval: 30_000, revalidateOnFocus: false },
+ );
+
+ const items = data?.items ?? [];
+ const sorted = [...items].sort((a, b) => {
+ const byRisk = RISK_ORDER.indexOf(a.risk_level) - RISK_ORDER.indexOf(b.risk_level);
+ if (byRisk !== 0) return byRisk;
+ return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
+ });
+
+ return (
+ <section
+ aria-labelledby="ops-approvals-heading"
+ className="rounded-xl border border-gray-800/60 bg-gray-900/40"
+ >
+ <div className="flex items-baseline justify-between px-4 py-3">
+ <div>
+ <h2 id="ops-approvals-heading" className="text-sm font-medium text-gray-300">
+ Actions awaiting approval
+ </h2>
+ <p className="mt-0.5 text-[11px] text-gray-500">
+ Containment the agent has proposed and paused on.
+ </p>
+ </div>
+ {data && data.total > 0 && (
+ <span className="shrink-0 rounded-full bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-300">
+ {`${data.total} pending`}
+ </span>
+ )}
+ </div>
+
+ {isLoading && !data ? (
+ <div className="m-4 h-20 animate-pulse rounded bg-gray-800/40" />
+ ) : error ? (
+ <ErrorState
+ title="Approval queue unavailable"
+ description="Pending containment actions cannot be listed. Check /responder/approvals directly."
+ error={error}
+ onRetry={() => {
+ void mutate();
+ }}
+ className="m-4"
+ />
+ ) : sorted.length === 0 ? (
+ <EmptyState
+ title="Nothing waiting on a human"
+ description="No response action is currently paused for approval."
+ className="m-4"
+ />
+ ) : (
+ <>
+ <ul>
+ {sorted.slice(0, 6).map((item) => (
+ <li
+ key={item.id}
+ className="border-t border-gray-800/40 px-4 py-2.5 first:border-t-0"
+ >
+ <Link
+ href="/responder/approvals"
+ className="flex items-start gap-3 hover:opacity-90"
+ >
+ <span
+ className={clsx(
+ 'mt-0.5 shrink-0 rounded border px-1.5 py-0.5 text-[10px] font-medium uppercase',
+ RISK_STYLE[item.risk_level],
+ )}
+ >
+ {item.risk_level}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-sm text-gray-200">{item.title}</span>
+ <span className="block truncate text-[11px] text-gray-500">
+ {item.summary}
+ </span>
+ </span>
+ <span className="shrink-0 text-[11px] text-gray-500">
+ {formatWaitingFor(item.created_at)}
+ </span>
+ </Link>
+ </li>
+ ))}
+ </ul>
+ <div className="border-t border-gray-800/40 px-4 py-2.5">
+ <Link
+ href="/responder/approvals"
+ className="text-xs text-blue-400 underline underline-offset-2 hover:text-blue-300"
+ >
+ {sorted.length > 6
+ ? `Review all ${data?.total ?? sorted.length} in the approvals queue`
+ : 'Open the approvals queue'}
+ </Link>
+ </div>
+ </>
+ )}
+ </section>
+ );
+}
diff --git a/apps/web/src/components/federated/FederatedSearchView.test.tsx b/apps/web/src/components/federated/FederatedSearchView.test.tsx
new file mode 100644
index 000000000..eafc66535
--- /dev/null
+++ b/apps/web/src/components/federated/FederatedSearchView.test.tsx
@@ -0,0 +1,367 @@
+/**
+ * Federated search surface.
+ *
+ * The property these tests exist to protect is per-backend isolation. The API
+ * deliberately never fails the whole call because one SIEM is slow, 401s or
+ * 5xxs — it returns a `sources[]` verdict per backend instead. A UI that
+ * renders only the merged rows discards that, and the analyst cannot tell
+ * "Sentinel has nothing" from "Sentinel did not answer", which are opposite
+ * conclusions mid-incident.
+ *
+ * So: a partial failure must stay visible, and must never be allowed to look
+ * like a clean empty result.
+ */
+
+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { SWRConfig } from 'swr';
+import { axe } from 'vitest-axe';
+
+const listBackends = vi.hoisted(() => vi.fn());
+const search = vi.hoisted(() => vi.fn());
+
+// Hoisted with the mock factory, which vitest lifts above the imports.
+const FakeDisabledError = vi.hoisted(
+ () =>
+ class FederatedSearchDisabledError extends Error {
+ constructor() {
+ super('Federated search is disabled on this deployment (AISOC_FEATURE_FED_SEARCH).');
+ this.name = 'FederatedSearchDisabledError';
+ }
+ },
+);
+
+vi.mock('@/lib/api', () => ({
+ __esModule: true,
+ federatedApi: { listBackends, search },
+ FederatedSearchDisabledError: FakeDisabledError,
+ FEDERATED_OPERATORS: [
+ 'eq', 'ne', 'contains', 'starts_with', 'ends_with', 'gt', 'gte', 'lt', 'lte', 'in',
+ ],
+}));
+
+vi.mock('next/link', () => ({
+ __esModule: true,
+ default: ({ children, href }: { children: React.ReactNode; href: string }) => (
+ <a href={href}>{children}</a>
+ ),
+}));
+
+// Real SWR against a mocked fetcher: the loading -> resolved transition is
+// part of what is under test, and stubbing SWR would skip it.
+import { FederatedSearchView } from './FederatedSearchView';
+
+const BACKENDS = {
+ backends: [
+ {
+ connector_id: 'aaaaaaaa-0000-4000-8000-000000000001',
+ connector_type: 'splunk',
+ name: 'Prod Splunk',
+ health_status: 'healthy',
+ is_enabled: true,
+ },
+ {
+ connector_id: 'bbbbbbbb-0000-4000-8000-000000000002',
+ connector_type: 'microsoft_sentinel',
+ name: 'Corp Sentinel',
+ health_status: 'degraded',
+ is_enabled: true,
+ },
+ ],
+};
+
+/** One backend answered with a row, the other timed out. */
+const PARTIAL_FAILURE = {
+ rows: [
+ {
+ _time: '2026-05-06T12:00:00Z',
+ host: 'WIN-DC01',
+ user: 'svc_backup',
+ _aisoc_source: {
+ connector_id: 'aaaaaaaa-0000-4000-8000-000000000001',
+ connector_name: 'Prod Splunk',
+ connector_type: 'splunk',
+ },
+ },
+ ],
+ row_count: 1,
+ sources: [
+ {
+ connector_id: 'aaaaaaaa-0000-4000-8000-000000000001',
+ connector_name: 'Prod Splunk',
+ connector_type: 'splunk',
+ status: 'ok' as const,
+ row_count: 1,
+ duration_ms: 812,
+ error: null,
+ },
+ {
+ connector_id: 'bbbbbbbb-0000-4000-8000-000000000002',
+ connector_name: 'Corp Sentinel',
+ connector_type: 'microsoft_sentinel',
+ status: 'error' as const,
+ row_count: 0,
+ duration_ms: 30_000,
+ error: 'connectors service unreachable: ReadTimeout',
+ },
+ ],
+ truncated: false,
+};
+
+/**
+ * Render with a private SWR cache.
+ *
+ * SWR's cache is module-global, so without this the second test in a file
+ * reads the first test's `federated-backends` entry and never calls the
+ * mocked fetcher — every later assertion then measures the wrong render.
+ */
+function renderView() {
+ return render(
+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>
+ <FederatedSearchView />
+ </SWRConfig>,
+ );
+}
+
+async function runSearch(text = 'failed logon') {
+ const input = await screen.findByLabelText(/search text/i);
+ fireEvent.change(input, { target: { value: text } });
+ fireEvent.click(screen.getByRole('button', { name: /run federated search/i }));
+}
+
+beforeEach(() => {
+ listBackends.mockReset();
+ search.mockReset();
+ listBackends.mockResolvedValue(BACKENDS);
+});
+
+afterEach(() => cleanup());
+
+describe('backend inventory', () => {
+ it('lists the tenant\u2019s connected SIEMs with their recorded health', async () => {
+ renderView();
+
+ expect(await screen.findByText('Prod Splunk')).toBeTruthy();
+ expect(screen.getByText('Corp Sentinel')).toBeTruthy();
+ expect(screen.getByText('Reachable')).toBeTruthy();
+ expect(screen.getByText('Degraded')).toBeTruthy();
+ });
+
+ it('says so, and offers no query box, when no SIEM is connected', async () => {
+ listBackends.mockResolvedValue({ backends: [] });
+ renderView();
+
+ expect(await screen.findByText(/No SIEM connectors are connected/i)).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /run federated search/i })).toBeNull();
+ });
+
+ it('names the feature flag rather than showing a bare not-found', async () => {
+ listBackends.mockRejectedValue(new FakeDisabledError());
+ renderView();
+
+ expect(await screen.findByText(/Federated search is turned off/i)).toBeTruthy();
+ expect(screen.getByText(/AISOC_FEATURE_FED_SEARCH/)).toBeTruthy();
+ });
+
+ it('surfaces a backend-list failure instead of rendering an empty picker', async () => {
+ listBackends.mockRejectedValue(new Error('API 500 Internal Server Error'));
+ renderView();
+
+ expect(await screen.findByText(/Could not list federated backends/i)).toBeTruthy();
+ expect(screen.getByText(/API 500 Internal Server Error/)).toBeTruthy();
+ });
+});
+
+describe('per-backend isolation', () => {
+ it('shows one SIEM timing out without blanking the other SIEM\u2019s rows', async () => {
+ search.mockResolvedValue(PARTIAL_FAILURE);
+ renderView();
+ await runSearch();
+
+ // The failure is named, with its own message and its own latency.
+ await waitFor(() => expect(screen.getByText(/2 backends did not/i)).toBeTruthy());
+ expect(screen.getByText(/connectors service unreachable: ReadTimeout/)).toBeTruthy();
+ expect(screen.getByText('30000 ms')).toBeTruthy();
+
+ // And the backend that did answer still shows its row.
+ expect(screen.getByText('812 ms')).toBeTruthy();
+ expect(screen.getAllByText(/WIN-DC01/).length).toBeGreaterThan(0);
+ });
+
+ it('does not print a row count for a backend that failed', async () => {
+ search.mockResolvedValue(PARTIAL_FAILURE);
+ renderView();
+ await runSearch();
+
+ const failed = await screen.findByTestId(
+ 'source-verdict-bbbbbbbb-0000-4000-8000-000000000002',
+ );
+ // "0 rows" beside a failure reads as "nothing matched", which is the one
+ // conclusion the analyst must not draw from a timeout.
+ expect(failed.textContent).not.toMatch(/\b0 rows?\b/);
+ expect(failed.textContent).toMatch(/Failed/);
+ });
+
+ it('distinguishes "every backend failed" from "nothing matched"', async () => {
+ search.mockResolvedValue({
+ rows: [],
+ row_count: 0,
+ sources: [
+ { ...PARTIAL_FAILURE.sources[1], status: 'error' as const },
+ ],
+ truncated: false,
+ });
+ renderView();
+ await runSearch();
+
+ expect(await screen.findByText(/No backend returned results/i)).toBeTruthy();
+ expect(screen.queryByText(/No matching events/i)).toBeNull();
+ });
+
+ it('says "no matching events" when a backend genuinely answered empty', async () => {
+ search.mockResolvedValue({
+ rows: [],
+ row_count: 0,
+ sources: [{ ...PARTIAL_FAILURE.sources[0], row_count: 0 }],
+ truncated: false,
+ });
+ renderView();
+ await runSearch();
+
+ expect(await screen.findByText(/No matching events/i)).toBeTruthy();
+ });
+
+ it('flags a merged result that was capped', async () => {
+ search.mockResolvedValue({ ...PARTIAL_FAILURE, truncated: true });
+ renderView();
+ await runSearch();
+
+ expect(await screen.findByText(/Capped at 100 rows after merging/i)).toBeTruthy();
+ });
+});
+
+describe('query construction', () => {
+ it('refuses to send a query the server would reject as empty', async () => {
+ renderView();
+ await screen.findByText('Prod Splunk');
+
+ const button = screen.getByRole('button', { name: /run federated search/i });
+ expect(button.hasAttribute('disabled')).toBe(true);
+ fireEvent.click(button);
+ expect(search).not.toHaveBeenCalled();
+ });
+
+ it('omits connector_ids when every backend is selected, rather than listing them', async () => {
+ search.mockResolvedValue(PARTIAL_FAILURE);
+ renderView();
+ await runSearch();
+
+ await waitFor(() => expect(search).toHaveBeenCalledTimes(1));
+ // `null` means "every enabled backend" server-side. Enumerating them
+ // instead would silently pin the search to whatever was connected at the
+ // moment the page loaded.
+ expect(search.mock.calls[0][0].connector_ids).toBeNull();
+ });
+
+ it('scopes to the chosen backend when one is unticked', async () => {
+ search.mockResolvedValue(PARTIAL_FAILURE);
+ renderView();
+ await screen.findByText('Prod Splunk');
+
+ fireEvent.click(screen.getAllByRole('checkbox')[1]); // untick Sentinel
+ await runSearch();
+
+ await waitFor(() => expect(search).toHaveBeenCalledTimes(1));
+ expect(search.mock.calls[0][0].connector_ids).toEqual([
+ 'aaaaaaaa-0000-4000-8000-000000000001',
+ ]);
+ });
+
+ it('splits a comma list for the `in` operator and sends a real array', async () => {
+ search.mockResolvedValue(PARTIAL_FAILURE);
+ renderView();
+ await screen.findByText('Prod Splunk');
+
+ fireEvent.click(screen.getByRole('button', { name: /add filter/i }));
+ fireEvent.change(screen.getByLabelText(/filter 1 field/i), {
+ target: { value: 'user' },
+ });
+ fireEvent.change(screen.getByLabelText(/filter 1 operator/i), {
+ target: { value: 'in' },
+ });
+ fireEvent.change(screen.getByLabelText(/filter 1 value/i), {
+ target: { value: 'alice, bob ,carol' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: /run federated search/i }));
+
+ await waitFor(() => expect(search).toHaveBeenCalledTimes(1));
+ expect(search.mock.calls[0][0].indicators).toEqual([
+ { field: 'user', operator: 'in', value: ['alice', 'bob', 'carol'] },
+ ]);
+ });
+
+ it('drops half-typed filter rows instead of sending an invalid indicator', async () => {
+ search.mockResolvedValue(PARTIAL_FAILURE);
+ renderView();
+ await screen.findByText('Prod Splunk');
+
+ fireEvent.click(screen.getByRole('button', { name: /add filter/i }));
+ fireEvent.change(screen.getByLabelText(/filter 1 field/i), {
+ target: { value: 'host' },
+ });
+ // value left blank
+ await runSearch();
+
+ await waitFor(() => expect(search).toHaveBeenCalledTimes(1));
+ expect(search.mock.calls[0][0].indicators).toEqual([]);
+ });
+});
+
+describe('pivots', () => {
+ it('deep-links recognised entities into the attack graph', async () => {
+ search.mockResolvedValue(PARTIAL_FAILURE);
+ renderView();
+ await runSearch();
+
+ const hostPivot = await screen.findByRole('link', { name: /Pivot host: WIN-DC01/i });
+ expect(hostPivot.getAttribute('href')).toBe('/graph?entity=host%3AWIN-DC01');
+
+ const userPivot = screen.getByRole('link', { name: /Pivot user: svc_backup/i });
+ expect(userPivot.getAttribute('href')).toBe('/graph?entity=user%3Asvc_backup');
+ });
+});
+
+describe('accessibility (WCAG 2.1 AA)', () => {
+ // jsdom cannot compute styles from CSS variables, so axe's color-contrast
+ // rule only ever returns "incomplete" here. Same exemption the shared
+ // sweep in `src/test/a11y.test.tsx` takes.
+ const axeOptions = { rules: { 'color-contrast': { enabled: false } } };
+
+ it('has no violations with the query form and backend picker rendered', async () => {
+ const { container } = renderView();
+ await screen.findByText('Prod Splunk');
+
+ expect(await axe(container, axeOptions)).toHaveNoViolations();
+ });
+
+ it('has no violations with results and a partial failure on screen', async () => {
+ search.mockResolvedValue(PARTIAL_FAILURE);
+ const { container } = renderView();
+ await runSearch();
+ await screen.findByText(/connectors service unreachable/);
+
+ expect(await axe(container, axeOptions)).toHaveNoViolations();
+ });
+});
+
+describe('request failure', () => {
+ it('shows the error and no partial rows when the search call itself fails', async () => {
+ search.mockRejectedValue(new Error('API 502 Bad Gateway'));
+ renderView();
+ await runSearch();
+
+ expect(await screen.findByText(/Federated search failed/i)).toBeTruthy();
+ expect(screen.getByText(/API 502 Bad Gateway/)).toBeTruthy();
+ expect(screen.queryByText(/Merged rows/i)).toBeNull();
+ });
+});
diff --git a/apps/web/src/components/federated/FederatedSearchView.tsx b/apps/web/src/components/federated/FederatedSearchView.tsx
new file mode 100644
index 000000000..e0842a5ba
--- /dev/null
+++ b/apps/web/src/components/federated/FederatedSearchView.tsx
@@ -0,0 +1,707 @@
+'use client';
+
+/**
+ * Federated SIEM search.
+ *
+ * `/api/v1/federated/backends` and `/api/v1/federated/search` have existed
+ * server-side for some time — the API decrypts each tenant's own connector
+ * credentials, fans one `UnifiedQuery` out to Splunk / Sentinel / Elastic /
+ * QRadar in parallel, and merges the rows. Until now `apps/web` had no client
+ * for either, so the capability was reachable only from the SDK.
+ *
+ * The design constraint that shapes this whole view is the endpoint's
+ * per-source isolation: it never fails the call because one backend is slow,
+ * 401s or 5xxs. It returns `sources[]`, a verdict per backend. A UI that
+ * renders only the merged rows throws that away, and the analyst cannot tell
+ * "Sentinel has nothing" from "Sentinel did not answer" — which are opposite
+ * conclusions during an incident. So the verdict strip is not a detail panel
+ * here; it renders above the rows, always, including when every backend
+ * failed and there are no rows at all.
+ */
+
+import { useCallback, useMemo, useState } from 'react';
+import useSWR from 'swr';
+import Link from 'next/link';
+import { clsx } from 'clsx';
+import {
+ FEDERATED_OPERATORS,
+ FederatedSearchDisabledError,
+ federatedApi,
+ type FederatedBackend,
+ type FederatedIndicator,
+ type FederatedOperator,
+ type FederatedRow,
+ type FederatedSearchResponse,
+ type FederatedSourceVerdict,
+} from '@/lib/api';
+import { EmptyState } from '@/components/ui/EmptyState';
+import { ErrorState } from '@/components/ui/ErrorState';
+import { pivotPathForValue, pivotableFields } from './pivot';
+
+const TIME_WINDOWS: ReadonlyArray<{ label: string; seconds: number }> = [
+ { label: '15 minutes', seconds: 15 * 60 },
+ { label: '1 hour', seconds: 60 * 60 },
+ { label: '4 hours', seconds: 4 * 60 * 60 },
+ { label: '24 hours', seconds: 24 * 60 * 60 },
+ { label: '7 days', seconds: 7 * 24 * 60 * 60 },
+];
+
+const ROW_LIMITS = [50, 100, 250, 500, 1000] as const;
+
+/** Vendor labels. Anything unknown falls through to the raw type. */
+const BACKEND_LABELS: Record<string, string> = {
+ splunk: 'Splunk',
+ microsoft_sentinel: 'Microsoft Sentinel',
+ elastic: 'Elastic',
+ qradar: 'IBM QRadar',
+};
+
+function backendLabel(connectorType: string): string {
+ return BACKEND_LABELS[connectorType] ?? connectorType;
+}
+
+/**
+ * Connector `health_status` is free-form on the wire. Only map the values the
+ * backend is known to emit and render anything else verbatim — inventing a
+ * green dot for a status we do not recognise is the same class of mistake as
+ * inventing a row count.
+ */
+const HEALTH_STYLES: Record<string, { dot: string; label: string }> = {
+ healthy: { dot: 'bg-green-500', label: 'Reachable' },
+ degraded: { dot: 'bg-yellow-500', label: 'Degraded' },
+ failed: { dot: 'bg-red-500', label: 'Failing' },
+ unknown: { dot: 'bg-gray-500', label: 'Not yet polled' },
+};
+
+function healthStyle(status: string) {
+ return HEALTH_STYLES[status] ?? { dot: 'bg-gray-500', label: status };
+}
+
+interface IndicatorDraft extends FederatedIndicator {
+ /** Stable key so React does not reorder inputs when a row is removed. */
+ id: string;
+ value: string;
+}
+
+let indicatorSeq = 0;
+function newIndicator(): IndicatorDraft {
+ indicatorSeq += 1;
+ return { id: `ind-${indicatorSeq}`, field: '', operator: 'eq', value: '' };
+}
+
+// ─── Backend picker ───────────────────────────────────────────────────────────
+
+function BackendPicker({
+ backends,
+ selected,
+ onToggle,
+ onSelectAll,
+}: {
+ backends: FederatedBackend[];
+ selected: Set<string>;
+ onToggle: (id: string) => void;
+ onSelectAll: (all: boolean) => void;
+}) {
+ const allSelected = selected.size === 0 || selected.size === backends.length;
+
+ return (
+ <fieldset className="rounded-xl border border-gray-800/60 bg-gray-900/40 p-4">
+ <legend className="px-1 text-xs font-medium uppercase tracking-wider text-gray-500">
+ Backends to query
+ </legend>
+ <div className="mb-3 flex items-center justify-between">
+ <p className="text-xs text-gray-500">
+ {backends.length} federated-capable {backends.length === 1 ? 'connector' : 'connectors'}{' '}
+ enabled for this tenant.
+ </p>
+ <button
+ type="button"
+ onClick={() => onSelectAll(!allSelected)}
+ className="text-xs text-blue-400 underline underline-offset-2 hover:text-blue-300"
+ >
+ {allSelected ? 'Clear selection' : 'Select all'}
+ </button>
+ </div>
+ <ul className="grid gap-2 sm:grid-cols-2">
+ {backends.map((b) => {
+ const health = healthStyle(b.health_status);
+ const checked = selected.size === 0 || selected.has(b.connector_id);
+ return (
+ <li key={b.connector_id}>
+ <label
+ className={clsx(
+ 'flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2 transition-colors',
+ checked
+ ? 'border-blue-500/50 bg-blue-500/5'
+ : 'border-gray-800/60 bg-gray-900/40 hover:border-gray-700',
+ )}
+ >
+ <input
+ type="checkbox"
+ className="h-4 w-4 rounded border-gray-600 bg-gray-800 text-blue-500"
+ checked={checked}
+ onChange={() => onToggle(b.connector_id)}
+ />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-sm text-gray-200">{b.name}</span>
+ <span className="block text-[11px] text-gray-500">
+ {backendLabel(b.connector_type)}
+ </span>
+ </span>
+ <span className="flex shrink-0 items-center gap-1.5" title={`Connector health: ${b.health_status}`}>
+ <span className={clsx('h-1.5 w-1.5 rounded-full', health.dot)} />
+ <span className="text-[11px] text-gray-400">{health.label}</span>
+ </span>
+ </label>
+ </li>
+ );
+ })}
+ </ul>
+ <p className="mt-3 text-[11px] text-gray-600">
+ Health is the connector&apos;s last recorded poll status, not a live probe. A
+ backend that is reachable for ingest can still fail this query — the
+ per-backend result below is the authoritative answer.
+ </p>
+ </fieldset>
+ );
+}
+
+// ─── Per-backend verdict strip ────────────────────────────────────────────────
+
+function SourceVerdictCard({ verdict }: { verdict: FederatedSourceVerdict }) {
+ const tone =
+ verdict.status === 'ok'
+ ? 'border-green-500/30 bg-green-500/5'
+ : verdict.status === 'unsupported'
+ ? 'border-gray-700 bg-gray-900/40'
+ : 'border-red-500/30 bg-red-500/5';
+
+ const statusLabel =
+ verdict.status === 'ok'
+ ? 'Answered'
+ : verdict.status === 'unsupported'
+ ? 'Not supported'
+ : 'Failed';
+
+ return (
+ <li
+ className={clsx('rounded-lg border px-3 py-2.5', tone)}
+ data-testid={`source-verdict-${verdict.connector_id}`}
+ >
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="truncate text-sm font-medium text-gray-200">
+ {verdict.connector_name}
+ </span>
+ <span
+ className={clsx(
+ 'shrink-0 text-[11px] font-medium',
+ verdict.status === 'ok' ? 'text-green-300' : verdict.status === 'error' ? 'text-red-300' : 'text-gray-400',
+ )}
+ >
+ {statusLabel}
+ </span>
+ </div>
+ <div className="mt-1 flex items-center gap-3 text-[11px] text-gray-500">
+ <span>{backendLabel(verdict.connector_type)}</span>
+ {/* Row count is only meaningful for a backend that answered. Printing
+ "0 rows" for one that failed reads as "nothing matched". */}
+ {verdict.status === 'ok' && (
+ <span>
+ {verdict.row_count} {verdict.row_count === 1 ? 'row' : 'rows'}
+ </span>
+ )}
+ <span>{verdict.duration_ms} ms</span>
+ </div>
+ {verdict.error && (
+ <p className="mt-1.5 break-words text-[11px] text-red-300/90">{verdict.error}</p>
+ )}
+ </li>
+ );
+}
+
+function SourceVerdictStrip({ sources }: { sources: FederatedSourceVerdict[] }) {
+ const answered = sources.filter((s) => s.status === 'ok').length;
+ const failed = sources.filter((s) => s.status === 'error').length;
+
+ return (
+ <section aria-labelledby="fed-sources-heading">
+ <div className="mb-2 flex items-baseline justify-between">
+ <h2 id="fed-sources-heading" className="text-sm font-medium text-gray-300">
+ Per-backend result
+ </h2>
+ <p className="text-xs text-gray-500">
+ {`${answered} of ${sources.length} answered`}
+ {failed > 0 ? `, ${failed} failed` : ''}
+ </p>
+ </div>
+ {failed > 0 && (
+ <p
+ role="status"
+ className="mb-2 rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-200"
+ >
+ Results below are partial. {failed} of {sources.length} backends did not
+ answer, so an absence of rows from those sources is not evidence of an
+ absence of activity.
+ </p>
+ )}
+ <ul className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
+ {sources.map((s) => (
+ <SourceVerdictCard key={s.connector_id} verdict={s} />
+ ))}
+ </ul>
+ </section>
+ );
+}
+
+// ─── Result rows ──────────────────────────────────────────────────────────────
+
+function renderCell(value: unknown): string {
+ if (value === null || value === undefined) return '';
+ if (typeof value === 'string') return value;
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
+ try {
+ return JSON.stringify(value);
+ } catch {
+ return String(value);
+ }
+}
+
+function ResultRow({ row, index }: { row: FederatedRow; index: number }) {
+ const [expanded, setExpanded] = useState(false);
+ const source = row._aisoc_source;
+ const { _aisoc_source: _omit, ...fields } = row;
+ void _omit;
+
+ const pivots = pivotableFields(fields);
+
+ return (
+ <li className="rounded-lg border border-gray-800/60 bg-gray-900/40">
+ <div className="flex items-start gap-3 px-3 py-2.5">
+ <span className="mt-0.5 shrink-0 font-mono text-[11px] text-gray-600">
+ {index + 1}
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ {source && (
+ <span className="rounded border border-gray-700/60 bg-gray-800/60 px-1.5 py-0.5 text-[10px] text-gray-300">
+ {source.connector_name}
+ </span>
+ )}
+ {Object.entries(fields)
+ .slice(0, 4)
+ .map(([k, v]) => (
+ <span key={k} className="truncate text-xs text-gray-300">
+ <span className="text-gray-500">{k}=</span>
+ <span className="font-mono">{renderCell(v)}</span>
+ </span>
+ ))}
+ </div>
+ {pivots.length > 0 && (
+ <div className="mt-1.5 flex flex-wrap items-center gap-2">
+ {pivots.map((p) => (
+ <Link
+ key={`${p.type}:${p.value}`}
+ href={pivotPathForValue(p.type, p.value)}
+ className="rounded border border-gray-700/60 bg-gray-800/40 px-1.5 py-0.5 text-[10px] text-blue-300 hover:border-blue-500/50 hover:text-blue-200"
+ >
+ {`Pivot ${p.type}: ${p.value}`}
+ </Link>
+ ))}
+ </div>
+ )}
+ </div>
+ <button
+ type="button"
+ onClick={() => setExpanded((v) => !v)}
+ aria-expanded={expanded}
+ className="shrink-0 rounded border border-gray-700/60 px-2 py-0.5 text-[11px] text-gray-400 hover:border-gray-600 hover:text-gray-200"
+ >
+ {expanded ? 'Hide' : 'Raw'}
+ </button>
+ </div>
+ {expanded && (
+ <pre className="overflow-x-auto border-t border-gray-800/60 px-3 py-2 text-[11px] text-gray-400">
+ {JSON.stringify(fields, null, 2)}
+ </pre>
+ )}
+ </li>
+ );
+}
+
+// ─── Main view ────────────────────────────────────────────────────────────────
+
+export function FederatedSearchView() {
+ const {
+ data: backendsData,
+ error: backendsError,
+ isLoading: backendsLoading,
+ mutate: refetchBackends,
+ } = useSWR('federated-backends', () => federatedApi.listBackends(), {
+ revalidateOnFocus: false,
+ shouldRetryOnError: false,
+ });
+
+ const backends = useMemo(() => backendsData?.backends ?? [], [backendsData]);
+
+ const [selected, setSelected] = useState<Set<string>>(new Set());
+ const [freeText, setFreeText] = useState('');
+ const [indicators, setIndicators] = useState<IndicatorDraft[]>([]);
+ const [sinceSeconds, setSinceSeconds] = useState(3600);
+ const [limit, setLimit] = useState<number>(100);
+
+ const [running, setRunning] = useState(false);
+ const [result, setResult] = useState<FederatedSearchResponse | null>(null);
+ const [runError, setRunError] = useState<unknown>(null);
+ /** Echo of the query that produced `result`, so the header cannot drift. */
+ const [ranAt, setRanAt] = useState<string | null>(null);
+
+ const cleanedIndicators = useMemo(
+ () =>
+ indicators
+ .filter((i) => i.field.trim() !== '' && String(i.value).trim() !== '')
+ .map<FederatedIndicator>((i) => ({
+ field: i.field.trim(),
+ operator: i.operator,
+ // `in` is the one operator the server requires a list for.
+ value:
+ i.operator === 'in'
+ ? String(i.value)
+ .split(',')
+ .map((v) => v.trim())
+ .filter(Boolean)
+ : i.value,
+ }))
+ .filter((i) => (i.operator === 'in' ? (i.value as unknown[]).length > 0 : true)),
+ [indicators],
+ );
+
+ // Mirrors the server's own 422 precondition, so the analyst is told before
+ // the round-trip rather than after it.
+ const canRun = freeText.trim() !== '' || cleanedIndicators.length > 0;
+
+ const toggleBackend = useCallback(
+ (id: string) => {
+ setSelected((prev) => {
+ // An empty set means "all", which is also what the API does when
+ // `connector_ids` is omitted. Unticking one of an implicit-all
+ // selection has to materialise the rest first or it would read as
+ // "select only this one".
+ const base = prev.size === 0 ? new Set(backends.map((b) => b.connector_id)) : new Set(prev);
+ if (base.has(id)) base.delete(id);
+ else base.add(id);
+ return base;
+ });
+ },
+ [backends],
+ );
+
+ const selectAll = useCallback(
+ (all: boolean) => setSelected(all ? new Set() : new Set(['__none__'])),
+ [],
+ );
+
+ const run = useCallback(async () => {
+ if (!canRun || running) return;
+ setRunning(true);
+ setRunError(null);
+ try {
+ const chosen = [...selected].filter((id) => id !== '__none__');
+ const response = await federatedApi.search({
+ free_text: freeText.trim(),
+ indicators: cleanedIndicators,
+ since_seconds: sinceSeconds,
+ limit,
+ // Omit entirely to mean "every enabled backend" — sending [] would be
+ // an explicit empty subset, which is not the same request.
+ connector_ids: chosen.length > 0 && chosen.length < backends.length ? chosen : null,
+ });
+ setResult(response);
+ setRanAt(new Date().toISOString());
+ } catch (err) {
+ setRunError(err);
+ setResult(null);
+ } finally {
+ setRunning(false);
+ }
+ }, [canRun, running, selected, freeText, cleanedIndicators, sinceSeconds, limit, backends.length]);
+
+ // ── Feature disabled ────────────────────────────────────────────────────────
+ if (backendsError instanceof FederatedSearchDisabledError) {
+ return (
+ <EmptyState
+ title="Federated search is turned off on this deployment"
+ description="Set AISOC_FEATURE_FED_SEARCH=true on the API service to enable cross-SIEM search. No query is sent while it is disabled."
+ />
+ );
+ }
+
+ if (backendsError) {
+ return (
+ <ErrorState
+ title="Could not list federated backends"
+ description="The API did not return the connector list, so there is nothing to query against yet."
+ error={backendsError}
+ onRetry={() => {
+ void refetchBackends();
+ }}
+ />
+ );
+ }
+
+ return (
+ <div className="space-y-5">
+ <header>
+ <h1 className="text-xl font-semibold text-gray-100">Federated search</h1>
+ <p className="mt-1 text-sm text-gray-500">
+ One query, fanned out in parallel to every SIEM this tenant has connected,
+ using that tenant&apos;s own stored credentials. Each backend answers
+ independently.
+ </p>
+ </header>
+
+ {backendsLoading ? (
+ <div className="h-32 animate-pulse rounded-xl bg-gray-800/30" />
+ ) : backends.length === 0 ? (
+ <EmptyState
+ title="No SIEM connectors are connected"
+ description="Federated search queries Splunk, Microsoft Sentinel, Elastic and QRadar connectors. Connect and enable at least one to search across them."
+ action={
+ <Link
+ href="/connectors"
+ className="text-sm text-blue-400 underline underline-offset-2 hover:text-blue-300"
+ >
+ Connect a SIEM
+ </Link>
+ }
+ />
+ ) : (
+ <>
+ <BackendPicker
+ backends={backends}
+ selected={selected}
+ onToggle={toggleBackend}
+ onSelectAll={selectAll}
+ />
+
+ <form
+ className="space-y-4 rounded-xl border border-gray-800/60 bg-gray-900/40 p-4"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void run();
+ }}
+ >
+ <div>
+ <label htmlFor="fed-free-text" className="mb-1.5 block text-xs font-medium uppercase tracking-wider text-gray-500">
+ Search text
+ </label>
+ <input
+ id="fed-free-text"
+ type="text"
+ value={freeText}
+ onChange={(e) => setFreeText(e.target.value)}
+ placeholder="e.g. failed logon, or an indicator like 10.0.0.7"
+ className="w-full rounded-lg border border-gray-700 bg-gray-950/60 px-3 py-2 text-sm text-gray-100 placeholder:text-gray-600 focus:border-blue-500 focus:outline-none"
+ />
+ <p className="mt-1 text-[11px] text-gray-600">
+ Translated per backend into SPL, KQL, ES|QL or AQL. You never write
+ vendor query syntax here.
+ </p>
+ </div>
+
+ <div>
+ <div className="mb-1.5 flex items-center justify-between">
+ <span className="text-xs font-medium uppercase tracking-wider text-gray-500">
+ Field filters
+ </span>
+ <button
+ type="button"
+ onClick={() => setIndicators((prev) => [...prev, newIndicator()])}
+ className="text-xs text-blue-400 underline underline-offset-2 hover:text-blue-300"
+ >
+ Add filter
+ </button>
+ </div>
+ {indicators.length === 0 ? (
+ <p className="text-[11px] text-gray-600">
+ Optional. Filters are AND-joined with each other and with the
+ search text above.
+ </p>
+ ) : (
+ <ul className="space-y-2">
+ {indicators.map((ind, idx) => (
+ <li key={ind.id} className="flex flex-wrap items-center gap-2">
+ <input
+ aria-label={`Filter ${idx + 1} field`}
+ type="text"
+ value={ind.field}
+ placeholder="field"
+ onChange={(e) =>
+ setIndicators((prev) =>
+ prev.map((p) => (p.id === ind.id ? { ...p, field: e.target.value } : p)),
+ )
+ }
+ className="min-w-0 flex-1 rounded-lg border border-gray-700 bg-gray-950/60 px-2.5 py-1.5 text-sm text-gray-100 placeholder:text-gray-600 focus:border-blue-500 focus:outline-none"
+ />
+ <select
+ aria-label={`Filter ${idx + 1} operator`}
+ value={ind.operator}
+ onChange={(e) =>
+ setIndicators((prev) =>
+ prev.map((p) =>
+ p.id === ind.id
+ ? { ...p, operator: e.target.value as FederatedOperator }
+ : p,
+ ),
+ )
+ }
+ className="rounded-lg border border-gray-700 bg-gray-950/60 px-2 py-1.5 text-sm text-gray-100 focus:border-blue-500 focus:outline-none"
+ >
+ {FEDERATED_OPERATORS.map((op) => (
+ <option key={op} value={op}>
+ {op}
+ </option>
+ ))}
+ </select>
+ <input
+ aria-label={`Filter ${idx + 1} value`}
+ type="text"
+ value={String(ind.value)}
+ placeholder={ind.operator === 'in' ? 'a, b, c' : 'value'}
+ onChange={(e) =>
+ setIndicators((prev) =>
+ prev.map((p) => (p.id === ind.id ? { ...p, value: e.target.value } : p)),
+ )
+ }
+ className="min-w-0 flex-1 rounded-lg border border-gray-700 bg-gray-950/60 px-2.5 py-1.5 text-sm text-gray-100 placeholder:text-gray-600 focus:border-blue-500 focus:outline-none"
+ />
+ <button
+ type="button"
+ aria-label={`Remove filter ${idx + 1}`}
+ onClick={() => setIndicators((prev) => prev.filter((p) => p.id !== ind.id))}
+ className="rounded border border-gray-700/60 px-2 py-1 text-xs text-gray-400 hover:border-red-500/50 hover:text-red-300"
+ >
+ Remove
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+
+ <div className="flex flex-wrap items-end gap-4">
+ <div>
+ <label htmlFor="fed-window" className="mb-1.5 block text-xs font-medium uppercase tracking-wider text-gray-500">
+ Time window
+ </label>
+ <select
+ id="fed-window"
+ value={sinceSeconds}
+ onChange={(e) => setSinceSeconds(Number(e.target.value))}
+ className="rounded-lg border border-gray-700 bg-gray-950/60 px-2.5 py-1.5 text-sm text-gray-100 focus:border-blue-500 focus:outline-none"
+ >
+ {TIME_WINDOWS.map((w) => (
+ <option key={w.seconds} value={w.seconds}>
+ Last {w.label}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div>
+ <label htmlFor="fed-limit" className="mb-1.5 block text-xs font-medium uppercase tracking-wider text-gray-500">
+ Row cap
+ </label>
+ <select
+ id="fed-limit"
+ value={limit}
+ onChange={(e) => setLimit(Number(e.target.value))}
+ className="rounded-lg border border-gray-700 bg-gray-950/60 px-2.5 py-1.5 text-sm text-gray-100 focus:border-blue-500 focus:outline-none"
+ >
+ {ROW_LIMITS.map((l) => (
+ <option key={l} value={l}>
+ {l} rows
+ </option>
+ ))}
+ </select>
+ </div>
+ <button
+ type="submit"
+ disabled={!canRun || running}
+ className={clsx(
+ 'rounded-lg px-4 py-2 text-sm font-medium transition-colors',
+ canRun && !running
+ ? 'bg-blue-600 text-white hover:bg-blue-500'
+ : 'cursor-not-allowed bg-gray-800 text-gray-500',
+ )}
+ >
+ {running ? 'Searching…' : 'Run federated search'}
+ </button>
+ {!canRun && (
+ <p className="text-[11px] text-gray-600">
+ Enter search text or at least one field filter.
+ </p>
+ )}
+ </div>
+ </form>
+
+ {runError != null && (
+ <ErrorState
+ title="Federated search failed"
+ description="The request did not reach the backends. No partial results are shown."
+ error={runError}
+ onRetry={() => {
+ void run();
+ }}
+ />
+ )}
+
+ {result && (
+ <div className="space-y-4">
+ <SourceVerdictStrip sources={result.sources} />
+
+ <section aria-labelledby="fed-rows-heading">
+ <div className="mb-2 flex items-baseline justify-between">
+ <h2 id="fed-rows-heading" className="text-sm font-medium text-gray-300">
+ Merged rows
+ </h2>
+ <p className="text-xs text-gray-500">
+ {`${result.row_count} ${result.row_count === 1 ? 'row' : 'rows'}`}
+ {ranAt ? ` · ${new Date(ranAt).toLocaleTimeString()}` : ''}
+ </p>
+ </div>
+ {result.truncated && (
+ <p
+ role="status"
+ className="mb-2 rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-200"
+ >
+ Capped at {limit} rows after merging. Narrow the window or add a
+ filter to see the rest.
+ </p>
+ )}
+ {result.rows.length === 0 ? (
+ <EmptyState
+ title={
+ result.sources.some((s) => s.status === 'ok')
+ ? 'No matching events'
+ : 'No backend returned results'
+ }
+ description={
+ result.sources.some((s) => s.status === 'ok')
+ ? 'At least one backend answered and matched nothing in this window.'
+ : 'Every backend failed or was skipped. The per-backend result above carries each failure.'
+ }
+ />
+ ) : (
+ <ul className="space-y-2">
+ {result.rows.map((row, i) => (
+ <ResultRow key={i} row={row} index={i} />
+ ))}
+ </ul>
+ )}
+ </section>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/federated/pivot.test.ts b/apps/web/src/components/federated/pivot.test.ts
new file mode 100644
index 000000000..295d0fd8a
--- /dev/null
+++ b/apps/web/src/components/federated/pivot.test.ts
@@ -0,0 +1,97 @@
+/**
+ * Pivot extraction from a federated SIEM row.
+ *
+ * The rule under test is conservative on purpose: recognise the field names we
+ * actually know, and offer no pivot for anything else. A pivot on the wrong
+ * entity is worse than no pivot — it widens the analyst's picture with an
+ * unrelated node while looking exactly like a correct one.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { pivotPathForValue, pivotableFields } from './pivot';
+
+describe('pivotableFields', () => {
+ it('recognises the same entity across three vendors field-naming styles', () => {
+ expect(pivotableFields({ src_ip: '10.0.0.7' })).toEqual([{ type: 'ip', value: '10.0.0.7' }]);
+ expect(pivotableFields({ 'source.ip': '10.0.0.7' })).toEqual([{ type: 'ip', value: '10.0.0.7' }]);
+ expect(pivotableFields({ SourceIP: '10.0.0.7' })).toEqual([{ type: 'ip', value: '10.0.0.7' }]);
+ });
+
+ it('pulls host, user, ip and domain out of one wide row', () => {
+ const targets = pivotableFields({
+ hostname: 'WIN-DC01',
+ 'user.name': 'svc_backup',
+ dest_ip: '198.51.100.9',
+ fqdn: 'updates.example.test',
+ });
+
+ expect(targets).toEqual([
+ { type: 'host', value: 'WIN-DC01' },
+ { type: 'user', value: 'svc_backup' },
+ { type: 'ip', value: '198.51.100.9' },
+ { type: 'domain', value: 'updates.example.test' },
+ ]);
+ });
+
+ it('does not treat every field containing "ip" as an address', () => {
+ // `zip`, `recipient` and `description` all contain "ip". A substring
+ // heuristic would offer three wrong pivots for this row.
+ const targets = pivotableFields({
+ zip: '94107',
+ recipient: '[email protected]',
+ description: 'ip allowlist updated',
+ });
+
+ expect(targets).toEqual([]);
+ });
+
+ it('offers nothing for an unrecognised column', () => {
+ expect(pivotableFields({ some_vendor_specific_column: 'value' })).toEqual([]);
+ });
+
+ it('skips vendor placeholders that would pivot to a node that cannot exist', () => {
+ for (const placeholder of ['-', 'null', 'N/A', 'unknown', '(null)', ' ']) {
+ expect(pivotableFields({ host: placeholder }), placeholder).toEqual([]);
+ }
+ });
+
+ it('skips non-scalar and over-long values', () => {
+ expect(pivotableFields({ host: { nested: true } })).toEqual([]);
+ expect(pivotableFields({ host: 'x'.repeat(256) })).toEqual([]);
+ // A numeric identifier is still an identifier.
+ expect(pivotableFields({ host: 42 })).toEqual([{ type: 'host', value: '42' }]);
+ });
+
+ it('de-duplicates the same entity reached through two column names', () => {
+ const targets = pivotableFields({ src: '10.0.0.7', src_ip: '10.0.0.7' });
+ expect(targets).toEqual([{ type: 'ip', value: '10.0.0.7' }]);
+ });
+
+ it('caps the chip count so a wide row does not become a wall of links', () => {
+ const wide = {
+ host: 'h1',
+ user: 'u1',
+ src_ip: '10.0.0.1',
+ domain: 'a.example.test',
+ computer: 'h2',
+ account: 'u2',
+ dest_ip: '10.0.0.2',
+ };
+ expect(pivotableFields(wide)).toHaveLength(4);
+ expect(pivotableFields(wide, 2)).toHaveLength(2);
+ });
+});
+
+describe('pivotPathForValue', () => {
+ it('targets the route the Investigation Rail entity chips already use', () => {
+ expect(pivotPathForValue('host', 'WIN-DC01')).toBe('/graph?entity=host%3AWIN-DC01');
+ });
+
+ it('encodes exactly once, so a value with a slash or space survives', () => {
+ expect(pivotPathForValue('user', 'CORP\\svc backup')).toBe(
+ '/graph?entity=user%3ACORP%5Csvc%20backup',
+ );
+ const url = new URL(pivotPathForValue('user', 'CORP\\svc backup'), 'https://example.test');
+ expect(url.searchParams.get('entity')).toBe('user:CORP\\svc backup');
+ });
+});
diff --git a/apps/web/src/components/federated/pivot.ts b/apps/web/src/components/federated/pivot.ts
new file mode 100644
index 000000000..4efceed74
--- /dev/null
+++ b/apps/web/src/components/federated/pivot.ts
@@ -0,0 +1,145 @@
+/**
+ * Turning a SIEM row into a pivot the console can actually service.
+ *
+ * Federated rows arrive in whatever shape the vendor emits — Splunk's `src`,
+ * Sentinel's `SourceIP`, Elastic's `source.ip`. To offer a pivot we have to
+ * recognise the entity inside the row first, and we only claim a pivot for the
+ * field names we genuinely recognise. An unrecognised column renders as plain
+ * text rather than a link that lands somewhere unhelpful.
+ *
+ * The target is `/graph?entity=<type>:<value>`, which is the URL shape the
+ * Investigation Rail's entity chips already use (`services/api/app/services/
+ * alert_rail.py` builds `entity=host:…`, `entity=ip:…`). `AttackGraphView`
+ * reads and honours that parameter, so these links select the node rather than
+ * merely landing on the page.
+ */
+
+export type PivotEntityType = 'host' | 'user' | 'ip' | 'domain';
+
+export interface PivotTarget {
+ type: PivotEntityType;
+ value: string;
+}
+
+/**
+ * Field names, lower-cased, that carry each entity type.
+ *
+ * Deliberately a fixed list rather than a heuristic. A regex that guesses
+ * "anything containing `ip`" also matches `zip`, `recipient` and `description`,
+ * and a pivot on the wrong entity is worse than no pivot: it silently widens
+ * the analyst's picture with an unrelated node.
+ */
+const FIELD_MAP: ReadonlyArray<readonly [PivotEntityType, ReadonlySet<string>]> = [
+ [
+ 'host',
+ new Set([
+ 'host',
+ 'hostname',
+ 'host.name',
+ 'computer',
+ 'computername',
+ 'device.name',
+ 'dvc',
+ 'machine',
+ 'src_host',
+ 'agent.name',
+ ]),
+ ],
+ [
+ 'user',
+ new Set([
+ 'user',
+ 'username',
+ 'user.name',
+ 'user_name',
+ 'account',
+ 'accountname',
+ 'actor.user.name',
+ 'subjectusername',
+ 'samaccountname',
+ ]),
+ ],
+ [
+ 'ip',
+ new Set([
+ 'ip',
+ 'src',
+ 'src_ip',
+ 'source.ip',
+ 'sourceip',
+ 'client_ip',
+ 'clientip',
+ 'dest',
+ 'dest_ip',
+ 'destination.ip',
+ 'destinationip',
+ 'src_endpoint.ip',
+ 'remote_ip',
+ ]),
+ ],
+ [
+ 'domain',
+ new Set([
+ 'domain',
+ 'dns.question.name',
+ 'query',
+ 'fqdn',
+ 'url_domain',
+ 'dest_host',
+ 'http_host',
+ ]),
+ ],
+];
+
+/** Longest value we will put in a URL. Beyond this it is not an identifier. */
+const MAX_PIVOT_VALUE = 255;
+
+function normaliseValue(raw: unknown): string | null {
+ if (typeof raw === 'number') return String(raw);
+ if (typeof raw !== 'string') return null;
+ const trimmed = raw.trim();
+ if (trimmed === '' || trimmed.length > MAX_PIVOT_VALUE) return null;
+ // Placeholders several vendors emit for "field present but unset". Linking
+ // on these produces a pivot to a node that cannot exist.
+ if (['-', 'null', 'none', 'n/a', 'unknown', '(null)'].includes(trimmed.toLowerCase())) {
+ return null;
+ }
+ return trimmed;
+}
+
+/**
+ * Entities worth pivoting on in one row, de-duplicated by `type:value`.
+ *
+ * Capped, because a wide SIEM row can carry a dozen recognised columns and a
+ * row of twelve pivot chips is not a pivot affordance, it is noise.
+ */
+export function pivotableFields(
+ fields: Record<string, unknown>,
+ max = 4,
+): PivotTarget[] {
+ const seen = new Set<string>();
+ const out: PivotTarget[] = [];
+
+ for (const [key, raw] of Object.entries(fields)) {
+ const lower = key.toLowerCase();
+ const match = FIELD_MAP.find(([, names]) => names.has(lower));
+ if (!match) continue;
+
+ const value = normaliseValue(raw);
+ if (value === null) continue;
+
+ const dedupeKey = `${match[0]}:${value.toLowerCase()}`;
+ if (seen.has(dedupeKey)) continue;
+ seen.add(dedupeKey);
+ out.push({ type: match[0], value });
+
+ if (out.length >= max) break;
+ }
+
+ return out;
+}
+
+/** `/graph?entity=<type>:<value>`, with the value encoded exactly once. */
+export function pivotPathForValue(type: PivotEntityType, value: string): string {
+ return `/graph?entity=${encodeURIComponent(`${type}:${value}`)}`;
+}
diff --git a/apps/web/src/components/graph/AttackGraphClient.tsx b/apps/web/src/components/graph/AttackGraphClient.tsx
index 6cd99b4b0..a8a62f0af 100644
--- a/apps/web/src/components/graph/AttackGraphClient.tsx
+++ b/apps/web/src/components/graph/AttackGraphClient.tsx
@@ -1,5 +1,6 @@
'use client';
+import { Suspense } from 'react';
import dynamic from 'next/dynamic';
const AttackGraphView = dynamic(
@@ -18,5 +19,17 @@ const AttackGraphView = dynamic(
);
export default function AttackGraphClient() {
- return <AttackGraphView />;
+ // `AttackGraphView` reads `?entity=` via `useSearchParams`, which Next
+ // requires to sit under a Suspense boundary.
+ return (
+ <Suspense
+ fallback={
+ <div className="flex h-[60vh] items-center justify-center text-gray-400">
+ Loading attack graph…
+ </div>
+ }
+ >
+ <AttackGraphView />
+ </Suspense>
+ );
}
diff --git a/apps/web/src/components/graph/AttackGraphEntityParam.test.tsx b/apps/web/src/components/graph/AttackGraphEntityParam.test.tsx
new file mode 100644
index 000000000..f8e9c5752
--- /dev/null
+++ b/apps/web/src/components/graph/AttackGraphEntityParam.test.tsx
@@ -0,0 +1,63 @@
+/**
+ * `/graph?entity=…` selects the node it names.
+ *
+ * Several callers already built that URL — the Investigation Rail's entity
+ * chips (`services/api/app/services/alert_rail.py` emits `entity=host:…`,
+ * `entity=ip:…`) and `HuntView`'s "Pivot to graph" button — and nothing read
+ * it. The pivot navigated to the graph and dropped the entity, so the analyst
+ * arrived at an unfiltered topology and had to find the node by eye.
+ *
+ * Federated search adds a third caller, so the parameter is now honoured.
+ *
+ * `GraphCanvas` drives cytoscape against a real canvas, which jsdom does not
+ * provide, so the node-matching half is tested directly and the wiring is
+ * covered by the type checker plus the production build.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { findNodeForEntityParam } from './AttackGraphView';
+import type { GraphNode } from '@/lib/api';
+
+const NODES: GraphNode[] = [
+ { id: 'host:WIN-DC01', label: 'WIN-DC01', kind: 'asset' },
+ { id: 'user:svc_backup', label: 'svc_backup', kind: 'user' },
+ { id: 'ip:10.0.0.7', label: '10.0.0.7', kind: 'ip' },
+];
+
+describe('findNodeForEntityParam', () => {
+ it('matches the typed form the rail and federated search emit', () => {
+ expect(findNodeForEntityParam(NODES, 'host:WIN-DC01')?.id).toBe('host:WIN-DC01');
+ expect(findNodeForEntityParam(NODES, 'ip:10.0.0.7')?.id).toBe('ip:10.0.0.7');
+ });
+
+ it('matches the bare form HuntView\u2019s pivot button emits', () => {
+ // `HuntView` builds `/graph?entity=${host}` with no type prefix.
+ expect(findNodeForEntityParam(NODES, 'WIN-DC01')?.id).toBe('host:WIN-DC01');
+ });
+
+ it('treats the type half as a hint, not a requirement', () => {
+ // An operator pasting the wrong prefix should still land on the node.
+ expect(findNodeForEntityParam(NODES, 'asset:WIN-DC01')?.id).toBe('host:WIN-DC01');
+ });
+
+ it('is case-insensitive on the value', () => {
+ expect(findNodeForEntityParam(NODES, 'host:win-dc01')?.id).toBe('host:WIN-DC01');
+ });
+
+ it('selects nothing rather than guessing when there is no match', () => {
+ expect(findNodeForEntityParam(NODES, 'host:NOT-IN-GRAPH')).toBeNull();
+ expect(findNodeForEntityParam(NODES, '')).toBeNull();
+ expect(findNodeForEntityParam(NODES, ' ')).toBeNull();
+ expect(findNodeForEntityParam(NODES, 'host:')).toBeNull();
+ expect(findNodeForEntityParam(NODES, null)).toBeNull();
+ expect(findNodeForEntityParam([], 'host:WIN-DC01')).toBeNull();
+ });
+
+ it('prefers an id match over a label match', () => {
+ const ambiguous: GraphNode[] = [
+ { id: 'other', label: 'WIN-DC01', kind: 'asset' },
+ { id: 'WIN-DC01', label: 'something-else', kind: 'asset' },
+ ];
+ expect(findNodeForEntityParam(ambiguous, 'WIN-DC01')?.id).toBe('WIN-DC01');
+ });
+});
diff --git a/apps/web/src/components/graph/AttackGraphView.tsx b/apps/web/src/components/graph/AttackGraphView.tsx
index 9e1270a61..b3e514869 100644
--- a/apps/web/src/components/graph/AttackGraphView.tsx
+++ b/apps/web/src/components/graph/AttackGraphView.tsx
@@ -14,6 +14,7 @@
*/
import { useEffect, useMemo, useRef, useState } from 'react';
+import { useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import cytoscape, {
type Core,
@@ -331,8 +332,52 @@ function MitreHeatmap({ coverage }: { coverage: MitreCoverage }) {
// ─── Main view ────────────────────────────────────────────────────────────────
+/**
+ * Match `?entity=` against a loaded node.
+ *
+ * Accepts both the `host:WIN-DC01` form the Investigation Rail and federated
+ * search emit, and a bare `WIN-DC01`, because `HuntView`'s existing pivot
+ * sends the bare value. The type half is used as a hint rather than a
+ * requirement: an operator who pastes `ip:10.0.0.7` should still land on the
+ * node if the graph happens to label it differently.
+ */
+export function findNodeForEntityParam(
+ nodes: readonly GraphNode[],
+ entity: string | null,
+): GraphNode | null {
+ if (!entity) return null;
+ const raw = entity.trim();
+ if (raw === '') return null;
+
+ const sep = raw.indexOf(':');
+ const value = (sep > 0 ? raw.slice(sep + 1) : raw).trim().toLowerCase();
+ if (value === '') return null;
+
+ return (
+ nodes.find((n) => n.id.toLowerCase() === value) ??
+ nodes.find((n) => n.label.toLowerCase() === value) ??
+ null
+ );
+}
+
export function AttackGraphView() {
- const [selected, setSelected] = useState<GraphNode | null>(null);
+ const searchParams = useSearchParams();
+ const entityParam = searchParams?.get('entity') ?? null;
+
+ /**
+ * Selection is derived from `?entity=` until the analyst picks for
+ * themselves, then their choice wins.
+ *
+ * The wrapper object is what distinguishes "has not chosen yet" (`null`)
+ * from "explicitly dismissed the panel" (`{ node: null }`); collapsing
+ * those would make the deep-linked node reappear every time the 30-second
+ * graph refresh landed.
+ *
+ * Deriving rather than syncing in an effect also keeps the deep link
+ * working when the parameter is present on first render but the nodes
+ * arrive with the fetch, which is the normal case.
+ */
+ const [override, setOverride] = useState<{ node: GraphNode | null } | null>(null);
const graphState = useSWR<AttackGraph>(
'attack-graph',
@@ -369,6 +414,13 @@ export function AttackGraphView() {
const graph = graphState.data;
const mitre = mitreState.data;
+ const entityMatch = useMemo(
+ () => findNodeForEntityParam(graph?.nodes ?? [], entityParam),
+ [graph?.nodes, entityParam],
+ );
+ const selected = override ? override.node : entityMatch;
+ const setSelected = (node: GraphNode | null) => setOverride({ node });
+
return (
<div className="space-y-6">
<header className="flex flex-col gap-2">
diff --git a/apps/web/src/components/layout/Sidebar.tsx b/apps/web/src/components/layout/Sidebar.tsx
index 3562e1aea..90a1978f8 100644
--- a/apps/web/src/components/layout/Sidebar.tsx
+++ b/apps/web/src/components/layout/Sidebar.tsx
@@ -155,6 +155,11 @@ const navSections: NavSection[] = [
href: '/dashboards/soc-insights',
icon: <ChartBarIcon />,
},
+ {
+ label: 'SOC Operations',
+ href: '/dashboards/operations',
+ icon: <ChartBarIcon />,
+ },
],
},
{
@@ -183,6 +188,11 @@ const navSections: NavSection[] = [
href: '/hunt',
icon: <SearchIcon />,
},
+ {
+ label: 'Federated Search',
+ href: '/federated-search',
+ icon: <SearchIcon />,
+ },
{
label: 'Explore',
href: '/explore',
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 29a65a3f0..0fd2140a7 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -1965,6 +1965,87 @@ export const metricsApi = {
getSOC: () => request<SOCMetrics>('/api/v1/metrics/soc'),
};
+// ─── Operational health: connector fleet, rejected events, alert posture ─────
+//
+// Three endpoints that existed server-side with no client. They answer the
+// question the alert-centric dashboards structurally cannot: whether the
+// absence of alerts means the estate is quiet or the pipeline stopped.
+
+/** How a connector is doing against *its own* configured poll cadence. */
+export type FleetHealthState = 'healthy' | 'degraded' | 'failed' | 'unproven' | 'disabled';
+
+export interface FleetConnectorHealth {
+ connector_id: string;
+ name: string;
+ connector_type: string;
+ state: FleetHealthState;
+ /** Operator-actionable wording from the server. Never bare "unhealthy". */
+ reason: string;
+ last_sync: string | null;
+ seconds_since_sync: number | null;
+ poll_interval_seconds: number;
+ /** How many poll cycles have been missed. Fractional. */
+ missed_intervals: number | null;
+ error_count: number;
+ events_ingested: number;
+ oauth_refresh_failures: number;
+ schema_drift_at: string | null;
+}
+
+export interface FleetHealth {
+ generated_at: string;
+ /** Worst enabled connector's state — deliberately not an average. */
+ state: FleetHealthState;
+ counts: Record<FleetHealthState, number>;
+ connectors: FleetConnectorHealth[];
+}
+
+export interface DeadLetterEntry {
+ id: string;
+ topic: string;
+ reason: string;
+ schema_version: string | null;
+ payload_excerpt: string | null;
+ source_event_id: string | null;
+ occurred_at: string | null;
+ acknowledged: boolean;
+}
+
+export interface DeadLetters {
+ window_hours: number;
+ total: number;
+ by_reason: Array<{ reason: string; count: number }>;
+ truncated: boolean;
+ dead_letters: DeadLetterEntry[];
+}
+
+export interface AlertStats {
+ total: number;
+ by_severity: Record<string, number>;
+ by_status: Record<string, number>;
+ new_last_24h: number;
+ critical_open: number;
+}
+
+export const operationsApi = {
+ /**
+ * Which connectors have quietly stopped working.
+ *
+ * Staleness is judged per connector against its own cadence, so a daily
+ * connector is not reported as failing eleven hours in.
+ */
+ fleetHealth: () => request<FleetHealth>('/api/v1/health/fleet'),
+
+ /** Events the pipeline refused, and why. */
+ deadLetters: (params: { hours?: number; limit?: number } = {}) =>
+ request<DeadLetters>('/api/v1/health/dead-letters', {
+ params: params as Record<string, string>,
+ }),
+
+ /** Severity / status distribution plus the two counters worth paging on. */
+ alertStats: () => request<AlertStats>('/api/v1/alerts/stats'),
+};
+
// ─── Investigations ─────────────────────────────────────────────────────────
export const investigationsApi = {
@@ -3061,6 +3142,170 @@ export const lakeApi = {
schema: () => request<LakeSchemaResponse>('/api/v1/lake/schema'),
};
+// ─── Federated SIEM search ───────────────────────────────────────────────────
+//
+// Client for `services/api/app/api/v1/endpoints/federated.py`, which fans one
+// `UnifiedQuery` out to every federated-capable connector the tenant has
+// enabled (Splunk, Microsoft Sentinel, Elastic, QRadar) using that tenant's
+// own vault-encrypted credentials, and merges the rows.
+//
+// The shape worth preserving through the client is `sources[]`. The endpoint
+// deliberately never fails the whole call because one backend is slow, 401s or
+// 5xxs — it returns a per-backend verdict instead. Collapsing that into a
+// single throw would discard exactly the information an analyst needs to tell
+// "Sentinel has nothing" from "Sentinel did not answer", so nothing here
+// treats a per-source error as a request error.
+
+/** Operator vocabulary accepted by `Indicator` in the connectors service. */
+export type FederatedOperator =
+ | 'eq'
+ | 'ne'
+ | 'contains'
+ | 'starts_with'
+ | 'ends_with'
+ | 'gt'
+ | 'gte'
+ | 'lt'
+ | 'lte'
+ | 'in';
+
+export const FEDERATED_OPERATORS: readonly FederatedOperator[] = [
+ 'eq',
+ 'ne',
+ 'contains',
+ 'starts_with',
+ 'ends_with',
+ 'gt',
+ 'gte',
+ 'lt',
+ 'lte',
+ 'in',
+] as const;
+
+/** One `field <op> value` triple. Stacking indicators implies AND. */
+export interface FederatedIndicator {
+ field: string;
+ operator: FederatedOperator;
+ value: unknown;
+}
+
+export interface FederatedSearchRequest {
+ free_text?: string;
+ indicators?: FederatedIndicator[];
+ since_seconds?: number;
+ limit?: number;
+ connector_ids?: string[] | null;
+ per_backend_timeout_seconds?: number | null;
+}
+
+/**
+ * Per-backend outcome.
+ *
+ * `status` is `ok` (rows returned, possibly zero), `error` (this backend
+ * failed and `error` carries the message; others may have succeeded), or
+ * `unsupported` (the connector type does not speak federated search).
+ */
+export interface FederatedSourceVerdict {
+ connector_id: string;
+ connector_name: string;
+ connector_type: string;
+ status: 'ok' | 'error' | 'unsupported';
+ row_count: number;
+ duration_ms: number;
+ error: string | null;
+}
+
+/** Source tag the API stamps onto every merged row. */
+export interface FederatedRowSource {
+ connector_id: string;
+ connector_name: string;
+ connector_type: string;
+}
+
+export type FederatedRow = Record<string, unknown> & {
+ _aisoc_source?: FederatedRowSource;
+};
+
+export interface FederatedSearchResponse {
+ rows: FederatedRow[];
+ row_count: number;
+ sources: FederatedSourceVerdict[];
+ truncated: boolean;
+}
+
+export interface FederatedBackend {
+ connector_id: string;
+ connector_type: string;
+ name: string;
+ health_status: string;
+ is_enabled: boolean;
+}
+
+export interface FederatedBackendsResponse {
+ backends: FederatedBackend[];
+}
+
+/**
+ * Thrown when the deployment has `AISOC_FEATURE_FED_SEARCH=false`.
+ *
+ * The endpoint answers 404 for that case, which is indistinguishable from a
+ * routing mistake unless the client names it. A disabled feature is a
+ * configuration fact the operator can act on; a generic "not found" is not.
+ */
+export class FederatedSearchDisabledError extends Error {
+ constructor() {
+ super('Federated search is disabled on this deployment (AISOC_FEATURE_FED_SEARCH).');
+ this.name = 'FederatedSearchDisabledError';
+ }
+}
+
+function asFederatedError(err: unknown): never {
+ // `_ensure_feature_enabled` answers 404 with this detail. The same endpoint
+ // also 404s for an unknown `connector_ids` entry, so match on the body
+ // rather than the status alone — misreporting a typo'd connector id as a
+ // disabled feature would send the operator to the wrong config file.
+ if (
+ err instanceof ApiError &&
+ err.status === 404 &&
+ /AISOC_FEATURE_FED_SEARCH|federated search is disabled/i.test(err.body)
+ ) {
+ throw new FederatedSearchDisabledError();
+ }
+ throw err;
+}
+
+export const federatedApi = {
+ /** Connector instances `search()` would fan out to, with their health. */
+ listBackends: async (): Promise<FederatedBackendsResponse> => {
+ try {
+ const raw = await request<Partial<FederatedBackendsResponse>>(
+ '/api/v1/federated/backends',
+ );
+ return { backends: Array.isArray(raw.backends) ? raw.backends : [] };
+ } catch (err) {
+ return asFederatedError(err);
+ }
+ },
+
+ search: async (body: FederatedSearchRequest): Promise<FederatedSearchResponse> => {
+ try {
+ const raw = await request<Partial<FederatedSearchResponse>>(
+ '/api/v1/federated/search',
+ { method: 'POST', body: JSON.stringify(body) },
+ );
+ const rows = Array.isArray(raw.rows) ? raw.rows : [];
+ return {
+ rows,
+ row_count: typeof raw.row_count === 'number' ? raw.row_count : rows.length,
+ sources: Array.isArray(raw.sources) ? raw.sources : [],
+ truncated: raw.truncated === true,
+ };
+ } catch (err) {
+ return asFederatedError(err);
+ }
+ },
+};
+
// ─── Natural-language query translator (T3.4) ────────────────────────────────
//
// Wraps `services/api/app/api/v1/endpoints/nl_query.py`. The translator