Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(a11y): axe covers the case workspace, and four real defects are fixed

Beenu Arora81b2e0b1a818
diff --git a/apps/web/src/components/cases/CaseWorkspace.tsx b/apps/web/src/components/cases/CaseWorkspace.tsx
index 633bf41e4..f775154e2 100644
--- a/apps/web/src/components/cases/CaseWorkspace.tsx
+++ b/apps/web/src/components/cases/CaseWorkspace.tsx
@@ -1,4 +1,4 @@
-'use client';
+"use client";
/**
* Case workspace.
@@ -17,36 +17,44 @@
* a fabricated incident on screen under the id the analyst had opened.
*/
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import Link from 'next/link';
-import { useSearchParams } from 'next/navigation';
-import useSWR from 'swr';
-import { clsx } from 'clsx';
-import { format, formatDistanceToNow } from 'date-fns';
-import toast from 'react-hot-toast';
-import { apiFetch, type AttackChainTimeline, type AttackChainWindow, type Case, type CaseAttackPath, casesApi, type CaseSeverity, type CaseStatus, type CaseTask, type CaseTimelineEvent, graphApi, realtimeApi } from '@/lib/api';
-import { Skeleton } from '@/components/ui/Skeleton';
-import { ErrorState } from '@/components/ui/ErrorState';
-import { EmptyState } from '@/components/ui/EmptyState';
-import { InvestigationLedger } from './InvestigationLedger';
-import { ContextualActions } from '@/components/copilot/ContextualActions';
-import { canUseDemoData } from '@/lib/demoFallback';
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import Link from "next/link";
+import { useSearchParams } from "next/navigation";
+import useSWR from "swr";
+import { clsx } from "clsx";
+import { format, formatDistanceToNow } from "date-fns";
+import toast from "react-hot-toast";
+import {
+ apiFetch,
+ type AttackChainTimeline,
+ type AttackChainWindow,
+ type Case,
+ type CaseAttackPath,
+ casesApi,
+ type CaseSeverity,
+ type CaseStatus,
+ type CaseTask,
+ type CaseTimelineEvent,
+ graphApi,
+ realtimeApi,
+} from "@/lib/api";
+import { Skeleton } from "@/components/ui/Skeleton";
+import { ErrorState } from "@/components/ui/ErrorState";
+import { EmptyState } from "@/components/ui/EmptyState";
+import { InvestigationLedger } from "./InvestigationLedger";
+import { ContextualActions } from "@/components/copilot/ContextualActions";
+import { canUseDemoData } from "@/lib/demoFallback";
type WorkspaceTab =
- | 'overview'
- | 'investigation'
- | 'attack-path'
- | 'attack-chain'
- | 'ledger'
- | 'report';
+ "overview" | "investigation" | "attack-path" | "attack-chain" | "ledger" | "report";
const VALID_TABS: readonly WorkspaceTab[] = [
- 'overview',
- 'investigation',
- 'attack-path',
- 'attack-chain',
- 'ledger',
- 'report',
+ "overview",
+ "investigation",
+ "attack-path",
+ "attack-chain",
+ "ledger",
+ "report",
];
function isWorkspaceTab(value: string | null): value is WorkspaceTab {
@@ -56,88 +64,88 @@ function isWorkspaceTab(value: string | null): value is WorkspaceTab {
// ─── Demo case ────────────────────────────────────────────────────────────────
function buildDemoCase(id: string): Case {
- const now = new Date('2026-05-06T12:00:00Z').getTime();
+ const now = new Date("2026-05-06T12:00:00Z").getTime();
return {
id,
- title: 'Suspected lateral movement from finance subnet',
+ title: "Suspected lateral movement from finance subnet",
description:
"Multiple high-severity alerts indicate an attacker pivoted from " +
"WIN-FIN-DB01 to BACKUP-SRV-12 using compromised service account credentials. " +
"Behavior consistent with T1021.002 (SMB/Windows Admin Shares).",
- status: 'investigating',
- severity: 'critical',
- assignee: '[email protected]',
- alertIds: ['alert-9012', 'alert-9013', 'alert-9019', 'alert-9024'],
+ status: "investigating",
+ severity: "critical",
+ assignee: "[email protected]",
+ alertIds: ["alert-9012", "alert-9013", "alert-9019", "alert-9024"],
alertCount: 4,
- tags: ['lateral-movement', 'credential-access', 'finance-subnet'],
- mitre: ['T1021.002', 'T1078', 'T1003.001'],
- createdBy: 'system',
+ tags: ["lateral-movement", "credential-access", "finance-subnet"],
+ mitre: ["T1021.002", "T1078", "T1003.001"],
+ createdBy: "system",
createdAt: new Date(now - 6 * 60 * 60 * 1000).toISOString(),
updatedAt: new Date(now - 12 * 60 * 1000).toISOString(),
dueAt: new Date(now + 18 * 60 * 60 * 1000).toISOString(),
timeline: [
{
- id: 'tl-1',
- type: 'created',
+ id: "tl-1",
+ type: "created",
timestamp: new Date(now - 6 * 60 * 60 * 1000).toISOString(),
- title: 'Case created from correlation rule',
- actor: 'system',
+ title: "Case created from correlation rule",
+ actor: "system",
description:
'Rule "Lateral movement from privileged subnet" matched 3 alerts within 4 minutes.',
},
{
- id: 'tl-2',
- type: 'assigned',
+ id: "tl-2",
+ type: "assigned",
timestamp: new Date(now - 5 * 60 * 60 * 1000).toISOString(),
- title: 'Assigned to Sasha Lin',
- actor: 'andre.k',
+ title: "Assigned to Sasha Lin",
+ actor: "andre.k",
},
{
- id: 'tl-3',
- type: 'agent',
+ id: "tl-3",
+ type: "agent",
timestamp: new Date(now - 4 * 60 * 60 * 1000).toISOString(),
- title: 'Auto-investigation completed',
- actor: 'aisoc-agent',
+ title: "Auto-investigation completed",
+ actor: "aisoc-agent",
description:
- 'Confirmed pivot via SMB. Recommend isolating WIN-FIN-DB01 and rotating service account creds.',
+ "Confirmed pivot via SMB. Recommend isolating WIN-FIN-DB01 and rotating service account creds.",
},
{
- id: 'tl-4',
- type: 'note',
+ id: "tl-4",
+ type: "note",
timestamp: new Date(now - 90 * 60 * 1000).toISOString(),
- title: 'Note added',
- actor: 'sasha.lin',
+ title: "Note added",
+ actor: "sasha.lin",
description:
- 'IT confirmed the service account belongs to the legacy backup tool. ' +
- 'Proceeding to rotate creds and revoke session.',
+ "IT confirmed the service account belongs to the legacy backup tool. " +
+ "Proceeding to rotate creds and revoke session.",
},
{
- id: 'tl-5',
- type: 'status',
+ id: "tl-5",
+ type: "status",
timestamp: new Date(now - 12 * 60 * 1000).toISOString(),
- title: 'Status changed to In progress',
- actor: 'sasha.lin',
+ title: "Status changed to In progress",
+ actor: "sasha.lin",
},
],
tasks: [
{
- id: 'task-1',
- title: 'Isolate WIN-FIN-DB01 from network',
- status: 'done',
- assignee: 'andre.k',
+ id: "task-1",
+ title: "Isolate WIN-FIN-DB01 from network",
+ status: "done",
+ assignee: "andre.k",
createdAt: new Date(now - 3 * 60 * 60 * 1000).toISOString(),
},
{
- id: 'task-2',
- title: 'Rotate svc_backup credentials',
- status: 'in_progress',
- assignee: 'sasha.lin',
+ id: "task-2",
+ title: "Rotate svc_backup credentials",
+ status: "in_progress",
+ assignee: "sasha.lin",
createdAt: new Date(now - 2 * 60 * 60 * 1000).toISOString(),
},
{
- id: 'task-3',
- title: 'Forensic image of BACKUP-SRV-12',
- status: 'todo',
+ id: "task-3",
+ title: "Forensic image of BACKUP-SRV-12",
+ status: "todo",
createdAt: new Date(now - 60 * 60 * 1000).toISOString(),
},
],
@@ -147,10 +155,10 @@ function buildDemoCase(id: string): Case {
// ─── Style maps ───────────────────────────────────────────────────────────────
const SEVERITY_BADGE: Record<CaseSeverity, string> = {
- critical: 'bg-red-500/15 text-red-300 ring-red-500/30',
- high: 'bg-orange-500/15 text-orange-300 ring-orange-500/30',
- medium: 'bg-yellow-500/15 text-yellow-300 ring-yellow-500/30',
- low: 'bg-blue-500/15 text-blue-300 ring-blue-500/30',
+ critical: "bg-red-500/15 text-red-300 ring-red-500/30",
+ high: "bg-orange-500/15 text-orange-300 ring-orange-500/30",
+ medium: "bg-yellow-500/15 text-yellow-300 ring-yellow-500/30",
+ low: "bg-blue-500/15 text-blue-300 ring-blue-500/30",
};
// Keyed on the six states the database actually permits. These used to name
@@ -160,37 +168,37 @@ const SEVERITY_BADGE: Record<CaseSeverity, string> = {
// label and had no dot colour, while `Record<CaseStatus, …>` called the maps
// exhaustive because the union was wrong in the same direction.
const STATUS_LABEL: Record<CaseStatus, string> = {
- new: 'New',
- triaged: 'Triaged',
- investigating: 'Investigating',
- contained: 'Contained',
- resolved: 'Resolved',
- closed: 'Closed',
+ new: "New",
+ triaged: "Triaged",
+ investigating: "Investigating",
+ contained: "Contained",
+ resolved: "Resolved",
+ closed: "Closed",
};
const STATUS_DOT: Record<CaseStatus, string> = {
- new: 'bg-slate-400',
- triaged: 'bg-sky-400',
- investigating: 'bg-blue-400 animate-pulse',
- contained: 'bg-amber-400',
- resolved: 'bg-emerald-400',
- closed: 'bg-slate-600',
+ new: "bg-slate-400",
+ triaged: "bg-sky-400",
+ investigating: "bg-blue-400 animate-pulse",
+ contained: "bg-amber-400",
+ resolved: "bg-emerald-400",
+ closed: "bg-slate-600",
};
-const TASK_STATUS_BADGE: Record<CaseTask['status'], string> = {
- todo: 'bg-slate-500/15 text-slate-300 ring-slate-500/30',
- in_progress: 'bg-blue-500/15 text-blue-300 ring-blue-500/30',
- done: 'bg-emerald-500/15 text-emerald-300 ring-emerald-500/30',
+const TASK_STATUS_BADGE: Record<CaseTask["status"], string> = {
+ todo: "bg-slate-500/15 text-slate-300 ring-slate-500/30",
+ in_progress: "bg-blue-500/15 text-blue-300 ring-blue-500/30",
+ done: "bg-emerald-500/15 text-emerald-300 ring-emerald-500/30",
};
const TIMELINE_ICON: Record<string, string> = {
- created: 'new',
- assigned: 'asn',
- status: 'sts',
- note: 'note',
- agent: 'ai',
- comment: 'cmt',
- alert: 'alrt',
+ created: "new",
+ assigned: "asn",
+ status: "sts",
+ note: "note",
+ agent: "ai",
+ comment: "cmt",
+ alert: "alrt",
};
// ─── Sub-components ───────────────────────────────────────────────────────────
@@ -198,7 +206,7 @@ const TIMELINE_ICON: Record<string, string> = {
function StatusPill({ status }: { status: CaseStatus }) {
return (
<span className="inline-flex items-center gap-1.5 rounded-full border border-slate-700/70 bg-slate-800/40 px-2 py-0.5 text-xs font-medium text-slate-200">
- <span className={clsx('h-1.5 w-1.5 rounded-full', STATUS_DOT[status])} />
+ <span className={clsx("h-1.5 w-1.5 rounded-full", STATUS_DOT[status])} />
{STATUS_LABEL[status]}
</span>
);
@@ -207,7 +215,7 @@ function StatusPill({ status }: { status: CaseStatus }) {
function MitreChip({ id }: { id: string }) {
return (
<a
- href={`https://attack.mitre.org/techniques/${id.replace('.', '/')}/`}
+ href={`https://attack.mitre.org/techniques/${id.replace(".", "/")}/`}
target="_blank"
rel="noreferrer"
className="rounded-full border border-orange-500/30 bg-orange-500/10 px-2 py-0.5 text-[11px] font-medium text-orange-300 transition-colors hover:bg-orange-500/20"
@@ -218,7 +226,7 @@ function MitreChip({ id }: { id: string }) {
}
function TimelineItem({ event }: { event: CaseTimelineEvent }) {
- const icon = TIMELINE_ICON[event.type] ?? '·';
+ const icon = TIMELINE_ICON[event.type] ?? "·";
return (
<li className="relative pl-10">
<span className="absolute left-0 top-1 flex h-7 w-7 items-center justify-center rounded-full border border-slate-700/70 bg-slate-900 text-[10px] font-medium uppercase tracking-wide text-slate-400">
@@ -227,16 +235,12 @@ function TimelineItem({ event }: { event: CaseTimelineEvent }) {
<div className="rounded-lg border border-slate-800/60 bg-slate-900/40 p-3">
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
<p className="text-sm font-medium text-slate-100">{event.title}</p>
- {event.actor && (
- <span className="text-[11px] text-slate-500">by {event.actor}</span>
- )}
+ {event.actor && <span className="text-[11px] text-slate-500">by {event.actor}</span>}
<span className="ml-auto text-[11px] text-slate-500" suppressHydrationWarning>
{formatDistanceToNow(new Date(event.timestamp), { addSuffix: true })}
</span>
</div>
- {event.description && (
- <p className="mt-1.5 text-xs text-slate-400">{event.description}</p>
- )}
+ {event.description && <p className="mt-1.5 text-xs text-slate-400">{event.description}</p>}
</div>
</li>
);
@@ -244,41 +248,35 @@ function TimelineItem({ event }: { event: CaseTimelineEvent }) {
interface TaskRowProps {
task: CaseTask;
- onChangeStatus: (status: CaseTask['status']) => void;
+ onChangeStatus: (status: CaseTask["status"]) => void;
}
function TaskRow({ task, onChangeStatus }: TaskRowProps) {
- const next: CaseTask['status'] =
- task.status === 'todo'
- ? 'in_progress'
- : task.status === 'in_progress'
- ? 'done'
- : 'todo';
+ const next: CaseTask["status"] =
+ task.status === "todo" ? "in_progress" : task.status === "in_progress" ? "done" : "todo";
return (
<li className="flex items-start gap-2 rounded-lg border border-slate-800/60 bg-slate-900/40 px-3 py-2">
<button
onClick={() => onChangeStatus(next)}
className={clsx(
- 'mt-0.5 flex h-5 w-5 flex-none items-center justify-center rounded border text-[11px] transition-colors',
- task.status === 'done'
- ? 'border-emerald-500/40 bg-emerald-500/15 text-emerald-300'
- : task.status === 'in_progress'
- ? 'border-blue-500/40 bg-blue-500/15 text-blue-300'
- : 'border-slate-600 text-slate-500 hover:border-slate-400',
+ "mt-0.5 flex h-5 w-5 flex-none items-center justify-center rounded border text-[11px] transition-colors",
+ task.status === "done"
+ ? "border-emerald-500/40 bg-emerald-500/15 text-emerald-300"
+ : task.status === "in_progress"
+ ? "border-blue-500/40 bg-blue-500/15 text-blue-300"
+ : "border-slate-600 text-slate-500 hover:border-slate-400"
)}
aria-label={`Mark task ${next}`}
title={`Move to ${next}`}
>
- {task.status === 'done' ? '✓' : task.status === 'in_progress' ? '·' : ''}
+ {task.status === "done" ? "✓" : task.status === "in_progress" ? "·" : ""}
</button>
<div className="min-w-0 flex-1">
<p
className={clsx(
- 'text-sm',
- task.status === 'done'
- ? 'text-slate-500 line-through'
- : 'text-slate-100',
+ "text-sm",
+ task.status === "done" ? "text-slate-500 line-through" : "text-slate-100"
)}
>
{task.title}
@@ -286,11 +284,11 @@ function TaskRow({ task, onChangeStatus }: TaskRowProps) {
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 text-[11px] text-slate-500">
<span
className={clsx(
- 'inline-flex items-center rounded px-1.5 py-0.5 ring-1',
- TASK_STATUS_BADGE[task.status],
+ "inline-flex items-center rounded px-1.5 py-0.5 ring-1",
+ TASK_STATUS_BADGE[task.status]
)}
>
- {task.status.replace('_', ' ')}
+ {task.status.replace("_", " ")}
</span>
{task.assignee && <span>@{task.assignee}</span>}
<span suppressHydrationWarning>
@@ -311,14 +309,14 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
// to the overview when the param is missing or unrecognized.
const searchParams = useSearchParams();
const initialTab: WorkspaceTab = useMemo(() => {
- const t = searchParams?.get('tab') ?? null;
- return isWorkspaceTab(t) ? t : 'overview';
+ const t = searchParams?.get("tab") ?? null;
+ return isWorkspaceTab(t) ? t : "overview";
}, [searchParams]);
const [activeTab, setActiveTab] = useState<WorkspaceTab>(initialTab);
const { data, error, isLoading, mutate } = useSWR<Case>(
- ['case', caseId],
+ ["case", caseId],
() => casesApi.get(caseId),
- { revalidateOnFocus: false, shouldRetryOnError: false },
+ { revalidateOnFocus: false, shouldRetryOnError: false }
);
// `buildDemoCase(caseId)` takes its id from the route param, so an ungated
@@ -338,10 +336,12 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
const [investigating, setInvestigating] = useState(false);
const [investigationRunId, setInvestigationRunId] = useState<string | null>(null);
- const [investigationStatus, setInvestigationStatus] = useState<string>('idle');
+ const [investigationStatus, setInvestigationStatus] = useState<string>("idle");
const [investigationData, setInvestigationData] = useState<Record<string, unknown> | null>(null);
- const [reportMd, setReportMd] = useState<string>('');
- const [liveSteps, setLiveSteps] = useState<Array<{ kind: string; agent: string; summary: string; ts: string }>>([]);
+ const [reportMd, setReportMd] = useState<string>("");
+ const [liveSteps, setLiveSteps] = useState<
+ Array<{ kind: string; agent: string; summary: string; ts: string }>
+ >([]);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const wsRef = useRef<WebSocket | null>(null);
@@ -359,17 +359,30 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
}
}, []);
- useEffect(() => () => { stopPolling(); closeWs(); }, [stopPolling, closeWs]);
+ useEffect(
+ () => () => {
+ stopPolling();
+ closeWs();
+ },
+ [stopPolling, closeWs]
+ );
// The case detail payload carries no timeline; the dedicated
// /cases/{id}/timeline endpoint synthesises opened/status/investigation
// events. Fetch it so the Overview timeline is never blank by silence.
useEffect(() => {
let cancelled = false;
- casesApi.getTimeline(caseId).then((res) => {
- if (!cancelled && Array.isArray(res?.events)) setFetchedTimeline(res.events);
- }).catch(() => { /* overview falls back to inline timeline */ });
- return () => { cancelled = true; };
+ casesApi
+ .getTimeline(caseId)
+ .then((res) => {
+ if (!cancelled && Array.isArray(res?.events)) setFetchedTimeline(res.events);
+ })
+ .catch(() => {
+ /* overview falls back to inline timeline */
+ });
+ return () => {
+ cancelled = true;
+ };
}, [caseId]);
// Restore the latest terminal run on mount — run state lives only in
@@ -385,7 +398,8 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
const body = (await resp.json()) as { runs?: Array<Record<string, unknown>> };
const runs = body.runs ?? [];
const latest = runs.find(
- (r) => typeof r?.run_id === "string" && (r.status === "completed" || r.status === "failed"),
+ (r) =>
+ typeof r?.run_id === "string" && (r.status === "completed" || r.status === "failed")
);
if (!latest || cancelled) return;
const runId = String(latest.run_id);
@@ -408,93 +422,107 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
/* best-effort restore; tab falls back to its idle prompt */
}
})();
- return () => { cancelled = true; };
+ return () => {
+ cancelled = true;
+ };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [caseId]);
/** Connect to the realtime service WebSocket for this run_id */
- const connectWs = useCallback((runId: string) => {
- closeWs();
- // Mint a short-lived ticket and attach it as `?token=` before opening the
- // socket (Issue #239). The realtime service rejects tokenless upgrades and
- // derives the tenant from the verified claim, so we no longer send a
- // client-chosen `tenant_id`. On failure (signed-out / ticketing not
- // configured) we silently fall back to the polling loop already running.
- void (async () => {
- let token: string;
- try {
- ({ token } = await realtimeApi.ticket());
- } catch {
- // Could not authenticate — polling fallback covers live updates.
- return;
- }
- const wsProto = window.location.protocol === 'https:' ? 'wss' : 'ws';
- // The Next.js dev server proxies /ws → realtime service on :8086.
- // In production, nginx handles the proxy.
- const wsUrl = `${wsProto}://${window.location.host}/ws/agents?token=${encodeURIComponent(token)}`;
- try {
- const ws = new WebSocket(wsUrl);
- wsRef.current = ws;
- ws.onmessage = (evt) => {
+ const connectWs = useCallback(
+ (runId: string) => {
+ closeWs();
+ // Mint a short-lived ticket and attach it as `?token=` before opening the
+ // socket (Issue #239). The realtime service rejects tokenless upgrades and
+ // derives the tenant from the verified claim, so we no longer send a
+ // client-chosen `tenant_id`. On failure (signed-out / ticketing not
+ // configured) we silently fall back to the polling loop already running.
+ void (async () => {
+ let token: string;
+ try {
+ ({ token } = await realtimeApi.ticket());
+ } catch {
+ // Could not authenticate — polling fallback covers live updates.
+ return;
+ }
+ const wsProto = window.location.protocol === "https:" ? "wss" : "ws";
+ // The Next.js dev server proxies /ws → realtime service on :8086.
+ // In production, nginx handles the proxy.
+ const wsUrl = `${wsProto}://${window.location.host}/ws/agents?token=${encodeURIComponent(token)}`;
try {
- const msg = JSON.parse(evt.data as string) as Record<string, unknown>;
- const msgRunId = msg.run_id as string | undefined;
- // Only process events for this run
- if (msgRunId && msgRunId !== runId) return;
-
- if (msg.type === 'agent.event') {
- const kind = (msg.kind ?? '') as string;
- const agent = (msg.agent ?? '') as string;
- const summary = (msg.summary ?? '') as string;
- const ts = (msg.timestamp ?? new Date().toISOString()) as string;
-
- setLiveSteps((prev) => [...prev, { kind, agent, summary, ts }]);
-
- if (kind === 'completed') {
- setInvestigationStatus('completed');
- setInvestigating(false);
- toast.success('Investigation complete — report ready');
- // Fetch the Markdown report
- apiFetch(`/api/v1/cases/${caseId}/investigations/${runId}/report.md`)
- .then((r) => r.ok ? r.text() : '')
- .then((md) => { if (md) setReportMd(md); })
- .catch(() => { /* best-effort */ });
- // Also fetch full data
- casesApi.getInvestigation(caseId, runId)
- .then((inv) => setInvestigationData(inv as Record<string, unknown>))
- .catch(() => { /* best-effort */ });
- closeWs();
- } else if (kind === 'error') {
- setInvestigationStatus('failed');
- setInvestigating(false);
- toast.error(`Investigation failed: ${summary}`);
- closeWs();
+ const ws = new WebSocket(wsUrl);
+ wsRef.current = ws;
+ ws.onmessage = (evt) => {
+ try {
+ const msg = JSON.parse(evt.data as string) as Record<string, unknown>;
+ const msgRunId = msg.run_id as string | undefined;
+ // Only process events for this run
+ if (msgRunId && msgRunId !== runId) return;
+
+ if (msg.type === "agent.event") {
+ const kind = (msg.kind ?? "") as string;
+ const agent = (msg.agent ?? "") as string;
+ const summary = (msg.summary ?? "") as string;
+ const ts = (msg.timestamp ?? new Date().toISOString()) as string;
+
+ setLiveSteps((prev) => [...prev, { kind, agent, summary, ts }]);
+
+ if (kind === "completed") {
+ setInvestigationStatus("completed");
+ setInvestigating(false);
+ toast.success("Investigation complete — report ready");
+ // Fetch the Markdown report
+ apiFetch(`/api/v1/cases/${caseId}/investigations/${runId}/report.md`)
+ .then((r) => (r.ok ? r.text() : ""))
+ .then((md) => {
+ if (md) setReportMd(md);
+ })
+ .catch(() => {
+ /* best-effort */
+ });
+ // Also fetch full data
+ casesApi
+ .getInvestigation(caseId, runId)
+ .then((inv) => setInvestigationData(inv as Record<string, unknown>))
+ .catch(() => {
+ /* best-effort */
+ });
+ closeWs();
+ } else if (kind === "error") {
+ setInvestigationStatus("failed");
+ setInvestigating(false);
+ toast.error(`Investigation failed: ${summary}`);
+ closeWs();
+ }
+ }
+ } catch {
+ /* ignore parse errors */
}
- }
- } catch { /* ignore parse errors */ }
- };
- ws.onerror = () => {
- // Fall back to polling if WebSocket fails
- ws.close();
- wsRef.current = null;
- };
- } catch {
- // WebSocket not available — polling fallback is already running
- }
- })();
- }, [caseId, closeWs]);
+ };
+ ws.onerror = () => {
+ // Fall back to polling if WebSocket fails
+ ws.close();
+ wsRef.current = null;
+ };
+ } catch {
+ // WebSocket not available — polling fallback is already running
+ }
+ })();
+ },
+ [caseId, closeWs]
+ );
const startInvestigation = useCallback(async () => {
if (!caseRecord || investigating) return;
setInvestigating(true);
- setInvestigationStatus('starting');
+ setInvestigationStatus("starting");
setLiveSteps([]);
- setActiveTab('investigation');
+ setActiveTab("investigation");
try {
const result = await casesApi.investigate(caseId, caseRecord.description ?? caseRecord.title);
setInvestigationRunId(result.run_id);
- setInvestigationStatus('running');
- toast.success('Agent investigation started');
+ setInvestigationStatus("running");
+ toast.success("Agent investigation started");
// Connect via WebSocket for live updates (falls back to polling on error)
connectWs(result.run_id);
@@ -505,17 +533,21 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
const inv = await casesApi.getInvestigation(caseId, result.run_id);
setInvestigationData(inv as Record<string, unknown>);
setInvestigationStatus(inv.status);
- if (inv.status === 'completed' || inv.status === 'failed') {
+ if (inv.status === "completed" || inv.status === "failed") {
stopPolling();
setInvestigating(false);
- if (inv.status === 'completed') {
- toast.success('Investigation complete — report ready');
+ if (inv.status === "completed") {
+ toast.success("Investigation complete — report ready");
try {
- const resp = await apiFetch(`/api/v1/cases/${caseId}/investigations/${result.run_id}/report.md`);
+ const resp = await apiFetch(
+ `/api/v1/cases/${caseId}/investigations/${result.run_id}/report.md`
+ );
if (resp.ok) setReportMd(await resp.text());
- } catch { /* best-effort */ }
+ } catch {
+ /* best-effort */
+ }
} else {
- toast.error(`Investigation failed: ${inv.error ?? 'unknown error'}`);
+ toast.error(`Investigation failed: ${inv.error ?? "unknown error"}`);
}
}
} catch {
@@ -530,10 +562,10 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
// structured panels that carried no caveat of their own, behind a toast
// that is gone by the time anyone reads them. An analyst cannot tell
// that verdict apart from one the agents actually produced.
- const message = e instanceof Error ? e.message : 'Could not reach the investigation service';
- setInvestigationStatus('failed');
- setInvestigationData({ status: 'failed', error: message });
- setReportMd('');
+ const message = e instanceof Error ? e.message : "Could not reach the investigation service";
+ setInvestigationStatus("failed");
+ setInvestigationData({ status: "failed", error: message });
+ setReportMd("");
setInvestigating(false);
toast.error(`Investigation could not start: ${message}`);
}
@@ -541,8 +573,8 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
// ─── Local mutations (optimistic) ──────────────────────────────────────────
- const [newComment, setNewComment] = useState('');
- const [newTask, setNewTask] = useState('');
+ const [newComment, setNewComment] = useState("");
+ const [newTask, setNewTask] = useState("");
const [statusUpdating, setStatusUpdating] = useState(false);
// WS-D2 — track summary-download state so the button can show "Generating…"
// and we can surface failures via toast without burying them in the console.
@@ -553,9 +585,9 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
setSummaryDownloading(true);
try {
await casesApi.openAutoSummaryHtml(caseRecord.id || caseId);
- toast.success('Summary opened — use Print → Save as PDF to archive');
+ toast.success("Summary opened — use Print → Save as PDF to archive");
} catch (e: unknown) {
- const message = e instanceof Error ? e.message : 'Backend offline';
+ const message = e instanceof Error ? e.message : "Backend offline";
toast.error(`Summary unavailable: ${message}`);
} finally {
setSummaryDownloading(false);
@@ -570,11 +602,21 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
try {
// Backwards moves are refused by the forward-only PATCH ladder (422);
// route them through the explicit reopen endpoint instead.
- const LADDER = ['new', 'triaged', 'investigating', 'contained', 'resolved', 'closed'] as const;
- if (LADDER.indexOf(status as (typeof LADDER)[number]) < LADDER.indexOf(previous as (typeof LADDER)[number])) {
+ const LADDER = [
+ "new",
+ "triaged",
+ "investigating",
+ "contained",
+ "resolved",
+ "closed",
+ ] as const;
+ if (
+ LADDER.indexOf(status as (typeof LADDER)[number]) <
+ LADDER.indexOf(previous as (typeof LADDER)[number])
+ ) {
await casesApi.reopen(caseRecord.id, {
reason: `Reopened to ${STATUS_LABEL[status]} from analyst console`,
- status: status === 'new' || status === 'triaged' ? status : 'investigating',
+ status: status === "new" || status === "triaged" ? status : "investigating",
});
toast.success(`Case reopened — ${STATUS_LABEL[status]}`);
} else {
@@ -586,7 +628,7 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
// showed a status the database does not have, on the one screen an
// analyst uses to decide whether an incident is still open.
void mutate({ ...caseRecord, status: previous }, { revalidate: false });
- const message = e instanceof Error ? e.message : 'the case service rejected the write';
+ const message = e instanceof Error ? e.message : "the case service rejected the write";
toast.error(`Status unchanged — ${message}`);
} finally {
setStatusUpdating(false);
@@ -598,22 +640,22 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
if (!caseRecord || !trimmed) return;
const optimistic: CaseTimelineEvent = {
id: `tl-tmp-${Date.now()}`,
- type: 'comment',
+ type: "comment",
timestamp: new Date().toISOString(),
- title: 'Comment',
+ title: "Comment",
description: trimmed,
- actor: 'you',
+ actor: "you",
};
void mutate(
{ ...caseRecord, timeline: [...(caseRecord.timeline ?? []), optimistic] },
- { revalidate: false },
+ { revalidate: false }
);
- setNewComment('');
+ setNewComment("");
try {
await casesApi.addComment(caseRecord.id, trimmed);
- toast.success('Comment added');
+ toast.success("Comment added");
} catch {
- toast('Saved locally (writes disabled in demo)');
+ toast("Saved locally (writes disabled in demo)");
}
};
@@ -623,30 +665,25 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
const optimistic: CaseTask = {
id: `task-tmp-${Date.now()}`,
title: trimmed,
- status: 'todo',
+ status: "todo",
createdAt: new Date().toISOString(),
};
void mutate(
{ ...caseRecord, tasks: [...(caseRecord.tasks ?? []), optimistic] },
- { revalidate: false },
+ { revalidate: false }
);
- setNewTask('');
+ setNewTask("");
try {
await casesApi.addTask(caseRecord.id, optimistic);
- toast.success('Task added');
+ toast.success("Task added");
} catch {
- toast('Saved locally (writes disabled in demo)');
+ toast("Saved locally (writes disabled in demo)");
}
};
- const updateTaskStatus = async (
- taskId: string,
- status: CaseTask['status'],
- ) => {
+ const updateTaskStatus = async (taskId: string, status: CaseTask["status"]) => {
if (!caseRecord) return;
- const tasks = (caseRecord.tasks ?? []).map((t) =>
- t.id === taskId ? { ...t, status } : t,
- );
+ const tasks = (caseRecord.tasks ?? []).map((t) => (t.id === taskId ? { ...t, status } : t));
void mutate({ ...caseRecord, tasks }, { revalidate: false });
try {
await casesApi.updateTask(caseRecord.id, taskId, { status });
@@ -688,14 +725,12 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
);
}
- const sortedTimeline = [...new Map([...fetchedTimeline, ...(caseRecord.timeline ?? [])]
- .map((e) => [e.id, e])).values()].sort(
- (a, b) =>
- new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
- );
+ const sortedTimeline = [
+ ...new Map([...fetchedTimeline, ...(caseRecord.timeline ?? [])].map((e) => [e.id, e])).values(),
+ ].sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
const tasks = caseRecord.tasks ?? [];
- const tasksDone = tasks.filter((t) => t.status === 'done').length;
+ const tasksDone = tasks.filter((t) => t.status === "done").length;
const tasksProgress = tasks.length === 0 ? 0 : Math.round((tasksDone / tasks.length) * 100);
return (
@@ -724,8 +759,8 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
<div className="flex flex-wrap items-center gap-2">
<span
className={clsx(
- 'inline-flex items-center rounded px-2 py-0.5 text-[11px] font-bold uppercase tracking-wide ring-1',
- SEVERITY_BADGE[caseRecord.severity],
+ "inline-flex items-center rounded px-2 py-0.5 text-[11px] font-bold uppercase tracking-wide ring-1",
+ SEVERITY_BADGE[caseRecord.severity]
)}
>
{caseRecord.severity}
@@ -740,13 +775,9 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
</span>
))}
</div>
- <h1 className="mt-2 text-xl font-semibold text-white">
- {caseRecord.title}
- </h1>
+ <h1 className="mt-2 text-xl font-semibold text-white">{caseRecord.title}</h1>
{caseRecord.description && (
- <p className="mt-2 max-w-3xl text-sm text-slate-400">
- {caseRecord.description}
- </p>
+ <p className="mt-2 max-w-3xl text-sm text-slate-400">{caseRecord.description}</p>
)}
{caseRecord.mitre && caseRecord.mitre.length > 0 && (
<div className="mt-3 flex flex-wrap items-center gap-1.5 text-xs">
@@ -760,7 +791,13 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
{/* Action bar */}
<div className="flex flex-wrap items-center gap-2">
+ {/* Named for what changing it does. Without this a screen
+ reader announces "open" with no indication that choosing
+ another value transitions the case -- and this control
+ writes, so an unlabelled one is a state change somebody
+ cannot see they are making. */}
<select
+ aria-label="Change case status"
value={caseRecord.status}
onChange={(e) => void updateStatus(e.target.value as CaseStatus)}
disabled={statusUpdating}
@@ -771,37 +808,35 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
are refused by the API, so every status change from this
control failed validation.
*/}
- {(
- [
- 'new',
- 'triaged',
- 'investigating',
- 'contained',
- 'resolved',
- 'closed',
- ] as CaseStatus[]
- ).map(
- (s) => (
- <option key={s} value={s}>
- {STATUS_LABEL[s]}
- </option>
- ),
- )}
+ {(
+ [
+ "new",
+ "triaged",
+ "investigating",
+ "contained",
+ "resolved",
+ "closed",
+ ] as CaseStatus[]
+ ).map((s) => (
+ <option key={s} value={s}>
+ {STATUS_LABEL[s]}
+ </option>
+ ))}
</select>
<button
onClick={() => void startInvestigation()}
disabled={investigating}
className={clsx(
- 'inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-semibold transition-colors',
+ "inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-semibold transition-colors",
investigating
- ? 'cursor-not-allowed border-slate-700/40 bg-slate-800/40 text-slate-500'
- : 'border-emerald-500/40 bg-emerald-500/10 text-emerald-200 hover:bg-emerald-500/20',
+ ? "cursor-not-allowed border-slate-700/40 bg-slate-800/40 text-slate-500"
+ : "border-emerald-500/40 bg-emerald-500/10 text-emerald-200 hover:bg-emerald-500/20"
)}
>
{investigating && (
<span className="h-3 w-3 animate-spin rounded-full border border-emerald-500/30 border-t-emerald-400" />
)}
- {investigating ? 'Investigating…' : 'Investigate with agent'}
+ {investigating ? "Investigating…" : "Investigate with agent"}
</button>
{/*
WS-D2 — deterministic, analyst-ready snapshot of the entire case
@@ -817,27 +852,27 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
onClick={() => void downloadSummary()}
disabled={summaryDownloading || !caseRecord}
className={clsx(
- 'inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-semibold transition-colors',
+ "inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-semibold transition-colors",
summaryDownloading || !caseRecord
- ? 'cursor-not-allowed border-slate-700/40 bg-slate-800/40 text-slate-500'
- : 'border-indigo-500/40 bg-indigo-500/10 text-indigo-200 hover:bg-indigo-500/20',
+ ? "cursor-not-allowed border-slate-700/40 bg-slate-800/40 text-slate-500"
+ : "border-indigo-500/40 bg-indigo-500/10 text-indigo-200 hover:bg-indigo-500/20"
)}
title="Open a print-ready case summary (HTML → Save as PDF)"
>
{summaryDownloading && (
<span className="h-3 w-3 animate-spin rounded-full border border-indigo-500/30 border-t-indigo-400" />
)}
- {summaryDownloading ? 'Generating…' : 'Summary'}
+ {summaryDownloading ? "Generating…" : "Summary"}
</button>
</div>
</div>
{/* Meta row */}
<div className="mt-4 grid grid-cols-2 gap-2 border-t border-slate-800/60 pt-4 text-xs text-slate-400 sm:grid-cols-4">
- <Meta label="Assignee" value={caseRecord.assignee?.split('@')[0] ?? '—'} />
+ <Meta label="Assignee" value={caseRecord.assignee?.split("@")[0] ?? "—"} />
<Meta
label="Created"
- value={format(new Date(caseRecord.createdAt), 'MMM d, HH:mm')}
+ value={format(new Date(caseRecord.createdAt), "MMM d, HH:mm")}
suppressHydrationWarning
/>
<Meta
@@ -850,9 +885,7 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
<Meta
label="SLA"
value={
- caseRecord.dueAt
- ? `${formatDistanceToNow(new Date(caseRecord.dueAt))} left`
- : '—'
+ caseRecord.dueAt ? `${formatDistanceToNow(new Date(caseRecord.dueAt))} left` : "—"
}
suppressHydrationWarning
/>
@@ -866,16 +899,14 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
key={tab}
onClick={() => setActiveTab(tab)}
className={clsx(
- 'relative px-3 py-2 font-medium capitalize transition-colors',
- activeTab === tab
- ? 'text-emerald-300'
- : 'text-slate-500 hover:text-slate-300',
+ "relative px-3 py-2 font-medium capitalize transition-colors",
+ activeTab === tab ? "text-emerald-300" : "text-slate-500 hover:text-slate-300"
)}
>
- {tab === 'investigation' && investigating && (
+ {tab === "investigation" && investigating && (
<span className="mr-1 inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-emerald-400" />
)}
- {tab === 'ledger' ? (
+ {tab === "ledger" ? (
<span className="inline-flex items-center gap-1">
Ledger
<span
@@ -885,7 +916,7 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
audit
</span>
</span>
- ) : tab === 'attack-path' ? (
+ ) : tab === "attack-path" ? (
<span className="inline-flex items-center gap-1">
Attack path
<span
@@ -895,7 +926,7 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
graph
</span>
</span>
- ) : tab === 'attack-chain' ? (
+ ) : tab === "attack-chain" ? (
<span className="inline-flex items-center gap-1">
Attack chain
<span
@@ -916,12 +947,12 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
</div>
{/* Investigation tab */}
- {activeTab === 'investigation' && (
+ {activeTab === "investigation" && (
<InvestigationPanel
status={investigationStatus}
data={investigationData}
liveSteps={liveSteps}
- onViewReport={() => setActiveTab('report')}
+ onViewReport={() => setActiveTab("report")}
/>
)}
@@ -929,17 +960,13 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
We use the URL `caseId` prop rather than `caseRecord.id` because some
backend variants return the case body without an `id` field; the URL
is the canonical identifier here. */}
- {activeTab === 'attack-path' && (
- <AttackPathPanel caseId={caseRecord.id || caseId} />
- )}
+ {activeTab === "attack-path" && <AttackPathPanel caseId={caseRecord.id || caseId} />}
{/* Attack-chain tab — ranked temporal timeline of related alerts */}
- {activeTab === 'attack-chain' && (
- <AttackChainPanel caseId={caseRecord.id || caseId} />
- )}
+ {activeTab === "attack-chain" && <AttackChainPanel caseId={caseRecord.id || caseId} />}
{/* Ledger tab — persistent, replayable agent decision log */}
- {activeTab === 'ledger' && (
+ {activeTab === "ledger" && (
<InvestigationLedger
caseId={caseRecord.id || caseId}
activeRunId={investigationRunId}
@@ -948,181 +975,184 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
)}
{/* Report tab */}
- {activeTab === 'report' && (
+ {activeTab === "report" && (
<ReportPanel
markdown={reportMd}
caseId={caseRecord.id || caseId}
- runId={investigationRunId ?? ''}
+ runId={investigationRunId ?? ""}
/>
)}
{/* Overview: Three-pane layout */}
- {activeTab === 'overview' && (
- <div className="space-y-4">
- {/*
+ {activeTab === "overview" && (
+ <div className="space-y-4">
+ {/*
Ambient Copilot — case-scoped contextual AI. We pass a compact
snapshot of the case (no embedded alert blobs or full timeline) so the
LLM has grounding without ballooning token usage. Backed by
`services/agents` `/api/v1/contextual` endpoints.
*/}
- <ContextualActions
- page="cases"
- entityId={caseRecord.id}
- caseId={caseRecord.id}
- entity={{
- title: caseRecord.title,
- description: caseRecord.description,
- severity: caseRecord.severity,
- status: caseRecord.status,
- assignee: caseRecord.assignee,
- mitre: caseRecord.mitre,
- tags: caseRecord.tags,
- alert_ids: caseRecord.alertIds,
- alert_count: caseRecord.alertCount,
- created_at: caseRecord.createdAt,
- updated_at: caseRecord.updatedAt,
- due_at: caseRecord.dueAt,
- }}
- eyebrow="Ask AiSOC about this case"
- />
-
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-12">
- {/* Left: Linked alerts + IOCs */}
- <aside className="lg:col-span-3 space-y-4">
- <Panel title={`Linked alerts (${caseRecord.alertIds?.length ?? 0})`}>
- {(caseRecord.alertIds ?? []).length === 0 ? (
- <EmptyState
- title="No alerts linked"
- description="Link alerts from the alerts feed."
- />
- ) : (
- <ul className="space-y-1.5">
- {(caseRecord.alertIds ?? []).map((id) => (
- <li key={id}>
- <Link
- href={`/alerts?focus=${encodeURIComponent(id)}`}
- className="flex items-center justify-between rounded-md border border-slate-800/80 bg-slate-900/40 px-2.5 py-1.5 text-xs text-slate-300 transition-colors hover:border-slate-700 hover:bg-slate-800/40"
- >
- <span className="font-mono">{id}</span>
- <span className="text-[10px] uppercase tracking-wide text-slate-500">open</span>
- </Link>
- </li>
- ))}
- </ul>
- )}
- </Panel>
+ <ContextualActions
+ page="cases"
+ entityId={caseRecord.id}
+ caseId={caseRecord.id}
+ entity={{
+ title: caseRecord.title,
+ description: caseRecord.description,
+ severity: caseRecord.severity,
+ status: caseRecord.status,
+ assignee: caseRecord.assignee,
+ mitre: caseRecord.mitre,
+ tags: caseRecord.tags,
+ alert_ids: caseRecord.alertIds,
+ alert_count: caseRecord.alertCount,
+ created_at: caseRecord.createdAt,
+ updated_at: caseRecord.updatedAt,
+ due_at: caseRecord.dueAt,
+ }}
+ eyebrow="Ask AiSOC about this case"
+ />
- <Panel title="Tasks">
- <div className="mb-2 flex items-center gap-2 text-[11px] text-slate-400">
- <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-slate-800">
- <div
- className="h-full rounded-full bg-emerald-500 transition-all"
- style={{ width: `${tasksProgress}%` }}
- />
- </div>
- <span>
- {tasksDone}/{tasks.length}
- </span>
- </div>
- {tasks.length === 0 ? (
- <EmptyState title="No tasks yet" description="Add the first one below." />
- ) : (
- <ul className="space-y-1.5">
- {tasks.map((t) => (
- <TaskRow
- key={t.id}
- task={t}
- onChangeStatus={(s) => void updateTaskStatus(t.id, s)}
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-12">
+ {/* Left: Linked alerts + IOCs */}
+ {/* Two <aside> landmarks sit side by side here. Unnamed they
+ are indistinguishable in a landmark list, which is the one
+ place a screen-reader user navigates this page from. */}
+ <aside aria-label="Linked alerts" className="lg:col-span-3 space-y-4">
+ <Panel title={`Linked alerts (${caseRecord.alertIds?.length ?? 0})`}>
+ {(caseRecord.alertIds ?? []).length === 0 ? (
+ <EmptyState
+ title="No alerts linked"
+ description="Link alerts from the alerts feed."
/>
- ))}
- </ul>
- )}
- <div className="mt-2 flex items-center gap-2">
- <input
- value={newTask}
- onChange={(e) => setNewTask(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') void addTask();
- }}
- placeholder="Add task and press ↵"
- className="flex-1 rounded-md border border-slate-700/70 bg-slate-900/40 px-2 py-1.5 text-xs text-slate-100 placeholder-slate-600 focus:border-emerald-500/40 focus:outline-none"
- />
- <button
- onClick={() => void addTask()}
- className="rounded-md bg-emerald-500 px-2.5 py-1.5 text-xs font-semibold text-emerald-950 transition-colors hover:bg-emerald-400 disabled:cursor-not-allowed disabled:bg-slate-800 disabled:text-slate-500"
- disabled={!newTask.trim()}
+ ) : (
+ <ul className="space-y-1.5">
+ {(caseRecord.alertIds ?? []).map((id) => (
+ <li key={id}>
+ <Link
+ href={`/alerts?focus=${encodeURIComponent(id)}`}
+ className="flex items-center justify-between rounded-md border border-slate-800/80 bg-slate-900/40 px-2.5 py-1.5 text-xs text-slate-300 transition-colors hover:border-slate-700 hover:bg-slate-800/40"
+ >
+ <span className="font-mono">{id}</span>
+ <span className="text-[10px] uppercase tracking-wide text-slate-500">
+ open
+ </span>
+ </Link>
+ </li>
+ ))}
+ </ul>
+ )}
+ </Panel>
+
+ <Panel title="Tasks">
+ <div className="mb-2 flex items-center gap-2 text-[11px] text-slate-400">
+ <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-slate-800">
+ <div
+ className="h-full rounded-full bg-emerald-500 transition-all"
+ style={{ width: `${tasksProgress}%` }}
+ />
+ </div>
+ <span>
+ {tasksDone}/{tasks.length}
+ </span>
+ </div>
+ {tasks.length === 0 ? (
+ <EmptyState title="No tasks yet" description="Add the first one below." />
+ ) : (
+ <ul className="space-y-1.5">
+ {tasks.map((t) => (
+ <TaskRow
+ key={t.id}
+ task={t}
+ onChangeStatus={(s) => void updateTaskStatus(t.id, s)}
+ />
+ ))}
+ </ul>
+ )}
+ <div className="mt-2 flex items-center gap-2">
+ <input
+ value={newTask}
+ onChange={(e) => setNewTask(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") void addTask();
+ }}
+ placeholder="Add task and press ↵"
+ className="flex-1 rounded-md border border-slate-700/70 bg-slate-900/40 px-2 py-1.5 text-xs text-slate-100 placeholder-slate-600 focus:border-emerald-500/40 focus:outline-none"
+ />
+ <button
+ onClick={() => void addTask()}
+ className="rounded-md bg-emerald-500 px-2.5 py-1.5 text-xs font-semibold text-emerald-950 transition-colors hover:bg-emerald-400 disabled:cursor-not-allowed disabled:bg-slate-800 disabled:text-slate-500"
+ disabled={!newTask.trim()}
+ >
+ Add
+ </button>
+ </div>
+ </Panel>
+ </aside>
+
+ {/* Center: Timeline */}
+ <section className="lg:col-span-6">
+ <Panel
+ title="Timeline"
+ actions={
+ <span className="text-[11px] text-slate-500">{sortedTimeline.length} events</span>
+ }
>
- Add
- </button>
- </div>
- </Panel>
- </aside>
-
- {/* Center: Timeline */}
- <section className="lg:col-span-6">
- <Panel
- title="Timeline"
- actions={
- <span className="text-[11px] text-slate-500">
- {sortedTimeline.length} events
- </span>
- }
- >
- {sortedTimeline.length === 0 ? (
- <EmptyState
- title="Quiet so far"
- description="Activity, comments, and agent runs will appear here."
- />
- ) : (
- <ol className="relative space-y-3 before:absolute before:left-3.5 before:top-2 before:bottom-2 before:w-px before:bg-slate-800/80">
- {sortedTimeline.map((e) => (
- <TimelineItem key={e.id} event={e} />
- ))}
- </ol>
- )}
- </Panel>
- </section>
-
- {/* Right: Notes / activity composer */}
- <aside className="lg:col-span-3 space-y-4">
- <Panel title="Notes & comments">
- <div className="space-y-2">
- <textarea
- value={newComment}
- onChange={(e) => setNewComment(e.target.value)}
- rows={4}
- placeholder="Drop your findings, IOCs, or next steps…"
- className="w-full resize-none rounded-md border border-slate-700/70 bg-slate-900/40 px-2 py-1.5 text-xs text-slate-100 placeholder-slate-600 focus:border-emerald-500/40 focus:outline-none"
- />
- <div className="flex items-center justify-end gap-2">
- <button
- onClick={() => setNewComment('')}
- className="rounded-md border border-slate-700/70 px-2.5 py-1.5 text-xs text-slate-300 hover:border-slate-600"
- >
- Clear
- </button>
- <button
- onClick={() => void addComment()}
- disabled={!newComment.trim()}
- className="rounded-md bg-emerald-500 px-2.5 py-1.5 text-xs font-semibold text-emerald-950 transition-colors hover:bg-emerald-400 disabled:cursor-not-allowed disabled:bg-slate-800 disabled:text-slate-500"
- >
- Post
- </button>
- </div>
- </div>
- </Panel>
-
- <Panel title="Resolution">
- <textarea
- defaultValue={caseRecord.resolution ?? ''}
- rows={5}
- placeholder="Final summary, root cause, remediation…"
- className="w-full resize-none rounded-md border border-slate-700/70 bg-slate-900/40 px-2 py-1.5 text-xs text-slate-100 placeholder-slate-600 focus:border-emerald-500/40 focus:outline-none"
- />
- </Panel>
- </aside>
- </div>
- </div>
+ {sortedTimeline.length === 0 ? (
+ <EmptyState
+ title="Quiet so far"
+ description="Activity, comments, and agent runs will appear here."
+ />
+ ) : (
+ <ol className="relative space-y-3 before:absolute before:left-3.5 before:top-2 before:bottom-2 before:w-px before:bg-slate-800/80">
+ {sortedTimeline.map((e) => (
+ <TimelineItem key={e.id} event={e} />
+ ))}
+ </ol>
+ )}
+ </Panel>
+ </section>
+
+ {/* Right: Notes / activity composer */}
+ <aside aria-label="Notes and comments" className="lg:col-span-3 space-y-4">
+ <Panel title="Notes & comments">
+ <div className="space-y-2">
+ <textarea
+ value={newComment}
+ onChange={(e) => setNewComment(e.target.value)}
+ rows={4}
+ placeholder="Drop your findings, IOCs, or next steps…"
+ className="w-full resize-none rounded-md border border-slate-700/70 bg-slate-900/40 px-2 py-1.5 text-xs text-slate-100 placeholder-slate-600 focus:border-emerald-500/40 focus:outline-none"
+ />
+ <div className="flex items-center justify-end gap-2">
+ <button
+ onClick={() => setNewComment("")}
+ className="rounded-md border border-slate-700/70 px-2.5 py-1.5 text-xs text-slate-300 hover:border-slate-600"
+ >
+ Clear
+ </button>
+ <button
+ onClick={() => void addComment()}
+ disabled={!newComment.trim()}
+ className="rounded-md bg-emerald-500 px-2.5 py-1.5 text-xs font-semibold text-emerald-950 transition-colors hover:bg-emerald-400 disabled:cursor-not-allowed disabled:bg-slate-800 disabled:text-slate-500"
+ >
+ Post
+ </button>
+ </div>
+ </div>
+ </Panel>
+
+ <Panel title="Resolution">
+ <textarea
+ defaultValue={caseRecord.resolution ?? ""}
+ rows={5}
+ placeholder="Final summary, root cause, remediation…"
+ className="w-full resize-none rounded-md border border-slate-700/70 bg-slate-900/40 px-2 py-1.5 text-xs text-slate-100 placeholder-slate-600 focus:border-emerald-500/40 focus:outline-none"
+ />
+ </Panel>
+ </aside>
+ </div>
+ </div>
)}
</div>
);
@@ -1143,39 +1173,42 @@ function InvestigationPanel({
liveSteps: LiveStep[];
onViewReport: () => void;
}) {
- if (status === 'idle' || status === 'starting') {
+ if (status === "idle" || status === "starting") {
return (
<div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-slate-700/60 bg-slate-900/30 py-16 text-center">
<p className="text-sm font-medium text-slate-300">Agent investigation</p>
<p className="mt-1 max-w-md text-xs text-slate-500">
- Use &ldquo;Investigate with agent&rdquo; in the header to run the recon, forensic, and responder agents on this case.
+ Use &ldquo;Investigate with agent&rdquo; in the header to run the recon, forensic, and
+ responder agents on this case.
</p>
</div>
);
}
- if (status === 'running') {
+ if (status === "running") {
return (
<div className="rounded-xl border border-slate-800/70 bg-slate-900/30 p-5 space-y-4">
<div className="flex items-center gap-3">
<span className="h-7 w-7 animate-spin rounded-full border-2 border-emerald-500/30 border-t-emerald-400 shrink-0" />
<div>
<p className="text-sm font-medium text-slate-300">Investigation in progress…</p>
- <p className="text-xs text-slate-500">Agents are working. Steps appear below in real-time.</p>
+ <p className="text-xs text-slate-500">
+ Agents are working. Steps appear below in real-time.
+ </p>
</div>
</div>
- {liveSteps.length > 0 && (
- <LiveStepsFeed steps={liveSteps} />
- )}
+ {liveSteps.length > 0 && <LiveStepsFeed steps={liveSteps} />}
</div>
);
}
- if (status === 'failed') {
+ if (status === "failed") {
return (
<div className="rounded-xl border border-red-800/40 bg-red-900/10 p-5">
<p className="text-sm font-semibold text-red-300">Investigation failed</p>
- <p className="mt-1 text-xs text-slate-400">{String((data as { error?: string })?.error ?? 'Unknown error')}</p>
+ <p className="mt-1 text-xs text-slate-400">
+ {String((data as { error?: string })?.error ?? "Unknown error")}
+ </p>
{liveSteps.length > 0 && (
<div className="mt-3">
<LiveStepsFeed steps={liveSteps} />
@@ -1189,9 +1222,10 @@ function InvestigationPanel({
const recon = data?.recon as Record<string, unknown> | undefined;
const forensic = data?.forensic as Record<string, unknown> | undefined;
const responder = data?.responder as Record<string, unknown> | undefined;
- const auditLog = liveSteps.length > 0
- ? liveSteps
- : (data?.audit_log as Array<{ kind: string; agent: string; summary: string }>) ?? [];
+ const auditLog =
+ liveSteps.length > 0
+ ? liveSteps
+ : ((data?.audit_log as Array<{ kind: string; agent: string; summary: string }>) ?? []);
return (
<div className="space-y-4">
@@ -1211,7 +1245,9 @@ function InvestigationPanel({
{/* Recon */}
<div className="rounded-xl border border-slate-800/80 bg-slate-900/40 p-4 space-y-2">
<h4 className="text-xs font-semibold uppercase tracking-wide text-blue-300">Recon</h4>
- {recon?.summary != null && <p className="text-xs text-slate-400">{String(recon.summary)}</p>}
+ {recon?.summary != null && (
+ <p className="text-xs text-slate-400">{String(recon.summary)}</p>
+ )}
{Array.isArray(recon?.iocs) && recon.iocs.length > 0 && (
<div>
<p className="text-[11px] text-slate-500 mb-1">IOCs found:</p>
@@ -1227,7 +1263,12 @@ function InvestigationPanel({
{Array.isArray(recon?.mitre_techniques) && recon.mitre_techniques.length > 0 && (
<div className="flex flex-wrap gap-1">
{(recon.mitre_techniques as string[]).map((t) => (
- <span key={t} className="rounded bg-orange-500/10 px-1.5 py-0.5 text-[10px] text-orange-300 ring-1 ring-orange-500/20">{t}</span>
+ <span
+ key={t}
+ className="rounded bg-orange-500/10 px-1.5 py-0.5 text-[10px] text-orange-300 ring-1 ring-orange-500/20"
+ >
+ {t}
+ </span>
))}
</div>
)}
@@ -1235,20 +1276,29 @@ function InvestigationPanel({
{/* Forensic */}
<div className="rounded-xl border border-slate-800/80 bg-slate-900/40 p-4 space-y-2">
- <h4 className="text-xs font-semibold uppercase tracking-wide text-purple-300">Forensic</h4>
- {forensic?.summary != null && <p className="text-xs text-slate-400">{String(forensic.summary)}</p>}
+ <h4 className="text-xs font-semibold uppercase tracking-wide text-purple-300">
+ Forensic
+ </h4>
+ {forensic?.summary != null && (
+ <p className="text-xs text-slate-400">{String(forensic.summary)}</p>
+ )}
{forensic?.root_cause_hypothesis != null && (
<div>
<p className="text-[11px] text-slate-500">Root cause hypothesis:</p>
<p className="text-xs text-slate-300">{String(forensic.root_cause_hypothesis)}</p>
</div>
)}
- {typeof forensic?.confidence === 'number' && (
+ {typeof forensic?.confidence === "number" && (
<div className="flex items-center gap-2">
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-slate-800">
- <div className="h-full rounded-full bg-purple-500" style={{ width: `${(forensic.confidence as number) * 100}%` }} />
+ <div
+ className="h-full rounded-full bg-purple-500"
+ style={{ width: `${(forensic.confidence as number) * 100}%` }}
+ />
</div>
- <span className="text-[11px] text-slate-400">{Math.round((forensic.confidence as number) * 100)}% confidence</span>
+ <span className="text-[11px] text-slate-400">
+ {Math.round((forensic.confidence as number) * 100)}% confidence
+ </span>
</div>
)}
</div>
@@ -1256,7 +1306,9 @@ function InvestigationPanel({
{/* Responder */}
<div className="rounded-xl border border-slate-800/80 bg-slate-900/40 p-4 space-y-2">
<h4 className="text-xs font-semibold uppercase tracking-wide text-amber-300">Response</h4>
- {responder?.summary != null && <p className="text-xs text-slate-400">{String(responder.summary)}</p>}
+ {responder?.summary != null && (
+ <p className="text-xs text-slate-400">{String(responder.summary)}</p>
+ )}
{Array.isArray(responder?.recommended_actions) && (
<ul className="space-y-1.5">
{(responder.recommended_actions as Array<unknown>).slice(0, 4).map((raw, i) => {
@@ -1268,13 +1320,21 @@ function InvestigationPanel({
<li key={i} className="flex items-start gap-1.5 text-xs text-slate-300">
<span className="mt-0.5 h-1.5 w-1.5 flex-none rounded-full bg-amber-400" />
<span>
- {prio != null && <span className="mr-1 text-[10px] font-semibold text-amber-300">P{prio}</span>}
+ {prio != null && (
+ <span className="mr-1 text-[10px] font-semibold text-amber-300">
+ P{prio}
+ </span>
+ )}
{text}
{risk != null && risk.toLowerCase() !== "low" && (
- <span className="ml-1 rounded bg-red-500/10 px-1 py-0.5 text-[9px] uppercase text-red-300 ring-1 ring-red-500/20">{risk}</span>
+ <span className="ml-1 rounded bg-red-500/10 px-1 py-0.5 text-[9px] uppercase text-red-300 ring-1 ring-red-500/20">
+ {risk}
+ </span>
)}
{a.rationale != null && String(a.rationale).length > 0 && (
- <span className="block text-[10px] text-slate-500">{String(a.rationale)}</span>
+ <span className="block text-[10px] text-slate-500">
+ {String(a.rationale)}
+ </span>
)}
</span>
</li>
@@ -1283,12 +1343,16 @@ function InvestigationPanel({
</ul>
)}
{responder?.risk_level != null && (
- <span className={clsx(
- 'inline-flex rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase ring-1',
- responder.risk_level === 'high' ? 'bg-red-500/10 text-red-300 ring-red-500/20' :
- responder.risk_level === 'medium' ? 'bg-amber-500/10 text-amber-300 ring-amber-500/20' :
- 'bg-emerald-500/10 text-emerald-300 ring-emerald-500/20',
- )}>
+ <span
+ className={clsx(
+ "inline-flex rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase ring-1",
+ responder.risk_level === "high"
+ ? "bg-red-500/10 text-red-300 ring-red-500/20"
+ : responder.risk_level === "medium"
+ ? "bg-amber-500/10 text-amber-300 ring-amber-500/20"
+ : "bg-emerald-500/10 text-emerald-300 ring-emerald-500/20"
+ )}
+ >
{String(responder.risk_level)} risk
</span>
)}
@@ -1323,7 +1387,7 @@ function AttackPathPanel({ caseId }: { caseId: string }) {
const { data, error, isLoading } = useSWR<CaseAttackPath | null>(
hasCaseId ? `case:${caseId}:attack-path` : null,
() => graphApi.getCaseAttackPath(caseId, { maxDepth: 4 }),
- { revalidateOnFocus: false },
+ { revalidateOnFocus: false }
);
if (!hasCaseId) {
@@ -1351,7 +1415,7 @@ function AttackPathPanel({ caseId }: { caseId: string }) {
return (
<ErrorState
title="Failed to load attack path"
- description={error instanceof Error ? error.message : 'Unknown error'}
+ description={error instanceof Error ? error.message : "Unknown error"}
/>
);
}
@@ -1360,13 +1424,25 @@ function AttackPathPanel({ caseId }: { caseId: string }) {
return (
<div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-slate-700/60 bg-slate-900/30 py-16 text-center">
<div className="mb-3 flex h-10 w-10 items-center justify-center rounded-full bg-orange-500/10 ring-1 ring-orange-500/30">
- <svg className="h-5 w-5 text-orange-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
+ <svg
+ className="h-5 w-5 text-orange-300"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M13 10V3L4 14h7v7l9-11h-7z"
+ />
</svg>
</div>
<p className="text-sm font-medium text-slate-300">No attack path yet</p>
<p className="mt-1 max-w-md text-xs text-slate-500">
- The Attack-Path Investigation Agent reconstructs lateral movement and blast radius from linked alerts and graph entities. Run an investigation or link more alerts to surface a path here.
+ The Attack-Path Investigation Agent reconstructs lateral movement and blast radius from
+ linked alerts and graph entities. Run an investigation or link more alerts to surface a
+ path here.
</p>
</div>
);
@@ -1374,14 +1450,11 @@ function AttackPathPanel({ caseId }: { caseId: string }) {
// Bucket nodes by entity type so the panel reads as &ldquo;hosts /
// identities / processes&rdquo; rather than an undifferentiated soup.
- const nodesByType = data.nodes.reduce<Record<string, CaseAttackPath['nodes']>>(
- (acc, node) => {
- const type = (node.properties?.type as string) ?? node.label ?? 'entity';
- (acc[type] ||= []).push(node);
- return acc;
- },
- {},
- );
+ const nodesByType = data.nodes.reduce<Record<string, CaseAttackPath["nodes"]>>((acc, node) => {
+ const type = (node.properties?.type as string) ?? node.label ?? "entity";
+ (acc[type] ||= []).push(node);
+ return acc;
+ }, {});
return (
<div className="space-y-4">
@@ -1389,7 +1462,8 @@ function AttackPathPanel({ caseId }: { caseId: string }) {
<div>
<h3 className="text-sm font-medium text-slate-200">Reconstructed attack path</h3>
<p className="text-xs text-slate-500">
- {data.nodeCount} node{data.nodeCount === 1 ? '' : 's'} · {data.edgeCount} edge{data.edgeCount === 1 ? '' : 's'} · depth ≤ 4
+ {data.nodeCount} node{data.nodeCount === 1 ? "" : "s"} · {data.edgeCount} edge
+ {data.edgeCount === 1 ? "" : "s"} · depth ≤ 4
</p>
</div>
<span className="inline-flex items-center gap-1.5 rounded-full bg-orange-500/10 px-2.5 py-0.5 text-xs font-medium text-orange-300 ring-1 ring-orange-500/30">
@@ -1401,23 +1475,17 @@ function AttackPathPanel({ caseId }: { caseId: string }) {
backend returns dense graphs (10s of nodes is normal). */}
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
{Object.entries(nodesByType).map(([type, nodes]) => (
- <div
- key={type}
- className="rounded-xl border border-slate-800/80 bg-slate-900/40 p-4"
- >
+ <div key={type} className="rounded-xl border border-slate-800/80 bg-slate-900/40 p-4">
<h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-400">
{type} ({nodes.length})
</h4>
<ul className="space-y-1.5">
{nodes.slice(0, 8).map((node) => (
- <li
- key={node.id}
- className="flex items-start gap-2 text-xs"
- >
+ <li key={node.id} className="flex items-start gap-2 text-xs">
<span className="mt-0.5 inline-block h-1.5 w-1.5 rounded-full bg-orange-400/60 shrink-0" />
<div className="min-w-0">
<p className="truncate font-mono text-slate-300">{node.label || node.id}</p>
- {typeof node.properties?.risk_score === 'number' && (
+ {typeof node.properties?.risk_score === "number" && (
<p className="text-[10px] text-slate-500">
risk score: {(node.properties.risk_score as number).toFixed(2)}
</p>
@@ -1426,9 +1494,7 @@ function AttackPathPanel({ caseId }: { caseId: string }) {
</li>
))}
{nodes.length > 8 && (
- <li className="text-[10px] italic text-slate-500">
- +{nodes.length - 8} more
- </li>
+ <li className="text-[10px] italic text-slate-500">+{nodes.length - 8} more</li>
)}
</ul>
</div>
@@ -1444,7 +1510,10 @@ function AttackPathPanel({ caseId }: { caseId: string }) {
</h4>
<ul className="space-y-1">
{data.edges.slice(0, 12).map((edge, i) => (
- <li key={`${edge.source}-${edge.target}-${i}`} className="flex items-center gap-2 text-[11px] font-mono">
+ <li
+ key={`${edge.source}-${edge.target}-${i}`}
+ className="flex items-center gap-2 text-[11px] font-mono"
+ >
<span className="truncate text-slate-300">{edge.source}</span>
<span className="rounded bg-slate-800 px-1.5 py-0.5 text-[10px] text-orange-300">
{edge.type}
@@ -1477,11 +1546,11 @@ function AttackPathPanel({ caseId }: { caseId: string }) {
// "yes, this is one campaign, not three independent things."
const CHAIN_SEVERITY_STYLES: Record<string, string> = {
- critical: 'bg-rose-500/15 text-rose-300 ring-rose-500/30',
- high: 'bg-orange-500/15 text-orange-300 ring-orange-500/30',
- medium: 'bg-amber-500/15 text-amber-300 ring-amber-500/30',
- low: 'bg-sky-500/15 text-sky-300 ring-sky-500/30',
- info: 'bg-slate-500/15 text-slate-300 ring-slate-500/30',
+ critical: "bg-rose-500/15 text-rose-300 ring-rose-500/30",
+ high: "bg-orange-500/15 text-orange-300 ring-orange-500/30",
+ medium: "bg-amber-500/15 text-amber-300 ring-amber-500/30",
+ low: "bg-sky-500/15 text-sky-300 ring-sky-500/30",
+ info: "bg-slate-500/15 text-slate-300 ring-slate-500/30",
};
function severityChipClass(severity: string): string {
@@ -1489,20 +1558,20 @@ function severityChipClass(severity: string): string {
}
const CHAIN_WINDOWS: ReadonlyArray<{ value: AttackChainWindow; label: string }> = [
- { value: '1h', label: '1 h' },
- { value: '6h', label: '6 h' },
- { value: '24h', label: '24 h' },
- { value: '72h', label: '72 h' },
- { value: '7d', label: '7 d' },
- { value: '30d', label: '30 d' },
+ { value: "1h", label: "1 h" },
+ { value: "6h", label: "6 h" },
+ { value: "24h", label: "24 h" },
+ { value: "72h", label: "72 h" },
+ { value: "7d", label: "7 d" },
+ { value: "30d", label: "30 d" },
];
const CHAIN_WINDOW_VALUES: ReadonlySet<AttackChainWindow> = new Set(
- CHAIN_WINDOWS.map((w) => w.value),
+ CHAIN_WINDOWS.map((w) => w.value)
);
function isAttackChainWindow(value: string | null | undefined): value is AttackChainWindow {
- return typeof value === 'string' && CHAIN_WINDOW_VALUES.has(value as AttackChainWindow);
+ return typeof value === "string" && CHAIN_WINDOW_VALUES.has(value as AttackChainWindow);
}
// Default lookback for first-time loads. Picked to be wide enough that a
@@ -1510,7 +1579,7 @@ function isAttackChainWindow(value: string | null | undefined): value is AttackC
// before, an active shift) renders chain links instead of the empty state
// on first paint; analysts who want a tighter view narrow with the
// selector, and the choice is persisted on the URL via `?window=…`.
-const DEFAULT_CHAIN_WINDOW: AttackChainWindow = '24h';
+const DEFAULT_CHAIN_WINDOW: AttackChainWindow = "24h";
function AttackChainPanel({ caseId }: { caseId: string }) {
// Mirror AttackPathPanel's guard: caseId can be empty during the brief window
@@ -1527,18 +1596,18 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
// router instance (which can be undefined in unit tests).
const searchParams = useSearchParams();
const initialWindow: AttackChainWindow = useMemo(() => {
- const raw = searchParams?.get('window') ?? null;
+ const raw = searchParams?.get("window") ?? null;
return isAttackChainWindow(raw) ? raw : DEFAULT_CHAIN_WINDOW;
}, [searchParams]);
const [windowParam, setWindowParam] = useState<AttackChainWindow>(initialWindow);
const handleWindowChange = useCallback((next: AttackChainWindow) => {
setWindowParam(next);
- if (typeof window === 'undefined') return;
+ if (typeof window === "undefined") return;
try {
const url = new URL(window.location.href);
- url.searchParams.set('window', next);
- window.history.replaceState({}, '', url.toString());
+ url.searchParams.set("window", next);
+ window.history.replaceState({}, "", url.toString());
} catch {
// Best-effort URL sync; a malformed location shouldn't break the
// panel. The state update above is the source of truth either way.
@@ -1546,9 +1615,9 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
}, []);
const { data, error, isLoading } = useSWR<AttackChainTimeline | null>(
- hasCaseId ? ['case:attack-chain', caseId, windowParam] : null,
+ hasCaseId ? ["case:attack-chain", caseId, windowParam] : null,
() => casesApi.getAttackChain(caseId, { window: windowParam }),
- { revalidateOnFocus: false, shouldRetryOnError: false },
+ { revalidateOnFocus: false, shouldRetryOnError: false }
);
if (!hasCaseId) {
@@ -1577,7 +1646,7 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
return (
<ErrorState
title="Failed to load attack chain"
- description={error instanceof Error ? error.message : 'Unknown error'}
+ description={error instanceof Error ? error.message : "Unknown error"}
/>
);
}
@@ -1591,7 +1660,12 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
<WindowSelector value={windowParam} onChange={handleWindowChange} />
<div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-slate-700/60 bg-slate-900/30 py-16 text-center">
<div className="mb-3 flex h-10 w-10 items-center justify-center rounded-full bg-rose-500/10 ring-1 ring-rose-500/30">
- <svg className="h-5 w-5 text-rose-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <svg
+ className="h-5 w-5 text-rose-300"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ >
<path
strokeLinecap="round"
strokeLinejoin="round"
@@ -1602,8 +1676,8 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
</div>
<p className="text-sm font-medium text-slate-300">No attack chain yet</p>
<p className="mt-1 max-w-md text-xs text-slate-500">
- An attack chain forms once two or more alerts in the {windowParam} window share
- entities or MITRE techniques. Link more alerts to the case or widen the window.
+ An attack chain forms once two or more alerts in the {windowParam} window share entities
+ or MITRE techniques. Link more alerts to the case or widen the window.
</p>
</div>
</div>
@@ -1614,13 +1688,13 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
// distinctly — analysts treat a 0.4 chain very differently from a 0.85 chain.
const confidencePct = Math.round(data.confidence * 100);
const confidenceBand =
- data.confidence >= 0.75 ? 'high' : data.confidence >= 0.5 ? 'medium' : 'low';
+ data.confidence >= 0.75 ? "high" : data.confidence >= 0.5 ? "medium" : "low";
const confidenceClass =
- confidenceBand === 'high'
- ? 'bg-emerald-500/15 text-emerald-300 ring-emerald-500/30'
- : confidenceBand === 'medium'
- ? 'bg-amber-500/15 text-amber-300 ring-amber-500/30'
- : 'bg-slate-500/15 text-slate-300 ring-slate-500/30';
+ confidenceBand === "high"
+ ? "bg-emerald-500/15 text-emerald-300 ring-emerald-500/30"
+ : confidenceBand === "medium"
+ ? "bg-amber-500/15 text-amber-300 ring-amber-500/30"
+ : "bg-slate-500/15 text-slate-300 ring-slate-500/30";
const nodeCount = data.entityGraph.nodes.length;
const edgeCount = data.entityGraph.edges.length;
@@ -1631,8 +1705,9 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
<div className="min-w-0">
<h3 className="text-sm font-medium text-slate-200">Reconstructed attack chain</h3>
<p className="text-xs text-slate-500">
- {data.chain.length} link{data.chain.length === 1 ? '' : 's'} · {nodeCount} entit
- {nodeCount === 1 ? 'y' : 'ies'} · {edgeCount} edge{edgeCount === 1 ? '' : 's'} · window {data.window}
+ {data.chain.length} link{data.chain.length === 1 ? "" : "s"} · {nodeCount} entit
+ {nodeCount === 1 ? "y" : "ies"} · {edgeCount} edge{edgeCount === 1 ? "" : "s"} · window{" "}
+ {data.window}
</p>
{data.chainSignature && (
<p className="mt-0.5 font-mono text-[10px] text-slate-600 truncate">
@@ -1643,8 +1718,8 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
<div className="flex items-center gap-2">
<span
className={clsx(
- 'inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium ring-1',
- confidenceClass,
+ "inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium ring-1",
+ confidenceClass
)}
title="Confidence is derived from average link score and chain length"
>
@@ -1662,21 +1737,20 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
const sevClass = severityChipClass(link.severity);
const isFirst = index === 0;
const dtMinutes = Math.round(link.dtSeconds / 60);
- const dtLabel =
- isFirst
- ? 'seed'
- : dtMinutes <= 0
- ? `+${Math.max(1, Math.round(link.dtSeconds))}s`
- : dtMinutes < 60
- ? `+${dtMinutes}m`
- : `+${(dtMinutes / 60).toFixed(1)}h`;
+ const dtLabel = isFirst
+ ? "seed"
+ : dtMinutes <= 0
+ ? `+${Math.max(1, Math.round(link.dtSeconds))}s`
+ : dtMinutes < 60
+ ? `+${dtMinutes}m`
+ : `+${(dtMinutes / 60).toFixed(1)}h`;
return (
<li key={link.alertId} className="relative">
{/* Dot anchored to the spine */}
<span
className={clsx(
- 'absolute -left-[26px] top-2 inline-block h-2.5 w-2.5 rounded-full ring-2 ring-slate-950',
- isFirst ? 'bg-rose-400' : 'bg-slate-500',
+ "absolute -left-[26px] top-2 inline-block h-2.5 w-2.5 rounded-full ring-2 ring-slate-950",
+ isFirst ? "bg-rose-400" : "bg-slate-500"
)}
/>
<div className="rounded-xl border border-slate-800/80 bg-slate-900/40 p-4">
@@ -1685,8 +1759,8 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
<div className="flex flex-wrap items-center gap-2">
<span
className={clsx(
- 'inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide ring-1',
- sevClass,
+ "inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide ring-1",
+ sevClass
)}
>
{link.severity}
@@ -1701,17 +1775,23 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
{link.connectorType}
</span>
)}
- <span className="text-[10px] font-mono text-slate-500" title="time since previous link">
+ <span
+ className="text-[10px] font-mono text-slate-500"
+ title="time since previous link"
+ >
Δt {dtLabel}
</span>
</div>
- <p className="mt-1.5 text-sm font-medium text-slate-200 truncate" title={link.title}>
+ <p
+ className="mt-1.5 text-sm font-medium text-slate-200 truncate"
+ title={link.title}
+ >
{link.title}
</p>
<p className="mt-0.5 text-[11px] text-slate-500">
{(() => {
try {
- return `${format(new Date(link.eventTime), 'MMM d, HH:mm:ss')} · ${formatDistanceToNow(new Date(link.eventTime), { addSuffix: true })}`;
+ return `${format(new Date(link.eventTime), "MMM d, HH:mm:ss")} · ${formatDistanceToNow(new Date(link.eventTime), { addSuffix: true })}`;
} catch {
return link.eventTime;
}
@@ -1733,9 +1813,9 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
<div className="mt-3 flex flex-wrap gap-1.5">
{link.sharedEntities.slice(0, 6).map((entity, i) => (
<span
- key={`${entity.kind ?? 'entity'}-${entity.value ?? i}`}
+ key={`${entity.kind ?? "entity"}-${entity.value ?? i}`}
className="inline-flex items-center gap-1 rounded bg-slate-800/70 px-1.5 py-0.5 text-[10px] font-mono text-slate-300 ring-1 ring-slate-700/60"
- title={`Shared with previous link: ${entity.kind ?? ''}`}
+ title={`Shared with previous link: ${entity.kind ?? ""}`}
>
<span className="text-slate-500">{entity.kind}</span>
<span>{entity.value}</span>
@@ -1784,7 +1864,8 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
Entities in chain ({data.entityGraph.nodes.length})
</h4>
<span className="text-[10px] text-slate-500">
- {data.entityGraph.edges.length} connection{data.entityGraph.edges.length === 1 ? '' : 's'}
+ {data.entityGraph.edges.length} connection
+ {data.entityGraph.edges.length === 1 ? "" : "s"}
</span>
</div>
<ul className="mt-2 flex flex-wrap gap-1.5">
@@ -1808,16 +1889,15 @@ function AttackChainPanel({ caseId }: { caseId: string }) {
)}
<p className="text-[10px] text-slate-600">
- Chain computed at{' '}
+ Chain computed at{" "}
{(() => {
try {
- return format(new Date(data.generatedAt), 'MMM d, HH:mm:ss');
+ return format(new Date(data.generatedAt), "MMM d, HH:mm:ss");
} catch {
return data.generatedAt;
}
- })()}{' '}
- · seed alert{' '}
- <span className="font-mono">{data.seedAlertId}</span>
+ })()}{" "}
+ · seed alert <span className="font-mono">{data.seedAlertId}</span>
</p>
</div>
);
@@ -1842,10 +1922,10 @@ function WindowSelector({
type="button"
onClick={() => onChange(opt.value)}
className={clsx(
- 'rounded px-2 py-1 text-[11px] font-medium transition',
+ "rounded px-2 py-1 text-[11px] font-medium transition",
value === opt.value
- ? 'bg-slate-800 text-slate-100 ring-1 ring-slate-700/60'
- : 'text-slate-400 hover:text-slate-200',
+ ? "bg-slate-800 text-slate-100 ring-1 ring-slate-700/60"
+ : "text-slate-400 hover:text-slate-200"
)}
aria-pressed={value === opt.value}
>
@@ -1856,7 +1936,11 @@ function WindowSelector({
);
}
-function AuditLogPreview({ log }: { log: Array<{ kind: string; agent: string; summary: string }> }) {
+function AuditLogPreview({
+ log,
+}: {
+ log: Array<{ kind: string; agent: string; summary: string }>;
+}) {
return (
<ul className="p-4 space-y-1.5">
{log.map((entry, i) => (
@@ -1873,18 +1957,18 @@ function AuditLogPreview({ log }: { log: Array<{ kind: string; agent: string; su
// ─── Live steps feed (real-time WebSocket updates) ────────────────────────────
const AGENT_LABELS: Record<string, string> = {
- recon: 'recon',
- forensic: 'forensic',
- responder: 'responder',
- report: 'report',
- completed: 'done',
- error: 'error',
+ recon: "recon",
+ forensic: "forensic",
+ responder: "responder",
+ report: "report",
+ completed: "done",
+ error: "error",
};
function LiveStepsFeed({ steps }: { steps: LiveStep[] }) {
const bottomRef = useRef<HTMLDivElement>(null);
useEffect(() => {
- bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
+ bottomRef.current?.scrollIntoView({ behavior: "smooth" });
}, [steps.length]);
return (
@@ -1910,8 +1994,15 @@ function LiveStepsFeed({ steps }: { steps: LiveStep[] }) {
</div>
<p className="text-[11px] text-slate-400 mt-0.5 leading-relaxed">{step.summary}</p>
</div>
- <span className="shrink-0 text-[9px] text-slate-600 font-mono mt-0.5" suppressHydrationWarning>
- {new Date(step.ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
+ <span
+ className="shrink-0 text-[9px] text-slate-600 font-mono mt-0.5"
+ suppressHydrationWarning
+ >
+ {new Date(step.ts).toLocaleTimeString([], {
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ })}
</span>
</li>
);
@@ -1943,7 +2034,7 @@ function ReportPanel({
try {
await casesApi.downloadReportPdf(caseId, runId);
} catch (err) {
- setPdfError(err instanceof Error ? err.message : 'PDF download failed');
+ setPdfError(err instanceof Error ? err.message : "PDF download failed");
} finally {
setPdfDownloading(false);
}
@@ -1961,16 +2052,18 @@ function ReportPanel({
return (
<div className="rounded-xl border border-slate-800/80 bg-slate-900/40">
<div className="flex items-center justify-between border-b border-slate-800/80 px-4 py-2">
- <h3 className="text-xs font-semibold uppercase tracking-wide text-slate-300">Incident Report</h3>
+ <h2 className="text-xs font-semibold uppercase tracking-wide text-slate-300">
+ Incident Report
+ </h2>
<div className="flex items-center gap-3">
{/* Download Markdown */}
<button
onClick={() => {
- const blob = new Blob([markdown], { type: 'text/markdown' });
+ const blob = new Blob([markdown], { type: "text/markdown" });
const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
+ const a = document.createElement("a");
a.href = url;
- a.download = 'incident-report.md';
+ a.download = "incident-report.md";
a.click();
URL.revokeObjectURL(url);
}}
@@ -1984,10 +2077,10 @@ function ReportPanel({
onClick={handleDownloadPdf}
disabled={pdfDownloading}
className={clsx(
- 'flex items-center gap-1 rounded px-2 py-0.5 text-[11px] font-medium transition-colors',
+ "flex items-center gap-1 rounded px-2 py-0.5 text-[11px] font-medium transition-colors",
pdfDownloading
- ? 'cursor-not-allowed text-slate-500'
- : 'bg-indigo-600/20 text-indigo-300 hover:bg-indigo-600/40',
+ ? "cursor-not-allowed text-slate-500"
+ : "bg-indigo-600/20 text-indigo-300 hover:bg-indigo-600/40"
)}
>
{pdfDownloading ? (
@@ -2016,11 +2109,21 @@ function ReportPanel({
// ─── Tiny presentational helpers ──────────────────────────────────────────────
-function Meta({ label, value, suppressHydrationWarning: shw }: { label: string; value: string; suppressHydrationWarning?: boolean }) {
+function Meta({
+ label,
+ value,
+ suppressHydrationWarning: shw,
+}: {
+ label: string;
+ value: string;
+ suppressHydrationWarning?: boolean;
+}) {
return (
<div>
<p className="text-[11px] uppercase tracking-wide text-slate-500">{label}</p>
- <p className="mt-0.5 text-sm text-slate-200" suppressHydrationWarning={shw}>{value}</p>
+ <p className="mt-0.5 text-sm text-slate-200" suppressHydrationWarning={shw}>
+ {value}
+ </p>
</div>
);
}
@@ -2037,9 +2140,11 @@ function Panel({
return (
<div className="overflow-hidden rounded-xl border border-slate-800/80 bg-slate-900/40">
<div className="flex items-center justify-between border-b border-slate-800/80 px-3 py-2">
- <h3 className="text-xs font-semibold uppercase tracking-wide text-slate-300">
- {title}
- </h3>
+ {/* `h2`, not `h3`. The case title above is the page's `h1` and a
+ panel is its direct child, so `h3` skipped a level -- which is
+ what a screen-reader user navigating by heading reads as a
+ missing section. The size is a class, not the tag. */}
+ <h2 className="text-xs font-semibold uppercase tracking-wide text-slate-300">{title}</h2>
{actions}
</div>
<div className="p-3">{children}</div>
diff --git a/apps/web/src/components/cases/CasesView.tsx b/apps/web/src/components/cases/CasesView.tsx
index cb770cb92..c6198919a 100644
--- a/apps/web/src/components/cases/CasesView.tsx
+++ b/apps/web/src/components/cases/CasesView.tsx
@@ -1,61 +1,66 @@
-'use client';
+"use client";
-import { useState } from 'react';
-import { AnalystWorkload } from './AnalystWorkload';
-import useSWR from 'swr';
-import Link from 'next/link';
-import toast from 'react-hot-toast';
-import { casesApi, type Case, type CasesResponse } from '@/lib/api';
-import { clsx } from 'clsx';
-import { format } from 'date-fns';
-import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';
-import { SavedViewsBar } from '@/components/saved-views/SavedViewsBar';
-import { demoFallback } from '@/lib/demoFallback';
+import { useState } from "react";
+import { AnalystWorkload } from "./AnalystWorkload";
+import useSWR from "swr";
+import Link from "next/link";
+import toast from "react-hot-toast";
+import { casesApi, type Case, type CasesResponse } from "@/lib/api";
+import { clsx } from "clsx";
+import { format } from "date-fns";
+import { EmptyState, EmptyStateIcons } from "@/components/ui/EmptyState";
+import { SavedViewsBar } from "@/components/saved-views/SavedViewsBar";
+import { demoFallback } from "@/lib/demoFallback";
// WS-F3 — the saved-views API stores an opaque filter blob per view, so we
// flatten the three filter slices Cases tracks today into a single shape the
// bar can snapshot and replay. Nothing else in the view consumes this — it's
// purely the wire format between the bar and the local state setters.
type CaseFilterSnapshot = {
- status: Case['status'] | 'all';
- severity: Case['severity'] | 'all';
+ status: Case["status"] | "all";
+ severity: Case["severity"] | "all";
search: string;
};
// ─── Mock Data ────────────────────────────────────────────────────────────────
// Deterministic mock data — no Date.now() or Math.random() to avoid SSR hydration mismatches.
-const MOCK_CASE_BASE = new Date('2026-05-06T12:00:00Z').getTime();
+const MOCK_CASE_BASE = new Date("2026-05-06T12:00:00Z").getTime();
const MOCK_CASES: Case[] = Array.from({ length: 18 }, (_, i) => ({
id: `case-${1000 + i}`,
title: [
- 'Ransomware incident on finance workstations',
- 'Suspected APT lateral movement campaign',
- 'Credential stuffing attack against portal',
- 'Data exfiltration via cloud storage abuse',
- 'Supply chain compromise investigation',
- 'Insider threat: anomalous data access',
- 'Phishing campaign targeting executives',
- 'Cryptominer on dev server cluster',
- 'Brute-force attack on VPN endpoints',
- 'Unauthorized cloud resource provisioning',
+ "Ransomware incident on finance workstations",
+ "Suspected APT lateral movement campaign",
+ "Credential stuffing attack against portal",
+ "Data exfiltration via cloud storage abuse",
+ "Supply chain compromise investigation",
+ "Insider threat: anomalous data access",
+ "Phishing campaign targeting executives",
+ "Cryptominer on dev server cluster",
+ "Brute-force attack on VPN endpoints",
+ "Unauthorized cloud resource provisioning",
][i % 10],
- status: (['open', 'in_progress', 'resolved', 'closed'] as Case['status'][])[i % 4],
- severity: (['critical', 'high', 'medium', 'low'] as Case['severity'][])[i % 4],
- assignee: ['[email protected]', '[email protected]', '[email protected]', undefined][i % 4],
+ status: (["open", "in_progress", "resolved", "closed"] as Case["status"][])[i % 4],
+ severity: (["critical", "high", "medium", "low"] as Case["severity"][])[i % 4],
+ assignee: ["[email protected]", "[email protected]", "[email protected]", undefined][i % 4],
alertCount: ((i * 13 + 7) % 30) + 1,
createdAt: new Date(MOCK_CASE_BASE - i * 7200000).toISOString(),
updatedAt: new Date(MOCK_CASE_BASE - i * 1800000).toISOString(),
- tags: [['ransomware', 'finance'], ['apt', 'lateral'], ['credential', 'portal'], ['exfil', 'cloud']][i % 4],
+ tags: [
+ ["ransomware", "finance"],
+ ["apt", "lateral"],
+ ["credential", "portal"],
+ ["exfil", "cloud"],
+ ][i % 4],
}));
// ─── Helpers ──────────────────────────────────────────────────────────────────
const SEVERITY_CONFIG = {
- critical: { label: 'Critical', className: 'text-red-400 bg-red-500/10 border-red-500/20' },
- high: { label: 'High', className: 'text-orange-400 bg-orange-500/10 border-orange-500/20' },
- medium: { label: 'Medium', className: 'text-yellow-400 bg-yellow-500/10 border-yellow-500/20' },
- low: { label: 'Low', className: 'text-blue-400 bg-blue-500/10 border-blue-500/20' },
+ critical: { label: "Critical", className: "text-red-400 bg-red-500/10 border-red-500/20" },
+ high: { label: "High", className: "text-orange-400 bg-orange-500/10 border-orange-500/20" },
+ medium: { label: "Medium", className: "text-yellow-400 bg-yellow-500/10 border-yellow-500/20" },
+ low: { label: "Low", className: "text-blue-400 bg-blue-500/10 border-blue-500/20" },
};
// Keyed on the six states `aisoc_cases` permits. It used to name `open`,
@@ -63,16 +68,37 @@ const SEVERITY_CONFIG = {
// the four a case actually passes through, so every real row fell through to
// the `?? STATUS_CONFIG.open` fallback below and the list showed every case
// as "Open" whatever it was.
-const STATUS_CONFIG: Record<
- Case['status'],
- { label: string; className: string; dot: string }
-> = {
- new: { label: 'New', className: 'text-gray-300 bg-gray-700/50 border-gray-600/50', dot: 'bg-gray-400' },
- triaged: { label: 'Triaged', className: 'text-sky-300 bg-sky-500/10 border-sky-500/20', dot: 'bg-sky-400' },
- investigating: { label: 'Investigating', className: 'text-blue-300 bg-blue-500/10 border-blue-500/20', dot: 'bg-blue-400 animate-pulse' },
- contained: { label: 'Contained', className: 'text-amber-300 bg-amber-500/10 border-amber-500/20', dot: 'bg-amber-400' },
- resolved: { label: 'Resolved', className: 'text-green-300 bg-green-500/10 border-green-500/20', dot: 'bg-green-400' },
- closed: { label: 'Closed', className: 'text-gray-500 bg-gray-800/50 border-gray-700/50', dot: 'bg-gray-600' },
+const STATUS_CONFIG: Record<Case["status"], { label: string; className: string; dot: string }> = {
+ new: {
+ label: "New",
+ className: "text-gray-300 bg-gray-700/50 border-gray-600/50",
+ dot: "bg-gray-400",
+ },
+ triaged: {
+ label: "Triaged",
+ className: "text-sky-300 bg-sky-500/10 border-sky-500/20",
+ dot: "bg-sky-400",
+ },
+ investigating: {
+ label: "Investigating",
+ className: "text-blue-300 bg-blue-500/10 border-blue-500/20",
+ dot: "bg-blue-400 animate-pulse",
+ },
+ contained: {
+ label: "Contained",
+ className: "text-amber-300 bg-amber-500/10 border-amber-500/20",
+ dot: "bg-amber-400",
+ },
+ resolved: {
+ label: "Resolved",
+ className: "text-green-300 bg-green-500/10 border-green-500/20",
+ dot: "bg-green-400",
+ },
+ closed: {
+ label: "Closed",
+ className: "text-gray-500 bg-gray-800/50 border-gray-700/50",
+ dot: "bg-gray-600",
+ },
};
// ─── Case Card ────────────────────────────────────────────────────────────────
@@ -82,7 +108,7 @@ function CaseCard({ c }: { c: Case }) {
// Defensive: if normalization missed an unexpected status string, fall back
// to "open" styling so the entire list never blanks the page.
const sts = STATUS_CONFIG[c.status] ?? STATUS_CONFIG.new;
- const displayId = c.caseNumber ?? `${c.id ?? ''}`.slice(-6);
+ const displayId = c.caseNumber ?? `${c.id ?? ""}`.slice(-6);
const detailHref = `/cases/${encodeURIComponent(c.caseNumber ?? c.id)}`;
return (
@@ -91,15 +117,24 @@ function CaseCard({ c }: { c: Case }) {
<div className="flex items-start justify-between gap-3">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2">
- <span className={clsx('text-xs font-medium px-2 py-0.5 rounded border', sev.className)}>
+ <span
+ className={clsx("text-xs font-medium px-2 py-0.5 rounded border", sev.className)}
+ >
{sev.label}
</span>
- <span className={clsx('flex items-center gap-1 text-xs font-medium px-2 py-0.5 rounded border', sts.className)}>
- <span className={clsx('w-1.5 h-1.5 rounded-full', sts.dot)} />
+ <span
+ className={clsx(
+ "flex items-center gap-1 text-xs font-medium px-2 py-0.5 rounded border",
+ sts.className
+ )}
+ >
+ <span className={clsx("w-1.5 h-1.5 rounded-full", sts.dot)} />
{sts.label}
</span>
</div>
- <h3 className="text-sm font-medium text-gray-200 group-hover:text-white truncate">{c.title}</h3>
+ <h3 className="text-sm font-medium text-gray-200 group-hover:text-white truncate">
+ {c.title}
+ </h3>
<div className="flex items-center gap-3 mt-2">
<span className="text-xs text-gray-500">#{displayId}</span>
<span className="text-xs text-gray-500">·</span>
@@ -107,17 +142,22 @@ function CaseCard({ c }: { c: Case }) {
{c.assignee && (
<>
<span className="text-xs text-gray-500">·</span>
- <span className="text-xs text-gray-400">{c.assignee.split('@')[0]}</span>
+ <span className="text-xs text-gray-400">{c.assignee.split("@")[0]}</span>
</>
)}
</div>
</div>
<div className="text-right shrink-0 flex flex-col items-end gap-2">
- <p className="text-xs text-gray-500" suppressHydrationWarning>{format(new Date(c.createdAt), 'MMM dd, HH:mm')}</p>
+ <p className="text-xs text-gray-500" suppressHydrationWarning>
+ {format(new Date(c.createdAt), "MMM dd, HH:mm")}
+ </p>
{c.tags && c.tags.length > 0 && (
<div className="flex flex-wrap gap-1 justify-end">
{c.tags.slice(0, 2).map((tag) => (
- <span key={tag} className="text-xs text-gray-500 bg-gray-800 px-1.5 py-0.5 rounded">
+ <span
+ key={tag}
+ className="text-xs text-gray-500 bg-gray-800 px-1.5 py-0.5 rounded"
+ >
{tag}
</span>
))}
@@ -126,12 +166,17 @@ function CaseCard({ c }: { c: Case }) {
<button
onClick={(e) => {
e.preventDefault();
- toast.success('Incident report generated — downloading PDF');
+ toast.success("Incident report generated — downloading PDF");
}}
className="flex items-center gap-1 text-xs text-gray-500 hover:text-blue-400 transition-colors opacity-0 group-hover:opacity-100"
>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
+ />
</svg>
Export Report
</button>
@@ -144,12 +189,12 @@ function CaseCard({ c }: { c: Case }) {
// ─── Main View ────────────────────────────────────────────────────────────────
-type FilterStatus = Case['status'] | 'all';
+type FilterStatus = Case["status"] | "all";
export function CasesView() {
- const [statusFilter, setStatusFilter] = useState<FilterStatus>('all');
- const [severityFilter, setSeverityFilter] = useState<Case['severity'] | 'all'>('all');
- const [search, setSearch] = useState('');
+ const [statusFilter, setStatusFilter] = useState<FilterStatus>("all");
+ const [severityFilter, setSeverityFilter] = useState<Case["severity"] | "all">("all");
+ const [search, setSearch] = useState("");
// This view took an `initialCases` prop fed by a server-side fetch in
// `cases/page.tsx`. That fetch sent no credential and a build-time tenant
@@ -166,9 +211,13 @@ export function CasesView() {
pageSize: MOCK_CASES.length,
});
- const { data: casesData, error, isLoading } = useSWR(
- ['cases', statusFilter, severityFilter],
- () => casesApi.list({ status: statusFilter !== 'all' ? statusFilter : undefined }),
+ const {
+ data: casesData,
+ error,
+ isLoading,
+ } = useSWR(
+ ["cases", statusFilter, severityFilter],
+ () => casesApi.list({ status: statusFilter !== "all" ? statusFilter : undefined }),
{
fallbackData: sampleCases,
revalidateOnMount: true,
@@ -177,7 +226,7 @@ export function CasesView() {
const cases = (casesData?.cases || []).filter((c) => {
if (search && !c.title.toLowerCase().includes(search.toLowerCase())) return false;
- if (severityFilter !== 'all' && c.severity !== severityFilter) return false;
+ if (severityFilter !== "all" && c.severity !== severityFilter) return false;
return true;
});
@@ -192,10 +241,10 @@ export function CasesView() {
? { all: null, new: null, investigating: null, resolved: null, closed: null }
: {
all: allCases.length,
- new: allCases.filter(c => c.status === 'new').length,
- investigating: allCases.filter(c => c.status === 'investigating').length,
- resolved: allCases.filter(c => c.status === 'resolved').length,
- closed: allCases.filter(c => c.status === 'closed').length,
+ new: allCases.filter((c) => c.status === "new").length,
+ investigating: allCases.filter((c) => c.status === "investigating").length,
+ resolved: allCases.filter((c) => c.status === "resolved").length,
+ closed: allCases.filter((c) => c.status === "closed").length,
};
return (
@@ -204,7 +253,9 @@ export function CasesView() {
<div className="flex items-center justify-between">
<div>
<h1 className="text-xl font-semibold text-gray-100">Cases</h1>
- <p className="text-sm text-gray-500 mt-0.5">Manage security investigations and incidents</p>
+ <p className="text-sm text-gray-500 mt-0.5">
+ Manage security investigations and incidents
+ </p>
</div>
<div className="flex items-center gap-2">
<button
@@ -213,7 +264,12 @@ export function CasesView() {
className="flex items-center gap-2 bg-gray-700 text-gray-400 text-sm font-medium px-4 py-2 rounded-lg cursor-not-allowed select-none"
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M12 4v16m8-8H4"
+ />
</svg>
New Case
</button>
@@ -237,21 +293,28 @@ export function CasesView() {
anything. `triaged` and `contained` show on each row rather than as
their own tab.
*/}
- {(['all', 'new', 'investigating', 'resolved', 'closed'] as const).map((s) => {
+ {(["all", "new", "investigating", "resolved", "closed"] as const).map((s) => {
return (
<button
key={s}
onClick={() => setStatusFilter(s)}
className={clsx(
- 'bg-gray-900/60 border rounded-xl p-4 text-left transition-all',
- statusFilter === s ? 'border-blue-500/50 bg-blue-500/5' : 'border-gray-800/60 hover:border-gray-700'
+ "bg-gray-900/60 border rounded-xl p-4 text-left transition-all",
+ statusFilter === s
+ ? "border-blue-500/50 bg-blue-500/5"
+ : "border-gray-800/60 hover:border-gray-700"
)}
>
- <p className={clsx('text-2xl font-bold', statCounts[s] === null ? 'text-gray-600' : 'text-gray-100')}>
- {statCounts[s] === null ? '—' : statCounts[s]}
+ <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('_', ' ')}
+ {s === "all" ? "All Cases" : s.replace("_", " ")}
</p>
</button>
);
@@ -272,17 +335,27 @@ export function CasesView() {
search,
}}
onApply={(applied) => {
- setStatusFilter(applied.status ?? 'all');
- setSeverityFilter(applied.severity ?? 'all');
- setSearch(applied.search ?? '');
+ setStatusFilter(applied.status ?? "all");
+ setSeverityFilter(applied.severity ?? "all");
+ setSearch(applied.search ?? "");
}}
/>
{/* Filters */}
<div className="flex items-center gap-3">
<div className="relative flex-1 max-w-sm">
- <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
+ <svg
+ className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
+ />
</svg>
<input
type="text"
@@ -293,9 +366,15 @@ export function CasesView() {
/>
</div>
+ {/* The visible text is inside the options, so a screen reader
+ announces the current value with no idea what it selects.
+ `aria-label` rather than a visible `<label>`: the control sits
+ in a filter row whose meaning is carried by the options
+ themselves for a sighted reader. */}
<select
+ aria-label="Filter cases by severity"
value={severityFilter}
- onChange={(e) => setSeverityFilter(e.target.value as Case['severity'] | 'all')}
+ onChange={(e) => setSeverityFilter(e.target.value as Case["severity"] | "all")}
className="bg-gray-900/60 border border-gray-800 rounded-lg text-sm text-gray-400 px-3 py-2 focus:outline-none focus:border-blue-500/50"
>
<option value="all">All Severities</option>
@@ -312,9 +391,13 @@ export function CasesView() {
measured-and-none rather than not-measured. */}
<span
className="text-xs text-gray-500"
- title={countsUnknown ? 'The case service has not answered, so there is no count to show.' : undefined}
+ title={
+ countsUnknown
+ ? "The case service has not answered, so there is no count to show."
+ : undefined
+ }
>
- {countsUnknown ? '— cases' : `${cases.length} cases`}
+ {countsUnknown ? "— cases" : `${cases.length} cases`}
</span>
</div>
@@ -333,7 +416,7 @@ export function CasesView() {
// WS-F5 — distinguish "filter miss" from "no cases ever". The former
// gets a "clear filters" CTA; the latter explains what cases are and
// where they come from so a brand-new tenant doesn't think it's broken.
- statusFilter !== 'all' || severityFilter !== 'all' || search ? (
+ statusFilter !== "all" || severityFilter !== "all" || search ? (
<EmptyState
icon={EmptyStateIcons.search}
title="No cases match these filters"
@@ -341,9 +424,9 @@ export function CasesView() {
action={
<button
onClick={() => {
- setStatusFilter('all');
- setSeverityFilter('all');
- setSearch('');
+ setStatusFilter("all");
+ setSeverityFilter("all");
+ setSearch("");
}}
className="text-xs px-3 py-1.5 rounded-md border border-blue-500/40 bg-blue-500/10 text-blue-300 hover:bg-blue-500/20 transition-colors"
>
@@ -360,7 +443,9 @@ export function CasesView() {
)
) : (
<div className="grid grid-cols-1 gap-3">
- {cases.map((c) => <CaseCard key={c.id} c={c} />)}
+ {cases.map((c) => (
+ <CaseCard key={c.id} c={c} />
+ ))}
</div>
)}
</div>
diff --git a/apps/web/src/test/a11y.test.tsx b/apps/web/src/test/a11y.test.tsx
index 241ce899e..d56c152ba 100644
--- a/apps/web/src/test/a11y.test.tsx
+++ b/apps/web/src/test/a11y.test.tsx
@@ -24,21 +24,21 @@
* itself, which gives us a single place to tune contrast for both themes.
*/
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { cleanup, render } from '@testing-library/react';
-import { axe } from 'vitest-axe';
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render } from "@testing-library/react";
+import { axe } from "vitest-axe";
// Shared mocks ----------------------------------------------------------
// Parity 4.7. The operator views below fetch through SWR, and without
// this they would render a loading spinner: axe would pass on a spinner
// and the suite would report coverage it does not have.
-vi.mock('swr', () => ({
+vi.mock("swr", () => ({
// The key may be a string or a tuple: the Investigation Rail keys on
// `['alerts', id, 'rail']`, and reading only the string form gave it
// `undefined`, so it rendered its error state and axe passed on that.
default: (key: unknown) => ({
- data: swrFixture(Array.isArray(key) ? key.join('/') : typeof key === 'string' ? key : ''),
+ data: swrFixture(Array.isArray(key) ? key.join("/") : typeof key === "string" ? key : ""),
error: undefined,
isLoading: false,
mutate: vi.fn(),
@@ -47,7 +47,7 @@ vi.mock('swr', () => ({
useSWRConfig: () => ({ mutate: vi.fn() }),
}));
-vi.mock('next/link', () => ({
+vi.mock("next/link", () => ({
default: ({
children,
href,
@@ -62,17 +62,21 @@ vi.mock('next/link', () => ({
),
}));
-const pathnameMock = vi.fn(() => '/dashboard');
+const pathnameMock = vi.fn(() => "/dashboard");
-vi.mock('next/navigation', () => ({
+vi.mock("next/navigation", () => ({
usePathname: () => pathnameMock(),
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
+ // `CaseWorkspace` reads `?tab=` to deep-link a workspace tab. Without
+ // this it throws before rendering anything and axe would be handed an
+ // empty container.
+ useSearchParams: () => new URLSearchParams(""),
}));
// framer-motion's `motion.x` returns a real DOM tag and forwards refs. The
// production build pulls in IntersectionObserver and animation timers we
// don't need for static-DOM accessibility checks, so stub it out.
-vi.mock('framer-motion', () => {
+vi.mock("framer-motion", () => {
const factory = (Tag: React.ElementType) =>
function MotionStub(props: Record<string, unknown>) {
const { children, ...rest } = props as {
@@ -92,11 +96,11 @@ vi.mock('framer-motion', () => {
};
});
-vi.mock('react-hot-toast', () => ({
+vi.mock("react-hot-toast", () => ({
default: { error: vi.fn(), success: vi.fn() },
}));
-vi.mock('@/lib/api', () => ({
+vi.mock("@/lib/api", () => ({
authApi: {
isAuthenticated: () => false,
login: vi.fn(),
@@ -108,32 +112,45 @@ vi.mock('@/lib/api', () => ({
getHistory: vi.fn(() => Promise.resolve([])),
},
tenantsApi: {
- me: vi.fn(() => Promise.reject(new Error('unauthenticated'))),
+ me: vi.fn(() => Promise.reject(new Error("unauthenticated"))),
},
msspApi: {
listChildren: vi.fn(() => Promise.resolve([])),
},
- getActiveTenantId: vi.fn(() => ''),
+ casesApi: {
+ list: vi.fn(() => Promise.resolve({ cases: [], total: 0 })),
+ get: vi.fn(() => Promise.resolve(null)),
+ getTimeline: vi.fn(() => Promise.resolve({ events: [] })),
+ update: vi.fn(),
+ },
+ graphApi: {
+ attackPath: vi.fn(() => Promise.resolve(null)),
+ },
+ realtimeApi: {
+ subscribe: vi.fn(() => () => {}),
+ },
+ apiFetch: vi.fn(() => Promise.resolve(null)),
+ getActiveTenantId: vi.fn(() => ""),
setActiveTenantId: vi.fn(),
}));
// Sidebar reads version from package.json — mock it so the import doesn't
// fail when running outside the actual apps/web working directory.
-vi.mock('../../../package.json', () => ({
- default: { version: '0.0.0-test' },
+vi.mock("../../../package.json", () => ({
+ default: { version: "0.0.0-test" },
}));
// Component imports go after the mocks so the mocks are resolved first.
-import { Hero } from '../components/landing/Hero';
-import { StartHero } from '../components/onboarding/StartHero';
-import { ThemeToggle } from '../components/theme/ThemeToggle';
-import { ThemeProvider } from '../components/theme/ThemeProvider';
-import { TopBar } from '../components/layout/TopBar';
-import { TimeWindowProvider } from '../components/layout/TimeWindowProvider';
-import { TenantProvider } from '../components/layout/TenantProvider';
-import { Sidebar } from '../components/layout/Sidebar';
-import { EmptyState } from '../components/ui/EmptyState';
-import { CopilotDock } from '../components/copilot/CopilotDock';
+import { Hero } from "../components/landing/Hero";
+import { StartHero } from "../components/onboarding/StartHero";
+import { ThemeToggle } from "../components/theme/ThemeToggle";
+import { ThemeProvider } from "../components/theme/ThemeProvider";
+import { TopBar } from "../components/layout/TopBar";
+import { TimeWindowProvider } from "../components/layout/TimeWindowProvider";
+import { TenantProvider } from "../components/layout/TenantProvider";
+import { Sidebar } from "../components/layout/Sidebar";
+import { EmptyState } from "../components/ui/EmptyState";
+import { CopilotDock } from "../components/copilot/CopilotDock";
afterEach(() => {
cleanup();
@@ -144,7 +161,7 @@ afterEach(() => {
// is the single source of truth for contrast and is reviewed manually.
const axeOptions = {
rules: {
- 'color-contrast': { enabled: false },
+ "color-contrast": { enabled: false },
},
};
@@ -152,78 +169,124 @@ const axeOptions = {
* empty state. Deliberately small: this suite measures accessibility, not
* data handling, and a large fixture would make a failure hard to read. */
function swrFixture(key: string): unknown {
- if (key.startsWith('alerts/') || (key.includes('/alerts/') && !key.endsWith('/alerts'))) {
+ if (key.startsWith("alerts/") || (key.includes("/alerts/") && !key.endsWith("/alerts"))) {
return {
- id: 'a1',
- title: 'Encoded PowerShell from Office',
- severity: 'high',
- status: 'new',
+ id: "a1",
+ title: "Encoded PowerShell from Office",
+ severity: "high",
+ status: "new",
confidence: 72,
// camelCase: `normalizeAlert` has already run by the time the rail
// reads this, so the fixture has to be the normalised shape rather
// than the API's.
- createdAt: '2026-10-01T12:00:00Z',
+ createdAt: "2026-10-01T12:00:00Z",
riskScore: 68,
- narrative: 'A macro-enabled document spawned an encoded PowerShell command.',
- entities: [{ group: 'host', kind: 'hostname', value: 'WIN-FIN-01', label: 'WIN-FIN-01' }],
- timeline: [{ id: 'e1', timestamp: '2026-10-01T12:00:00Z', title: 'Process created' }],
- recommended_actions: [{ id: 'r1', title: 'Isolate the host', risk: 'high' }],
+ narrative: "A macro-enabled document spawned an encoded PowerShell command.",
+ entities: [{ group: "host", kind: "hostname", value: "WIN-FIN-01", label: "WIN-FIN-01" }],
+ timeline: [{ id: "e1", timestamp: "2026-10-01T12:00:00Z", title: "Process created" }],
+ recommended_actions: [{ id: "r1", title: "Isolate the host", risk: "high" }],
};
}
- if (key.endsWith('/alerts') || key.includes('/alerts?')) {
+ if (key.endsWith("/alerts") || key.includes("/alerts?")) {
return {
items: [
{
- id: 'a1',
- title: 'Encoded PowerShell from Office',
- severity: 'high',
- status: 'new',
- created_at: '2026-10-01T12:00:00Z',
- connector_type: 'CrowdStrike Falcon',
+ id: "a1",
+ title: "Encoded PowerShell from Office",
+ severity: "high",
+ status: "new",
+ created_at: "2026-10-01T12:00:00Z",
+ connector_type: "CrowdStrike Falcon",
},
],
total: 1,
};
}
- if (key.includes('/cases/')) {
+ // `CasesView` keys on `['cases', status, severity]`, so the joined form
+ // is `cases/all/all` rather than a path. Matching on a leading segment
+ // rather than on a slash-wrapped fragment is what makes both the list
+ // and the single-case keys reachable.
+ // `CasesView` keys on `['cases', status, severity]`, so the joined form
+ // is `cases/all/all` rather than a path. Matching on a leading segment
+ // rather than on a slash-wrapped fragment is what makes both the list
+ // and the single-case keys reachable.
+ //
+ // camelCase throughout, like the alert fixture above: the API's
+ // snake_case has already been normalised by the time a component reads
+ // it, and a snake_case fixture leaves every date `Invalid time value`
+ // and every view rendering an error instead of itself.
+ if (key === "cases" || key.startsWith("cases/")) {
return {
- id: 'c1',
- title: 'Suspected macro delivery',
- status: 'open',
- severity: 'high',
- created_at: '2026-10-01T12:00:00Z',
- alerts: [],
+ cases: [
+ {
+ id: "c1",
+ caseNumber: "CASE-0001",
+ title: "Suspected macro delivery",
+ summary: "A macro-enabled document spawned an encoded PowerShell command.",
+ status: "open",
+ severity: "high",
+ createdAt: "2026-10-01T12:00:00Z",
+ updatedAt: "2026-10-01T12:30:00Z",
+ assignee: "[email protected]",
+ alertCount: 1,
+ confidence: 72,
+ tags: ["phishing"],
+ },
+ ],
+ total: 1,
+ page: 1,
+ pageSize: 25,
+ };
+ }
+ if (key === "case" || key.startsWith("case/") || key.includes("/cases/")) {
+ return {
+ id: "c1",
+ caseNumber: "CASE-0001",
+ title: "Suspected macro delivery",
+ description: "A macro-enabled document spawned an encoded PowerShell command.",
+ status: "open",
+ severity: "high",
+ createdAt: "2026-10-01T12:00:00Z",
+ updatedAt: "2026-10-01T12:30:00Z",
+ dueAt: null,
+ assignee: "[email protected]",
+ alertCount: 1,
+ alertIds: ["a1"],
+ resolution: null,
+ mitre: [],
+ tags: ["phishing"],
+ tasks: [],
timeline: [],
};
}
return undefined;
}
-describe('WCAG 2.1 AA — high-traffic surfaces', () => {
- it('Landing Hero has no accessibility violations', async () => {
+describe("WCAG 2.1 AA — high-traffic surfaces", () => {
+ it("Landing Hero has no accessibility violations", async () => {
const { container } = render(<Hero />);
const results = await axe(container, axeOptions);
expect(results).toHaveNoViolations();
});
- it('Onboarding StartHero has no accessibility violations', async () => {
+ it("Onboarding StartHero has no accessibility violations", async () => {
const { container } = render(<StartHero />);
const results = await axe(container, axeOptions);
expect(results).toHaveNoViolations();
});
- it('ThemeToggle has no accessibility violations', async () => {
+ it("ThemeToggle has no accessibility violations", async () => {
const { container } = render(
<ThemeProvider>
<ThemeToggle />
- </ThemeProvider>,
+ </ThemeProvider>
);
const results = await axe(container, axeOptions);
expect(results).toHaveNoViolations();
});
- it('TopBar has no accessibility violations', async () => {
- pathnameMock.mockReturnValue('/dashboard');
+ it("TopBar has no accessibility violations", async () => {
+ pathnameMock.mockReturnValue("/dashboard");
const { container } = render(
<ThemeProvider>
<TimeWindowProvider>
@@ -231,31 +294,31 @@ describe('WCAG 2.1 AA — high-traffic surfaces', () => {
<TopBar />
</TenantProvider>
</TimeWindowProvider>
- </ThemeProvider>,
+ </ThemeProvider>
);
const results = await axe(container, axeOptions);
expect(results).toHaveNoViolations();
});
- it('Sidebar has no accessibility violations', async () => {
- pathnameMock.mockReturnValue('/alerts');
+ it("Sidebar has no accessibility violations", async () => {
+ pathnameMock.mockReturnValue("/alerts");
const { container } = render(
<ThemeProvider>
<Sidebar />
- </ThemeProvider>,
+ </ThemeProvider>
);
const results = await axe(container, axeOptions);
expect(results).toHaveNoViolations();
});
- it('EmptyState has no accessibility violations', async () => {
+ it("EmptyState has no accessibility violations", async () => {
const { container } = render(
- <EmptyState
- icon={<svg aria-hidden="true" />}
- title="No alerts found"
- description="There are no alerts matching your filters."
- action={<button type="button">Clear filters</button>}
- />,
+ <EmptyState
+ icon={<svg aria-hidden="true" />}
+ title="No alerts found"
+ description="There are no alerts matching your filters."
+ action={<button type="button">Clear filters</button>}
+ />
);
const results = await axe(container, axeOptions);
expect(results).toHaveNoViolations();
@@ -266,12 +329,12 @@ describe('WCAG 2.1 AA — high-traffic surfaces', () => {
* operator view below asserts it rendered something substantial first. */
function assertRenderedSomething(container: HTMLElement, what: string) {
const interactive = container.querySelectorAll(
- 'button, a, input, select, textarea, [role="tab"], [role="button"], table, h1, h2',
+ 'button, a, input, select, textarea, [role="tab"], [role="button"], table, h1, h2'
);
expect(
interactive.length,
`${what} rendered ${interactive.length} interactive or structural elements, so axe ` +
- 'passed on an empty or loading view rather than on the real one',
+ "passed on an empty or loading view rather than on the real one"
).toBeGreaterThan(2);
}
@@ -282,51 +345,83 @@ describe('WCAG 2.1 AA — high-traffic surfaces', () => {
// ones above. These are the views an analyst spends their day in, and
// they were covered by nothing.
- it('AlertsView (the queue and alert list) has no accessibility violations', async () => {
- pathnameMock.mockReturnValue('/alerts');
- const { AlertsView } = await import('@/components/alerts/AlertsView');
+ it("AlertsView (the queue and alert list) has no accessibility violations", async () => {
+ pathnameMock.mockReturnValue("/alerts");
+ const { AlertsView } = await import("@/components/alerts/AlertsView");
const { container } = render(
<ThemeProvider>
<AlertsView />
- </ThemeProvider>,
+ </ThemeProvider>
);
- assertRenderedSomething(container, 'AlertsView');
+ assertRenderedSomething(container, "AlertsView");
const results = await axe(container, axeOptions);
expect(results).toHaveNoViolations();
});
- it('InvestigationRail has no accessibility violations', async () => {
- pathnameMock.mockReturnValue('/alerts');
- const { InvestigationRail } = await import('@/components/alerts/InvestigationRail');
+ it("InvestigationRail has no accessibility violations", async () => {
+ pathnameMock.mockReturnValue("/alerts");
+ const { InvestigationRail } = await import("@/components/alerts/InvestigationRail");
const { container } = render(
<ThemeProvider>
<InvestigationRail alertId="a1" onClose={() => {}} />
- </ThemeProvider>,
+ </ThemeProvider>
);
- assertRenderedSomething(container, 'InvestigationRail');
+ assertRenderedSomething(container, "InvestigationRail");
const results = await axe(container, axeOptions);
expect(results).toHaveNoViolations();
});
- it('SettingsView has no accessibility violations', async () => {
- pathnameMock.mockReturnValue('/settings');
- const { SettingsView } = await import('@/components/settings/SettingsView');
+ it("SettingsView has no accessibility violations", async () => {
+ pathnameMock.mockReturnValue("/settings");
+ const { SettingsView } = await import("@/components/settings/SettingsView");
const { container } = render(
<ThemeProvider>
<SettingsView />
- </ThemeProvider>,
+ </ThemeProvider>
+ );
+ assertRenderedSomething(container, "SettingsView");
+ const results = await axe(container, axeOptions);
+ expect(results).toHaveNoViolations();
+ });
+
+ // The case workspace, which 4.7 left uncovered and said so. The plan
+ // names five views -- the queue, the alert list, the case workspace, the
+ // investigation rail and settings -- and this is the pair that was
+ // missing: the list an analyst picks a case from, and the page they then
+ // spend the investigation in.
+
+ it("CasesView (the case list) has no accessibility violations", async () => {
+ pathnameMock.mockReturnValue("/cases");
+ const { CasesView } = await import("@/components/cases/CasesView");
+ const { container } = render(
+ <ThemeProvider>
+ <CasesView />
+ </ThemeProvider>
+ );
+ assertRenderedSomething(container, "CasesView");
+ const results = await axe(container, axeOptions);
+ expect(results).toHaveNoViolations();
+ });
+
+ it("CaseWorkspace has no accessibility violations", async () => {
+ pathnameMock.mockReturnValue("/cases/c1");
+ const { CaseWorkspace } = await import("@/components/cases/CaseWorkspace");
+ const { container } = render(
+ <ThemeProvider>
+ <CaseWorkspace caseId="c1" />
+ </ThemeProvider>
);
- assertRenderedSomething(container, 'SettingsView');
+ assertRenderedSomething(container, "CaseWorkspace");
const results = await axe(container, axeOptions);
expect(results).toHaveNoViolations();
});
- it('CopilotDock (collapsed) has no accessibility violations', async () => {
- pathnameMock.mockReturnValue('/dashboard');
+ it("CopilotDock (collapsed) has no accessibility violations", async () => {
+ pathnameMock.mockReturnValue("/dashboard");
const { container } = render(
<ThemeProvider>
<CopilotDock />
- </ThemeProvider>,
+ </ThemeProvider>
);
const results = await axe(container, axeOptions);
expect(results).toHaveNoViolations();
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index fcb3a56e6..22a0003ff 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -278,7 +278,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Injection flip rate and unsafe-action rate are measured per family | `apps/docs/docs/benchmark.md` | `ci.yml :: Python — Tests` (`tests/adversarial/test_behavioural_injection.py`) | core | GATED | **27 pairs across the 9 families the plan names**, each payload written to fit the field it arrives in: overall flip 25.9%, unsafe action 3.7%, with a per-family ceiling so a regression in one cannot hide behind an improvement in another. It immediately found a real blind spot: **`fake_tool_output` flips every verdict and the guard catches none of it**, because a payload shaped like a tool's own answer reads as evidence rather than as an instruction. Recorded at 1.0 rather than patched, and the guard is deliberately not tuned against this corpus in the same change, because hardening against a tuned corpus has already been measured here moving 66.7% to 98.1% while held-out payloads moved 3.6% to 7.1%. **Measures the pipeline, not a model**: the stub is deliberately obedient, so the rates are an upper bound on harm and the artefact carries `llm_resistance_measured: false` |
| Closure accuracy is measured on the tenant's own data, not only on a synthetic corpus | `apps/docs/docs/operations/shadow-mode.md` | `ci.yml :: Python — Tests` (agents, `test_closure_qa_sampling.py`) | core | GATED | Nothing measured this. The eval harness grades a synthetic corpus and the funnel counts how many alerts were closed, neither of which answers "of the ones the agent closed on your data, how many should it have". A tenant-configurable sample (5% default) of auto-closures goes to an analyst, scored on the five-part rubric. The sample is a **deterministic hash of the alert id, not `random()`**: a rolled sample fires at the configured rate *per replica*, so three replicas at 5% sample 15%, and a redelivered Kafka message gets a second roll and weights one closure twice. Bucketing also makes a higher rate a superset of a lower one, so a tenant's figure stays comparable across a rate change. Zero reviews reports **not measured** rather than 0.0, and every mean travels with the count it was taken over |
| SSO completes a sign-in, into the right tenant with the mapped role | `apps/docs/docs/operations/security.md` | `ci.yml :: Python — Tests` (`services/api/tests/test_sso_provisioning.py`, `test_saml_connection_metadata.py`) + `sso-live.yml :: sso-live` (`tests/isolation/test_sso_live.py` against real Postgres and the real application: a SAML Response signed by the connection's own IdP key, and an RS256 `id_token` from a provider serving real discovery and a real JWKS, each taken through to a token `GET /auth/me` accepts) | core | PARTIAL | Both handlers used to end a successful sign-in by putting a JWT in an `aisoc_token` cookie carrying `sub`, `email`, `name` and `picture`. That token authenticated nothing three times over: signed with `JWT_SECRET` rather than the key the API verifies with, carrying no `tenant_id` or `role`, and in a cookie when the API reads `Authorization: Bearer`. A user could complete the whole dance and find every request unauthenticated. **The security property the tests exist for is that the tenant does not come from the assertion**: an IdP that can name its own tenant can name somebody else's, so it comes from the connection row an administrator configured, and `complete_sso_login` is asserted to take no tenant argument at all. A group cannot map to `admin` or `platform_admin`. The token travels in the URL fragment, which is not sent to the server and does not reach an access log or a `Referer`. **Fix pass 4.1** found the half none of that could see: `_saml_settings()` read its IdP trust anchor from `SAML_IDP_*` while the connection's own `metadata_url` and `metadata_xml` were written by `POST /sso-connections` and read by nothing, so on a stock install — which sets no SAML environment at all — every assertion was refused while the console showed a configured connection. The SAML callback also redirected straight to its RelayState destination, whose auth guard rebuilds its bounce target from `pathname + search` and drops the fragment the token travels in. Both are fixed and driven end to end. **Why this is PARTIAL and not GATED**: the identity providers in that suite are a keypair and a metadata document this repository authors, so they cannot exhibit a vendor's own quirks. `sso-live.yml :: keycloak-oidc` is the containerised leg and **has never been observed to pass** — it was written where no container runtime would start. The row returns to GATED on the first green run of that job, not before |
-| Accessibility is checked on the views an analyst uses, not only on the landing page | `ROADMAP.md` | `ci.yml :: Web — Tests` (`apps/web/src/test/a11y.test.tsx`) | core | GATED | 1.1 narrowed the "WCAG AA full accessibility pass" claim because axe covered the landing and chrome components only. 4.7 adds **three of the five** operator views the plan names: the alerts queue and list, the investigation rail, and settings. Each asserts it rendered real markup **before** axe runs, because axe passes on an empty div and a view that rendered a spinner would report coverage the suite does not have. That guard immediately caught one: the rail keys SWR on a tuple, the fixture read only the string form, and it was rendering its error state. **Limits stated**: the case workspace is not covered, and axe checks a subset of WCAG rather than all of it |
+| Accessibility is checked on the views an analyst uses, not only on the landing page | `ROADMAP.md` | `ci.yml :: Web — Tests` (`apps/web/src/test/a11y.test.tsx`) | core | GATED | 1.1 narrowed the "WCAG AA full accessibility pass" claim because axe covered the landing and chrome components only. 4.7 covers **all five** operator views the plan names: the alerts queue and list, the investigation rail, settings, and -- added by depth 8.1 -- the case list and the case workspace. Extending it to the last two found four real defects rather than confirming a clean sheet: two `<select>` filters with no accessible name (one of them the control that *writes* a case's status, so an unlabelled one is a state change somebody cannot see they are making), two `<aside>` landmarks indistinguishable from each other in the landmark list a screen-reader user navigates from, and panel headings at `h3` directly under the page's `h1`, which reads as a missing section. Each asserts it rendered real markup **before** axe runs, because axe passes on an empty div and a view that rendered a spinner would report coverage the suite does not have. That guard immediately caught one: the rail keys SWR on a tuple, the fixture read only the string form, and it was rendering its error state. **Limits stated**: axe checks a subset of WCAG rather than all of it, and jsdom computes no styles for CSS variables so the `color-contrast` rule is disabled and reviewed by hand |
| A playbook can start from an alert, and previews before it acts | `apps/docs/docs/console/playbooks.md` | `ci.yml :: Python — Tests` (agents, `test_alert_triggered_playbooks.py`) | core | GATED | `find_matching()` had **no production caller**, so no playbook ever ran from an alert. Three switches must agree before one acts (deployment, tenant, playbook) and the default of every one is off; anything short of all three runs in **preview**, with its plan and simulated steps attached to the alert. Preview is the default state rather than a mode somebody has to remember, so a deployment that enables the feature and forgets the per-playbook list gets previews rather than containment. The live list is read per call, so turning one off takes effect on the next alert rather than the next restart. It runs **after** triage, because a playbook's conditions read the verdict |
| An approval step is a durable pause that survives a restart | `apps/docs/docs/console/playbooks.md` | `ci.yml :: Python — Tests` (agents, `test_playbook_pause_resume.py`) | core | GATED | The engine is a single-threaded index walk with no pause and no resume, so `approval` failed closed and **12 shipped playbooks aborted on it**. Failing closed was right (it previously returned `{"skipped": true}` while reporting SUCCESS, letting a run continue into the action a human was meant to authorise) but it is not an approval mechanism. Migration `081` stores the position **and the context**, because the resumed half would otherwise see an empty context and every templated parameter would resolve to nothing. The stored index is the approval step itself and resume advances past it, so a replayed decision continues rather than pausing again. The pause is resolved **before** the run continues, so a double-tap in the responder app resumes once. Expiry is mandatory with a recorded outcome: `expired` is a decision, not the absence of one |
| A tenant's detection tuning reaches the streaming engine, and only that tenant's | `apps/docs/docs/console/detection-tuning.md` | `ci.yml :: Python — Service unit tests` (`services/fusion/tests/test_tenant_tuning_overlay.py`) | core | GATED | `DetectionEngine` evaluated the shared corpus and nothing else. The console writes a tenant's disables, thresholds and suppressions to `detection_rules`, where the streaming engine never looked, so a tenant who turned a noisy rule off **kept receiving its alerts while the console showed it disabled**, which is the worst shape because it tells the operator the problem is solved. An overlay rather than a per-tenant ruleset: the difference applied over one shared corpus, not N copies of 833 rules. Suppression is applied **after** the match so the hit can be logged with the tuning, its author and its reason, because "no alert" with no explanation is indistinguishable from a rule that did not match. A failed reload **keeps the previous overlay**: falling back to no-tuning would turn the tenant's queue back on and read as a flood rather than a fault |