Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(console): stop rendering a failed read as a healthy result (#984)
Beenu Arora562bc660cd8a
diff --git a/apps/web/src/app/(app)/honeytokens/page.tsx b/apps/web/src/app/(app)/honeytokens/page.tsxindex a0d5d94d0..19616d9b5 100644--- a/apps/web/src/app/(app)/honeytokens/page.tsx+++ b/apps/web/src/app/(app)/honeytokens/page.tsx@@ -227,7 +227,7 @@ function CreateTokenModal({}function TriggersPanel({ tokenId, onClose }: { tokenId: string; onClose: () => void }) {- const { data: triggers, isLoading } = useSWR<Trigger[]>(+ const { data: triggers, error, isLoading } = useSWR<Trigger[]>(`${API}/api/v1/honeytokens/${tokenId}/triggers`,fetcher,{ refreshInterval: 10_000 }@@ -244,6 +244,11 @@ function TriggersPanel({ tokenId, onClose }: { tokenId: string; onClose: () => v</div>{isLoading ? (<p className="text-sm text-gray-500">Loading…</p>+ ) : error ? (+ // "token has not been accessed" is a claim about attacker+ // behaviour. A failed request is not evidence for it, and on a+ // deception surface the wrong direction to guess in.+ <p className="text-sm text-red-400">Could not load trigger history. Whether this token was accessed is unknown.</p>) : !triggers?.length ? (<p className="text-sm text-gray-500">No triggers yet — token has not been accessed.</p>) : (@@ -306,10 +311,14 @@ export default function HoneytokensPage() {? `${API}/api/v1/honeytokens?tenant_id=${tenantId}${statusFilter ? `&status=${statusFilter}` : ""}${typeFilter ? `&token_type=${typeFilter}` : ""}`: null;- const { data: rawTokens, isLoading } = useSWR<HoneytokenRecord[]>(listKey, fetcher, {+ const { data: rawTokens, error: listError, isLoading } = useSWR<HoneytokenRecord[]>(listKey, fetcher, {refreshInterval: 15_000,});const tokens = Array.isArray(rawTokens) ? rawTokens : undefined;+ // The stat cards sit outside the loading guard that wraps the table, so+ // `?? 0` rendered a confident "Triggered 0" beside a table still saying+ // "Loading tokens…", and kept it there when the read failed.+ const countsUnknown = tokens === undefined;const refresh = () => {if (listKey) void mutate(listKey);@@ -326,12 +335,14 @@ export default function HoneytokensPage() {refresh();};- const counts = {- total: tokens?.length ?? 0,- active: tokens?.filter((t) => t.status === "active").length ?? 0,- triggered: tokens?.filter((t) => t.status === "triggered").length ?? 0,- revoked: tokens?.filter((t) => t.status === "revoked").length ?? 0,- };+ const counts: Record<string, number | null> = countsUnknown+ ? { total: null, active: null, triggered: null, revoked: null }+ : {+ total: tokens.length,+ active: tokens.filter((t) => t.status === "active").length,+ triggered: tokens.filter((t) => t.status === "triggered").length,+ revoked: tokens.filter((t) => t.status === "revoked").length,+ };return (<div className="p-6 max-w-6xl mx-auto">@@ -363,7 +374,10 @@ export default function HoneytokensPage() {].map((s) => (<div key={s.label} className="bg-gray-900/60 border border-gray-700 rounded-lg p-4"><p className="text-xs text-gray-500 uppercase tracking-wide">{s.label}</p>- <p className={`text-2xl font-bold mt-1 ${s.color}`}>{s.value}</p>+ <p className={`text-2xl font-bold mt-1 ${s.value === null ? 'text-gray-600' : s.color}`}>+ {s.value === null ? '—' : s.value}+ </p>+ {s.value === null && <p className="text-[11px] text-gray-500 mt-0.5">not measured</p>}</div>))}</div>@@ -401,6 +415,10 @@ export default function HoneytokensPage() {<div className="p-8 text-center text-sm text-gray-500">Resolving the active tenant…</div>) : isLoading ? (<div className="p-8 text-center text-sm text-gray-500">Loading tokens…</div>+ ) : listError ? (+ <div className="p-8 text-center text-sm text-red-400">+ Could not load honeytokens. This is not a report that none exist.+ </div>) : !tokens?.length ? (<div className="p-8 text-center text-sm text-gray-500">No honeytokens found. Create your first one.diff --git a/apps/web/src/app/(app)/purple-team/page.tsx b/apps/web/src/app/(app)/purple-team/page.tsxindex 2cba22301..7fe6fcfc4 100644--- a/apps/web/src/app/(app)/purple-team/page.tsx+++ b/apps/web/src/app/(app)/purple-team/page.tsx@@ -218,7 +218,7 @@ function driftDeltaLabel(d: number, suffix = ''): string {function CoverageHeatmap() {const tenantId = useTenantId()- const { data } = useSWR<CoverageMatrix>(+ const { data, error, isLoading } = useSWR<CoverageMatrix>(tenantId ? `${API}/api/v1/purple-team/coverage?tenant_id=${tenantId}` : null,fetcher,{ refreshInterval: 30000, fallbackData: demoFallback(MOCK_COVERAGE) }@@ -267,6 +267,11 @@ function CoverageHeatmap() {techniques: {},summary: { total_techniques: 0, tested_techniques: 0, detected_techniques: 0, overall_coverage: 0 },}+ // "0 of 0 techniques, 0% coverage" is not the truthful reading when the+ // service has told us nothing: it says the estate has no ATT&CK techniques+ // to test, which is the reassuring interpretation of a failed read. A+ // number nobody measured must not be rendered as a number.+ const unknown = !dataconst resolved = data ?? EMPTY_COVERAGEconst {summary: rawSummary,@@ -283,6 +288,21 @@ function CoverageHeatmap() {const driftSummary = drift?.drift.summaryconst hasPrevious = Boolean(drift?.previous)+ if (unknown) {+ return (+ <div className="rounded-lg border border-gray-800 bg-gray-900/60 p-6 text-sm">+ <p className="font-medium text-gray-200">ATT&CK coverage unknown</p>+ <p className="mt-1 text-gray-500">+ {isLoading+ ? 'Loading coverage from the purple-team service…'+ : error+ ? 'The purple-team service did not answer. This is not a report of zero coverage.'+ : 'No coverage has been reported for this tenant yet.'}+ </p>+ </div>+ )+ }+return (<div className="space-y-4">{/* Summary cards — show absolute values + delta-vs-last-snapshot when available. */}diff --git a/apps/web/src/app/r/[slug]/opengraph-image.tsx b/apps/web/src/app/r/[slug]/opengraph-image.tsxindex 0a86b861f..4f99959bd 100644--- a/apps/web/src/app/r/[slug]/opengraph-image.tsx+++ b/apps/web/src/app/r/[slug]/opengraph-image.tsx@@ -17,7 +17,8 @@ function verdictColor(verdict: string): string {export default async function Image({ params }: { params: Promise<{ slug: string }> }) {const { slug } = await params;- const replay = await fetchPublicReplay(slug);+ const result = await fetchPublicReplay(slug);+ const replay = result.kind === "ok" ? result.replay : null;const s = replay?.snapshot;const verdict = s?.verdict ?? "unknown";const title = replay?.title ?? "Investigation replay";diff --git a/apps/web/src/app/r/[slug]/page.tsx b/apps/web/src/app/r/[slug]/page.tsxindex 5ffc63047..5f1466b9a 100644--- a/apps/web/src/app/r/[slug]/page.tsx+++ b/apps/web/src/app/r/[slug]/page.tsx@@ -12,10 +12,14 @@ interface PageProps {export async function generateMetadata({ params }: PageProps): Promise<Metadata> {const { slug } = await params;- const replay = await fetchPublicReplay(slug);- if (!replay) {+ const result = await fetchPublicReplay(slug);+ if (result.kind === "unavailable") {+ return { title: "Replay temporarily unavailable · AiSOC" };+ }+ if (result.kind === "missing") {return { title: "Replay not found · AiSOC" };}+ const replay = result.replay;const s = replay.snapshot;const title = `${replay.title} · AiSOC investigation replay`;const description = `Verdict: ${s.verdict.replace(/_/g, " ")} · investigated in ${(s.elapsedMs / 1000).toFixed(@@ -31,11 +35,33 @@ export async function generateMetadata({ params }: PageProps): Promise<Metadata>};}+function ReplayUnavailable({ status }: { status: number | null }) {+ return (+ <main style={{ background: "#0b1020", minHeight: "100vh", color: "#e6e9f5", padding: "48px 24px" }}>+ <div style={{ maxWidth: 640, margin: "0 auto" }}>+ <Link href="/" style={{ color: "#8b93b7", textDecoration: "none", fontSize: 14 }}>+ ← AiSOC+ </Link>+ <h1 style={{ fontSize: 26, fontWeight: 800, margin: "24px 0 8px" }}>Replay temporarily unavailable</h1>+ <p style={{ color: "#8b93b7", fontSize: 15, lineHeight: 1.6 }}>+ This link is fine — we could not reach the service that serves it+ {status ? ` (HTTP ${status})` : " (no response)"}. Try again shortly.+ </p>+ </div>+ </main>+ );+}+export default async function ReplayPage({ params }: PageProps) {const { slug } = await params;- const replay = await fetchPublicReplay(slug);- if (!replay) notFound();+ const result = await fetchPublicReplay(slug);+ // Only a real 404 is a missing replay. Anything else is our outage, and+ // telling the reader their identifier is wrong sends them to debug a link+ // that is fine.+ if (result.kind === "missing") notFound();+ if (result.kind === "unavailable") return <ReplayUnavailable status={result.status} />;+ const replay = result.replay;const s = replay.snapshot;return (<main style={{ background: "#0b1020", minHeight: "100vh", color: "#e6e9f5", padding: "48px 24px" }}>diff --git a/apps/web/src/components/cases/CasesView.tsx b/apps/web/src/components/cases/CasesView.tsxindex ee6abebfe..c801f1649 100644--- a/apps/web/src/components/cases/CasesView.tsx+++ b/apps/web/src/components/cases/CasesView.tsx@@ -168,7 +168,7 @@ export function CasesView({ initialCases }: CasesViewProps = {}) {pageSize: MOCK_CASES.length,});- const { data: casesData, isLoading } = useSWR(+ const { data: casesData, error, isLoading } = useSWR(['cases', statusFilter, severityFilter],() => casesApi.list({ status: statusFilter !== 'all' ? statusFilter : undefined }),{@@ -189,13 +189,19 @@ export function CasesView({ initialCases }: CasesViewProps = {}) {// The list above already falls back to `[]`; this counted MOCK_CASES, so a// failed request rendered an empty table under stat cards claiming 18 cases.const allCases = casesData?.cases ?? [];- const statCounts = {- all: allCases.length,- open: allCases.filter(c => c.status === 'open').length,- in_progress: allCases.filter(c => c.status === 'in_progress').length,- resolved: allCases.filter(c => c.status === 'resolved').length,- closed: allCases.filter(c => c.status === 'closed').length,- };+ // Substituting `[]` for MOCK_CASES stopped the fabrication but moved the+ // defect: the grid sits above the `isLoading` branch, so five confident+ // zeros rendered on first paint and stayed there when the read failed.+ const countsUnknown = !casesData;+ const statCounts: Record<string, number | null> = countsUnknown+ ? { all: null, open: null, in_progress: null, resolved: null, closed: null }+ : {+ all: allCases.length,+ open: allCases.filter(c => c.status === 'open').length,+ in_progress: allCases.filter(c => c.status === 'in_progress').length,+ resolved: allCases.filter(c => c.status === 'resolved').length,+ closed: allCases.filter(c => c.status === 'closed').length,+ };return (<div className="space-y-5">@@ -234,7 +240,9 @@ export function CasesView({ initialCases }: CasesViewProps = {}) {statusFilter === s ? 'border-blue-500/50 bg-blue-500/5' : 'border-gray-800/60 hover:border-gray-700')}>- <p className="text-2xl font-bold text-gray-100">{statCounts[s]}</p>+ <p className={clsx('text-2xl font-bold', statCounts[s] === null ? 'text-gray-600' : 'text-gray-100')}>+ {statCounts[s] === null ? '—' : statCounts[s]}+ </p><p className="text-xs text-gray-500 mt-0.5 capitalize">{s === 'all' ? 'All Cases' : s.replace('_', ' ')}</p>@@ -298,6 +306,12 @@ export function CasesView({ initialCases }: CasesViewProps = {}) {<div className="flex items-center justify-center h-48"><div className="w-6 h-6 border-2 border-blue-500/30 border-t-blue-500 rounded-full animate-spin" /></div>+ ) : error && !casesData ? (+ <EmptyState+ icon={EmptyStateIcons.case}+ title="Could not load cases"+ description="The case service did not answer. This is not a report that no cases exist — retry, or check the API is reachable."+ />) : cases.length === 0 ? (// WS-F5 — distinguish "filter miss" from "no cases ever". The former// gets a "clear filters" CTA; the latter explains what cases are anddiff --git a/apps/web/src/components/dashboard/FunnelKpiBar.test.tsx b/apps/web/src/components/dashboard/FunnelKpiBar.test.tsxindex 9093d1045..076b70fa0 100644--- a/apps/web/src/components/dashboard/FunnelKpiBar.test.tsx+++ b/apps/web/src/components/dashboard/FunnelKpiBar.test.tsx@@ -81,14 +81,25 @@ const SAMPLE_FUNNEL = {generated_at: '2026-05-13T10:00:00Z',};+/**+ * Shaped like what `services/api/app/api/v1/endpoints/health.py` actually+ * emits, which the previous fixture was not: it gave `ingest` a p95 of 120+ * and `correlate` a p95 of 600, and both are hardcoded `0.0` in the endpoint+ * because neither is instrumented. Grading the component against numbers the+ * backend cannot produce is why `< 1 ms` and `0%` under a "Live" header+ * passed every test here.+ *+ * `unmeasured` is the endpoint's own declaration of which cells are+ * placeholders.+ */const SAMPLE_PIPELINE = {overall_status: 'yellow' as const,stages: [- { stage: 'ingest' as const, backlog: 0, p95_latency_ms: 120, error_rate: 0, status: 'green' as const },- { stage: 'normalize' as const, backlog: 5, p95_latency_ms: 200, error_rate: 0.01, status: 'green' as const },+ { stage: 'ingest' as const, backlog: 0, p95_latency_ms: 0, error_rate: 0, status: 'green' as const, unmeasured: ['p95_latency_ms'] },+ { stage: 'normalize' as const, backlog: 5, p95_latency_ms: 200, error_rate: 0, status: 'green' as const, unmeasured: ['backlog', 'error_rate'] },{ stage: 'fuse' as const, backlog: 42, p95_latency_ms: 1_800, error_rate: 0.03, status: 'yellow' as const },- { stage: 'correlate' as const, backlog: 12, p95_latency_ms: 600, error_rate: 0, status: 'green' as const },- { stage: 'alert' as const, backlog: 3, p95_latency_ms: 300, error_rate: 0, status: 'green' as const },+ { stage: 'correlate' as const, backlog: 12, p95_latency_ms: 0, error_rate: 0, status: 'green' as const, unmeasured: ['p95_latency_ms', 'error_rate'] },+ { stage: 'alert' as const, backlog: 3, p95_latency_ms: 300, error_rate: 0, status: 'green' as const, unmeasured: ['error_rate'] },],generated_at: '2026-05-13T10:00:00Z',};@@ -192,4 +203,56 @@ describe('PipelineHealth', () => {expect(screen.getByText('Pipeline Health')).toBeInTheDocument();expect(screen.getByText('unavailable')).toBeInTheDocument();});++ // `health.py`: "The SOC Console UI renders zeros as 'n/a' pills rather than+ // zero-bars so operators don't read absence as 'all good'." These are that+ // promise, asserted.+ it('renders a cell the endpoint could not measure as n/a, not as a number', () => {+ swrData.set(PIPELINE_KEY, SAMPLE_PIPELINE);+ render(<PipelineHealth />);++ // Four stages declare an unmeasured cell; six cells in total.+ expect(screen.getAllByText('n/a')).toHaveLength(6);+ // The reassuring readings those placeholder zeros used to produce are+ // gone. `ingest.error_rate` really is measured (unhealthy/enabled), so+ // exactly one genuine `0%` remains — an over-eager n/a would be the same+ // defect pointing the other way.+ expect(screen.queryByText('< 1 ms')).not.toBeInTheDocument();+ expect(screen.getAllByText('0%')).toHaveLength(1);+ });++ it('still renders a measured zero as zero', () => {+ swrData.set(PIPELINE_KEY, {+ ...SAMPLE_PIPELINE,+ stages: [{ stage: 'ingest' as const, backlog: 0, p95_latency_ms: 0, error_rate: 0, status: 'green' as const }],+ });+ render(<PipelineHealth />);+ // Nothing declared unmeasured, so a genuine zero must survive: an+ // over-eager n/a would be the same defect pointing the other way.+ expect(screen.getByText('0%')).toBeInTheDocument();+ expect(screen.getByText('< 1 ms')).toBeInTheDocument();+ expect(screen.queryByText('n/a')).not.toBeInTheDocument();+ });++ // FIRST PAINT. The error branch runs before any data arrives, so a header+ // that reads "Live" whenever `error` is falsy asserts liveness before a+ // single byte has been received. This is the case the suite never had.+ it('does not claim Live before the first response arrives', () => {+ swrLoading.add(PIPELINE_KEY);+ render(<PipelineHealth />);+ expect(screen.queryByText('Live')).not.toBeInTheDocument();+ expect(screen.getByText('Loading…')).toBeInTheDocument();+ });++ it('claims Live only once data has arrived', () => {+ swrData.set(PIPELINE_KEY, SAMPLE_PIPELINE);+ render(<PipelineHealth />);+ expect(screen.getByText('Live')).toBeInTheDocument();+ });++ it('marks a stage missing from a successful response rather than loading it forever', () => {+ swrData.set(PIPELINE_KEY, { ...SAMPLE_PIPELINE, stages: SAMPLE_PIPELINE.stages.slice(0, 4) });+ render(<PipelineHealth />);+ expect(screen.getByText('not reported')).toBeInTheDocument();+ });});diff --git a/apps/web/src/components/dashboard/PipelineHealth.tsx b/apps/web/src/components/dashboard/PipelineHealth.tsxindex fe963d940..fdf588d9f 100644--- a/apps/web/src/components/dashboard/PipelineHealth.tsx+++ b/apps/web/src/components/dashboard/PipelineHealth.tsx@@ -81,6 +81,15 @@ function statusStyles(status: Status) {}}+/** The pill an uninstrumented cell gets, so absence never reads as zero. */+function NotMeasured() {+ return (+ <span className="text-gray-500" title="Not instrumented on this stage yet">+ n/a+ </span>+ );+}+function formatLatency(ms: number): string {if (!Number.isFinite(ms) || ms < 0) return '—';if (ms < 1) return '< 1 ms';@@ -104,8 +113,22 @@ function formatErrorRate(ratio: number): string {return `${(ratio * 100).toFixed(2).replace(/\.?0+$/, '')}%`;}+/**+ * `health.py` says of this panel: "The SOC Console UI renders zeros as 'n/a'+ * pills rather than zero-bars so operators don't read absence as 'all good'."+ * It did not. Four of the five stages ship at least one hardcoded `0` for a+ * cell nothing instruments -- ingest and correlate have no p95, normalize,+ * fuse, correlate and alert have no error rate -- and the formatters below+ * turned those into `< 1 ms` and `0%`, under a "Live" header. That is the+ * single most reassuring reading a pipeline panel can offer, for the cells+ * it knows least about.+ *+ * The stage now names its own unmeasured fields, so the backend that knows+ * which ones they are is the thing that says so.+ */function StageCard({ stage }: { stage: PipelineStage }) {const styles = statusStyles(stage.status);+ const unmeasured = new Set(stage.unmeasured ?? []);return (<div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4 min-w-0"><div className="flex items-center justify-between mb-1">@@ -125,19 +148,19 @@ function StageCard({ stage }: { stage: PipelineStage }) {<div className="flex items-baseline justify-between text-xs"><dt className="text-gray-500">Backlog</dt><dd className="font-medium text-gray-200 tabular-nums">- {formatBacklog(stage.backlog)}+ {unmeasured.has('backlog') ? <NotMeasured /> : formatBacklog(stage.backlog)}</dd></div><div className="flex items-baseline justify-between text-xs"><dt className="text-gray-500">p95</dt><dd className="font-medium text-gray-200 tabular-nums">- {formatLatency(stage.p95_latency_ms)}+ {unmeasured.has('p95_latency_ms') ? <NotMeasured /> : formatLatency(stage.p95_latency_ms)}</dd></div><div className="flex items-baseline justify-between text-xs"><dt className="text-gray-500">Errors</dt>- <dd className={clsx('font-medium tabular-nums', styles.text)}>- {formatErrorRate(stage.error_rate)}+ <dd className={clsx('font-medium tabular-nums', unmeasured.has('error_rate') ? 'text-gray-500' : styles.text)}>+ {unmeasured.has('error_rate') ? <NotMeasured /> : formatErrorRate(stage.error_rate)}</dd></div></dl>@@ -166,6 +189,19 @@ function LoadingStage({ stage }: { stage: PipelineStage['stage'] }) {);}+function MissingStage({ stage, reason }: { stage: PipelineStage['stage']; reason: string }) {+ return (+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4 min-w-0">+ <div className="flex items-center justify-between mb-1">+ <p className="text-sm font-semibold text-gray-100 truncate">{STAGE_LABELS[stage]}</p>+ <span className="h-2.5 w-2.5 rounded-full bg-gray-700 ring-2 ring-gray-700/30" role="img" aria-label="status unknown" />+ </div>+ <p className="text-[11px] text-gray-500 truncate">{STAGE_DESCRIPTIONS[stage]}</p>+ <p className="mt-3 text-xs text-gray-500">{reason}</p>+ </div>+ );+}+export function PipelineHealth() {const { data, error, isLoading } = useSWR<PipelineHealthData>('pipeline-health',@@ -195,15 +231,24 @@ export function PipelineHealth() {</div>{error ? (<span className="text-xs text-red-400">unavailable</span>- ) : (+ ) : data ? (<span className="text-xs text-gray-500">Live</span>+ ) : (+ // `Live` was shown whenever `error` was falsy, which includes the+ // whole first-paint window: the header asserted liveness before a+ // single byte had arrived.+ <span className="text-xs text-gray-500">Loading…</span>)}</div><div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">{STAGE_ORDER.map((name) => {const stage = stagesByName[name];- if (isLoading || !stage) return <LoadingStage key={name} stage={name} />;+ if (isLoading) return <LoadingStage key={name} stage={name} />;+ // A stage absent from a *successful* response is not still loading.+ // It used to animate as a skeleton indefinitely, with no error and+ // no timeout, which reads as "nearly there" rather than "missing".+ if (!stage) return <MissingStage key={name} stage={name} reason={error ? 'stage unavailable' : 'not reported'} />;return <StageCard key={name} stage={stage} />;})}</div>diff --git a/apps/web/src/components/detections/DetectionsView.tsx b/apps/web/src/components/detections/DetectionsView.tsxindex 688ae5d1a..b7dc8a595 100644--- a/apps/web/src/components/detections/DetectionsView.tsx+++ b/apps/web/src/components/detections/DetectionsView.tsx@@ -532,6 +532,15 @@ export function DetectionsView() {<Skeleton key={i} className="h-24 w-full" />))}</div>+ ) : error && !useFallback ? (+ // "No detection rules yet" on a failed read tells an operator+ // their coverage is zero and invites them to author one. The+ // ErrorState below is a sibling rather than an alternative, so+ // both used to render — the reassuring one first.+ <EmptyState+ title="Could not load detection rules"+ description="The detection service did not answer. This is not a report that no rules exist."+ />) : filtered.length === 0 ? (rules.length === 0 ? (<EmptyState@@ -618,7 +627,9 @@ export function DetectionsView() {{error && !useFallback && (<ErrorStatetitle="Couldn't load detection rules"- description="The detection service didn't respond. We've shown the local demo set instead."+ // The guard is `!useFallback`, so the demo set was *not* shown.+ // The copy claimed a substitution its own condition rules out.+ description="The detection service didn't respond. Nothing is shown in its place."error={error}onRetry={() => mutate()}/>diff --git a/apps/web/src/components/layout/LiveQueueBadge.tsx b/apps/web/src/components/layout/LiveQueueBadge.tsxindex 7c14a949c..4617e13b5 100644--- a/apps/web/src/components/layout/LiveQueueBadge.tsx+++ b/apps/web/src/components/layout/LiveQueueBadge.tsx@@ -16,7 +16,7 @@ const POLL_INTERVAL_MS = 30_000;* @author Beenu Arora <[email protected]>*/export function LiveQueueBadge() {- const { data } = useSWR<QueueResponse>(+ const { data, error } = useSWR<QueueResponse>(['sidebar:queue:mine'],() => queueApi.list({ owner: 'me', period: 'all', page: 1, page_size: 1 }),{@@ -28,7 +28,27 @@ export function LiveQueueBadge() {},);- const count = data?.counts?.mine ?? 0;+ // `?? 0` then `if (count <= 0) return null` made a failed read+ // indistinguishable from an empty queue: the analyst's sidebar simply+ // showed no pending work. Unknown is its own state.+ const count = data?.counts?.mine ?? null;++ if (count === null) {+ // Hiding on error is the same pixel as an empty queue. A muted dash says+ // the number is unknown without claiming there is nothing to do.+ if (!error) return null;+ return (+ <span+ className="ml-auto inline-flex items-center justify-center min-w-[1.25rem] h-5 px-1.5 rounded-full text-xs font-bold tabular-nums bg-gray-700 text-gray-300"+ role="status"+ aria-label="Queue size unknown — the queue service did not answer"+ title="Queue size unknown — the queue service did not answer"+ data-testid="sidebar-queue-badge-unknown"+ >+ —+ </span>+ );+ }if (count <= 0) {return null;diff --git a/apps/web/src/components/layout/Sidebar.tsx b/apps/web/src/components/layout/Sidebar.tsxindex 704e0f6a1..6000b9dab 100644--- a/apps/web/src/components/layout/Sidebar.tsx+++ b/apps/web/src/components/layout/Sidebar.tsx@@ -421,11 +421,11 @@ export function Sidebar() {</>)}</div>- {/* Live indicator — decorative, status conveyed by the green dot label */}- <div className="ml-auto flex items-center gap-1" aria-hidden="true">- <div className="w-1.5 h-1.5 rounded-full bg-green-400 pulse-dot" />- <span className="text-xs text-fg-subtle">Live</span>- </div>+ {/* No status pill here. There is no data source in this file, so the+ green animated "Live" dot that used to sit beside the product name+ rendered on every page including one whose API was entirely down.+ `LiveFeedPanel` drives the same idea off the realtime socket and+ distinguishes connected-but-silent from receiving. */}</div>{/* Nav */}diff --git a/apps/web/src/components/layout/TenantProvider.test.tsx b/apps/web/src/components/layout/TenantProvider.test.tsxindex 7b087001c..92a58e253 100644--- a/apps/web/src/components/layout/TenantProvider.test.tsx+++ b/apps/web/src/components/layout/TenantProvider.test.tsx@@ -183,7 +183,7 @@ describe('TenantProvider', () => {expect(result.current.available).toHaveLength(1);});- it('tolerates /mssp/children failing for an otherwise-healthy parent', async () => {+ it('tolerates a 403 on /mssp/children for an otherwise-healthy parent', async () => {currentUserMock.mockReturnValue({id: 'u1',email: '[email protected]',@@ -197,7 +197,11 @@ describe('TenantProvider', () => {mssp_role: 'parent',parent_tenant_id: null,});- msspChildrenMock.mockRejectedValue(new Error('403'));+ // An `ApiError`-shaped 403, which is what `msspApi.listChildren` really+ // throws when the caller lacks `mssp:read`. The old fixture was a plain+ // `Error('403')` — a message, not a status — so the test passed on a+ // `catch {}` that also swallowed 500s and network failures.+ msspChildrenMock.mockRejectedValue(Object.assign(new Error('Forbidden'), { name: 'ApiError', status: 403 }));const { result } = renderHook(() => useTenant(), { wrapper });@@ -208,6 +212,22 @@ describe('TenantProvider', () => {expect(result.current.available).toHaveLength(1);});+ it('surfaces a server failure on /mssp/children rather than showing an empty portfolio', async () => {+ // An MSSP parent whose child-tenant endpoint is down must not be shown a+ // switcher that says they manage nobody. That is the reassuring reading+ // of a broken read, and it is indistinguishable from having offboarded+ // every customer.+ currentUserMock.mockReturnValue({ id: 'u1', email: '[email protected]', role: 'mssp-admin', tenant_id: 'parent-t' });+ isAuthenticatedMock.mockReturnValue(true);+ tenantsMeMock.mockResolvedValue({ id: 'parent-t', name: 'MSSP Holdings', mssp_role: 'parent', parent_tenant_id: null });+ msspChildrenMock.mockRejectedValue(Object.assign(new Error('Internal Server Error'), { name: 'ApiError', status: 500 }));++ const { result } = renderHook(() => useTenant(), { wrapper });++ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.error).not.toBeNull();+ });+it('throws when useTenant() is called outside the provider', () => {const err = vi.spyOn(console, 'error').mockImplementation(() => {});expect(() => renderHook(() => useTenant())).toThrow(diff --git a/apps/web/src/components/layout/TenantProvider.tsx b/apps/web/src/components/layout/TenantProvider.tsxindex 66f2629d1..968e19049 100644--- a/apps/web/src/components/layout/TenantProvider.tsx+++ b/apps/web/src/components/layout/TenantProvider.tsx@@ -119,11 +119,17 @@ export function TenantProvider({ children }: { children: ReactNode }) {if (me.mssp_role === 'parent') {try {children = await msspApi.listChildren();- } catch {- // Non-fatal: an MSSP parent without children is valid; a 403 here- // just means the user lacks `mssp:read` and we render the badge- // alone.- children = [];+ } catch (err) {+ // The comment justified only the 403. A bare catch also absorbed+ // 500s and network failures, so an MSSP parent whose child-tenant+ // endpoint was down saw an empty portfolio in the switcher rather+ // than an error — the reassuring reading of a broken read.+ const status = (err as { status?: number } | null)?.status;+ if (status === 403 || status === 404) {+ children = [];+ } else {+ throw err;+ }}}if (cancelled) return;diff --git a/apps/web/src/components/threat-intel/ThreatIntelView.tsx b/apps/web/src/components/threat-intel/ThreatIntelView.tsxindex 3433b3b09..1ec230cd4 100644--- a/apps/web/src/components/threat-intel/ThreatIntelView.tsx+++ b/apps/web/src/components/threat-intel/ThreatIntelView.tsx@@ -249,12 +249,19 @@ export function ThreatIntelView() {const [typeFilter, setTypeFilter] = useState<ThreatIndicator['type'] | 'all'>('all');const [search, setSearch] = useState('');- const { data } = useSWR(+ const { data, error, isLoading } = useSWR('threat-intel-indicators',() => threatIntelApi.list(),{ fallbackData: demoFallback({ indicators: MOCK_INDICATORS, total: MOCK_INDICATORS.length }) },);+ // `data` is undefined on first paint and on error alike, and both prior+ // fixes on these lines were about fabricated values rather than about+ // absence. `?? []` then published "Malicious (of shown): 0" — a security+ // verdict — and an empty state telling the operator to go connect a feed,+ // on a store the page could not reach.+ const storeUnknown = !data;+// Not `?? MOCK_INDICATORS`. `fallbackData` above already withholds the// sample set outside the hosted demo; repeating the constant here put it// back, so a 404 from the indicators API rendered five invented IOCs and a@@ -313,8 +320,10 @@ export function ThreatIntelView() {{ label: 'High confidence (of shown)', value: allIndicators.filter(i => i.confidence >= 80).length, color: 'text-orange-400' },].map((stat) => (<div key={stat.label} className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4">- <p className={clsx('text-2xl font-bold mb-1', stat.color)}>{stat.value}</p>- <p className="text-xs text-gray-500">{stat.label}</p>+ <p className={clsx('text-2xl font-bold mb-1', storeUnknown ? 'text-gray-600' : stat.color)}>+ {storeUnknown ? '—' : stat.value}+ </p>+ <p className="text-xs text-gray-500">{storeUnknown ? 'not measured' : stat.label}</p></div>))}</div>@@ -391,8 +400,14 @@ export function ThreatIntelView() {) : (<EmptyStateicon={EmptyStateIcons.shield}- title="No threat intel ingested yet"- description="Connect a TI feed (MISP, OTX, AbuseIPDB, GreyNoise, internal STIX/TAXII) from Settings → Connectors to start enriching alerts with reputation context."+ title={storeUnknown ? (isLoading ? 'Loading threat intel…' : 'Threat intel store unreachable') : 'No threat intel ingested yet'}+ description={+ storeUnknown+ ? isLoading+ ? 'Reading indicators from the threat-intel service.'+ : `The threat-intel service did not answer${error ? '' : ''}. This is not a report that no indicators exist.`+ : 'Connect a TI feed (MISP, OTX, AbuseIPDB, GreyNoise, internal STIX/TAXII) from Settings → Connectors to start enriching alerts with reputation context.'+ }className="bg-transparent py-8"/>)diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex a8a1b8ffc..27dbc2223 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -2106,6 +2106,14 @@ export interface PipelineStage {p95_latency_ms: number;error_rate: number;status: 'unknown' | 'green' | 'yellow' | 'red';+ /**+ * Numeric fields above that this stage could not measure. They still carry+ * `0` on the wire; render them as `n/a`, never as a value. Optional because+ * an older API will not send it -- treat absent as "nothing declared",+ * which is the pre-existing behaviour rather than a silent claim of+ * full instrumentation.+ */+ unmeasured?: string[];}export interface PipelineHealth {diff --git a/apps/web/src/lib/replay.test.ts b/apps/web/src/lib/replay.test.tsindex a4a4586b5..8927688a8 100644--- a/apps/web/src/lib/replay.test.ts+++ b/apps/web/src/lib/replay.test.ts@@ -15,23 +15,39 @@ describe("fetchPublicReplay", () => {vi.fn(async () => new Response(JSON.stringify(payload), { status: 200, headers: { "content-type": "application/json" } })),);const result = await fetchPublicReplay("abc123def456");- expect(result?.slug).toBe("abc123def456");- expect(result?.snapshot.stepCount).toBe(3);+ expect(result.kind).toBe("ok");+ if (result.kind !== "ok") return;+ expect(result.replay.slug).toBe("abc123def456");+ expect(result.replay.snapshot.stepCount).toBe(3);});- it("returns null on 404", async () => {+ it("reports a 404 as missing", async () => {vi.stubGlobal("fetch", vi.fn(async () => new Response("nope", { status: 404 })));- expect(await fetchPublicReplay("missing")).toBeNull();+ expect((await fetchPublicReplay("missing")).kind).toBe("missing");});- it("returns null on network error (never throws)", async () => {+ // These four used to assert `toBeNull()`, the same answer a 404 gave, and+ // the page turns that into "404 · page not found". An operator whose API+ // was down was told their replay link was wrong.+ it.each([500, 502, 503, 401])("reports HTTP %i as unavailable, not missing", async (status) => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response("boom", { status })));+ const result = await fetchPublicReplay("x");+ expect(result).toEqual({ kind: "unavailable", status });+ });++ it("reports a network error as unavailable (and never throws)", async () => {vi.stubGlobal("fetch",vi.fn(async () => {throw new Error("boom");}),);- expect(await fetchPublicReplay("x")).toBeNull();+ expect(await fetchPublicReplay("x")).toEqual({ kind: "unavailable", status: null });+ });++ it("reports an unparseable 200 body as unavailable", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response("<html>gateway</html>", { status: 200 })));+ expect((await fetchPublicReplay("x")).kind).toBe("unavailable");});it("URL-encodes the slug", async () => {diff --git a/apps/web/src/lib/replay.ts b/apps/web/src/lib/replay.tsindex f4b1b2513..cb4c5043b 100644--- a/apps/web/src/lib/replay.ts+++ b/apps/web/src/lib/replay.ts@@ -75,16 +75,34 @@ function apiBase(): string {).replace(/\/$/, "");}-/** Server-side fetch of a published replay. Returns null on 404 / error. */-export async function fetchPublicReplay(slug: string): Promise<PublicReplay | null> {+/**+ * "This replay does not exist" and "we could not reach the API" are different+ * answers, and the page renders a different page for each. Collapsing both+ * into `null` meant a 500, a 502 or a DNS failure reached `notFound()`, so an+ * operator whose API was down was told their link was wrong.+ */+export type PublicReplayResult =+ | { kind: "ok"; replay: PublicReplay }+ | { kind: "missing" }+ | { kind: "unavailable"; status: number | null };++/** Server-side fetch of a published replay. */+export async function fetchPublicReplay(slug: string): Promise<PublicReplayResult> {+ let res: Response;try {- const res = await fetch(`${apiBase()}/api/v1/r/${encodeURIComponent(slug)}`, {+ res = await fetch(`${apiBase()}/api/v1/r/${encodeURIComponent(slug)}`, {// Public, cacheable content; revalidate periodically at the edge.next: { revalidate: 300 },});- if (!res.ok) return null;- return (await res.json()) as PublicReplay;} catch {- return null;+ // No response at all: DNS failure, connection refused, timeout.+ return { kind: "unavailable", status: null };+ }+ if (res.status === 404 || res.status === 410) return { kind: "missing" };+ if (!res.ok) return { kind: "unavailable", status: res.status };+ try {+ return { kind: "ok", replay: (await res.json()) as PublicReplay };+ } catch {+ return { kind: "unavailable", status: res.status };}}diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 3361d9148..99d08e694 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -27498,6 +27498,11 @@ components:status:type: stringtitle: Status+ unmeasured:+ items:+ type: string+ type: array+ title: Unmeasuredtype: objectrequired:- stagediff --git a/services/api/app/api/v1/endpoints/health.py b/services/api/app/api/v1/endpoints/health.pyindex 73e1cf24b..65a6f45cf 100644--- a/services/api/app/api/v1/endpoints/health.py+++ b/services/api/app/api/v1/endpoints/health.py@@ -179,6 +179,7 @@ async def _ingest_stage(db, tenant_id, *, now: datetime) -> PipelineStage:p95_latency_ms=0.0,error_rate=0.0,status="unknown",+ unmeasured=["backlog", "p95_latency_ms", "error_rate"],)statuses: list[str] = []@@ -209,6 +210,7 @@ async def _ingest_stage(db, tenant_id, *, now: datetime) -> PipelineStage:p95_latency_ms=0.0,error_rate=error_rate,status=_worst_status(statuses),+ unmeasured=["p95_latency_ms"],)@@ -248,6 +250,7 @@ async def _normalize_stage(p95_latency_ms=0.0,error_rate=0.0,status="unknown",+ unmeasured=["backlog", "p95_latency_ms", "error_rate"],)p95_seconds = max(0.0, float(p95_seconds))@@ -256,6 +259,7 @@ async def _normalize_stage(backlog=0,p95_latency_ms=round(p95_seconds * 1000.0, 2),error_rate=0.0,+ unmeasured=["backlog", "error_rate"],status=_status_from_latency(p95_seconds=p95_seconds,warn_seconds=warn_seconds,@@ -301,6 +305,7 @@ async def _fuse_stage(p95_latency_ms=0.0,error_rate=0.0,status="unknown",+ unmeasured=["backlog", "p95_latency_ms", "error_rate"],)p95_seconds = max(0.0, float(p95_seconds))@@ -309,6 +314,7 @@ async def _fuse_stage(backlog=0,p95_latency_ms=round(p95_seconds * 1000.0, 2),error_rate=0.0,+ unmeasured=["backlog", "error_rate"],status=_status_from_latency(p95_seconds=p95_seconds,warn_seconds=warn_seconds,@@ -377,6 +383,7 @@ async def _correlate_stage(p95_latency_ms=0.0,error_rate=0.0,status=status,+ unmeasured=["p95_latency_ms", "error_rate"],)@@ -444,6 +451,7 @@ async def _alert_stage(p95_latency_ms=latency_ms,error_rate=0.0,status=status,+ unmeasured=["error_rate"],)diff --git a/services/api/app/api/v1/endpoints/metrics.py b/services/api/app/api/v1/endpoints/metrics.pyindex b2f151ffa..17be7ff11 100644--- a/services/api/app/api/v1/endpoints/metrics.py+++ b/services/api/app/api/v1/endpoints/metrics.py@@ -27,7 +27,7 @@ import loggingfrom datetime import UTC, datetime, timedeltafrom fastapi import APIRouter, Query-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom sqlalchemy import and_, func, select, textfrom app.api.v1.deps import AuthUser, DBSession@@ -217,6 +217,14 @@ class PipelineStage(BaseModel):p95_latency_ms: floaterror_rate: floatstatus: str+ #: Names of the numeric fields above this stage could not measure. Those+ #: fields still carry ``0`` for compatibility, and ``0`` is the most+ #: reassuring number a pipeline panel can show — an operator reads+ #: "0 backlog, <1 ms, 0% errors" as healthy, not as uninstrumented. The+ #: console renders anything named here as "n/a" instead. Four of the five+ #: stages have at least one such field, so without this the strip was+ #: mostly confident zeros about things nothing measures.+ unmeasured: list[str] = Field(default_factory=list)class PipelineHealth(BaseModel):diff --git a/services/api/tests/test_funnel_and_pipeline.py b/services/api/tests/test_funnel_and_pipeline.pyindex f2d31509f..dbccb8fb4 100644--- a/services/api/tests/test_funnel_and_pipeline.py+++ b/services/api/tests/test_funnel_and_pipeline.py@@ -1000,3 +1000,66 @@ class TestGetPipelineHealth:):payload = await get_pipeline_health(user=_user(), db=MagicMock())assert payload.overall_status == "red"+++class TestEveryPlaceholderZeroDeclaresItself:+ """A stage that hardcodes a metric must name it in ``unmeasured``.++ This module's docstring promises "The SOC Console UI renders zeros as+ 'n/a' pills rather than zero-bars so operators don't read absence as+ 'all good'". The console had no way to honour that: an uninstrumented+ cell and a measured zero arrived on the wire as the same ``0``, and+ four of the five stages carry at least one. The panel therefore showed+ ``0 backlog / < 1 ms / 0% errors`` under a "Live" header for the cells+ it knew least about.++ Asserted by reading the source for a hardcoded literal rather than by+ calling each builder, because the question is about the *constant in+ the code* — a builder driven by a mock could return a real zero and+ prove nothing either way. The direction that matters is: a literal that+ is not declared fails. Adding instrumentation and dropping the literal+ passes, which is the change that should pass.+ """++ #: Field name → the literal that means "not measured here".+ PLACEHOLDERS = {"backlog": "backlog=0,", "p95_latency_ms": "p95_latency_ms=0.0,", "error_rate": "error_rate=0.0,"}++ def _constructions(self) -> list[tuple[int, str]]:+ import pathlib+ import re++ source = (pathlib.Path(__file__).resolve().parents[1] / "app" / "api" / "v1" / "endpoints" / "health.py").read_text()+ out: list[tuple[int, str]] = []+ for match in re.finditer(r"PipelineStage\((.*?)\n\s*\)", source, re.S):+ out.append((source[: match.start()].count("\n") + 1, match.group(1)))+ return out++ def test_the_endpoint_still_constructs_stages_here(self) -> None:+ """A rename would otherwise make the next test vacuously true."""+ assert len(self._constructions()) >= 5, "found no PipelineStage constructions; this gate is reading the wrong file"++ def test_a_hardcoded_metric_is_declared_unmeasured(self) -> None:+ offenders: list[str] = []+ for lineno, body in self._constructions():+ declared = body[body.index("unmeasured=") :] if "unmeasured=" in body else ""+ for field, literal in self.PLACEHOLDERS.items():+ if literal in body and field not in declared:+ offenders.append(f"health.py:{lineno} hardcodes {literal.rstrip(',')} without declaring it unmeasured")+ assert not offenders, "a placeholder zero renders as a measurement:\n " + "\n ".join(offenders)++ @pytest.mark.asyncio+ async def test_a_tenant_with_no_connectors_measures_nothing_and_says_so(self) -> None:+ from app.api.v1.endpoints.health import _ingest_stage++ db = MagicMock()+ db.execute = AsyncMock(return_value=MagicMock(all=MagicMock(return_value=[])))++ stage = await _ingest_stage(db, uuid.uuid4(), now=datetime.now(UTC))++ assert stage.status == "unknown"+ assert set(stage.unmeasured) == {"backlog", "p95_latency_ms", "error_rate"}++ def test_the_default_is_empty_so_an_omission_is_never_a_silent_claim(self) -> None:+ from app.api.v1.endpoints.metrics import PipelineStage++ assert PipelineStage(stage="x", backlog=1, p95_latency_ms=2.0, error_rate=0.5, status="green").unmeasured == []