From 657788737185c5dc3d7398b2645417f2364c42b8 Mon Sep 17 00:00:00 2001 From: Vishwas Tiwari Date: Fri, 16 Oct 2026 12:55:18 +0530 Subject: [PATCH 1/5] feat(web): make the ai investigation the centre of the incident page A stepper shows the path from AI analysis through output checks, policy, human approval and verification, derived only from the incident's records (flowSteps, unit-tested on every way the flow stops). The investigation gets an animated confidence ring, citations that jump to and flash the cited event, missing evidence as chips, and a decision panel with an expiry countdown. Policy decisions read as a checklist; correlation scores as bars; the timeline shows who acted. Motion is CSS only and respects reduced motion. Co-Authored-By: Claude Opus 5.5 --- .../app/(dashboard)/incidents/[id]/page.tsx | 341 +++++++++++++----- apps/web/src/app/globals.css | 73 ++++ .../components/incident/confidence-gauge.tsx | 47 +++ .../components/incident/expiry-countdown.tsx | 31 ++ .../src/components/incident/flow-stepper.tsx | 65 ++++ apps/web/src/lib/investigation-flow.ts | 75 ++++ .../test/unit/lib/investigation-flow.test.ts | 96 +++++ 7 files changed, 637 insertions(+), 91 deletions(-) create mode 100644 apps/web/src/components/incident/confidence-gauge.tsx create mode 100644 apps/web/src/components/incident/expiry-countdown.tsx create mode 100644 apps/web/src/components/incident/flow-stepper.tsx create mode 100644 apps/web/src/lib/investigation-flow.ts create mode 100644 apps/web/test/unit/lib/investigation-flow.test.ts diff --git a/apps/web/src/app/(dashboard)/incidents/[id]/page.tsx b/apps/web/src/app/(dashboard)/incidents/[id]/page.tsx index 62b03bf..d50d257 100644 --- a/apps/web/src/app/(dashboard)/incidents/[id]/page.tsx +++ b/apps/web/src/app/(dashboard)/incidents/[id]/page.tsx @@ -1,22 +1,19 @@ -import { Bot, Check, ShieldCheck, Sparkles, X } from 'lucide-react'; +import { Bot, Check, Cpu, FileSearch, Lightbulb, ShieldCheck, Sparkles, Stethoscope, User, X } from 'lucide-react'; import { notFound } from 'next/navigation'; import type { ReactNode } from 'react'; +import { ConfidenceGauge } from '@/components/incident/confidence-gauge'; +import { ExpiryCountdown } from '@/components/incident/expiry-countdown'; +import { FlowStepper } from '@/components/incident/flow-stepper'; import { PageHeader } from '@/components/page-header'; import { StatusBadge } from '@/components/status-badge'; import { Alert } from '@/components/ui/alert'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { apiGet, apiRequest } from '@/lib/api'; -import { - formatConfidence, - formatDateTime, - formatScore, - humanise, - noticeFor, - summariseStates, -} from '@/lib/format'; +import { formatDateTime, formatScore, humanise, noticeFor, summariseStates } from '@/lib/format'; +import { flowSteps } from '@/lib/investigation-flow'; import { isId } from '@/lib/queries'; -import type { Investigation, PolicyDecision, RecoveryAction } from '@/lib/schemas'; +import type { AuditEntry, Investigation, PolicyDecision, RecoveryAction } from '@/lib/schemas'; import { incidentAuditSchema, incidentDetailSchema, @@ -26,12 +23,59 @@ import { import { cn } from '@/lib/utils'; import { decide, investigate } from './actions'; +const evidenceAnchor = (id: string) => `ev-${id}`; + +/** What a citation shows: the lab, when, and the event text. */ +interface CitedEvent { + lab: string; + at: string; + text: string; +} + +const VISIBLE_CITATIONS = 3; + +function Citation({ id, events }: { id: string; events: Map }) { + const event = events.get(id); + return ( + + {event ? ( + <> + + {event.lab} + {event.at} + + {event.text} + + ) : ( + {id} + )} + + ); +} + function Decisions({ decisions }: { decisions: PolicyDecision[] }) { return ( -
    - {decisions.map((d) => ( -
  1. - {d.passed ? : } +
      + {decisions.map((d, index) => ( +
    1. + + {d.passed ? : } + {d.passed ? 'passed' : 'failed'} {humanise(d.step)}: {d.reason} @@ -42,41 +86,65 @@ function Decisions({ decisions }: { decisions: PolicyDecision[] }) { ); } -function Section({ title, children }: { title: string; children: ReactNode }) { +function Section({ title, icon: Icon, children }: { title: string; icon?: typeof Check; children: ReactNode }) { return ( -
      -

      {title}

      +
      +

      + {Icon && } + {title} +

      {children}
      ); } -function EvidenceList({ title, ids, messages }: { title: string; ids: string[]; messages: Map }) { +// Citations link to the cited event in the evidence list below, which flashes +// on arrival. Only the incident's own events resolve, so a citation cannot +// point outside the incident. +function EvidenceList({ title, ids, events }: { title: string; ids: string[]; events: Map }) { if (ids.length === 0) return null; + const shown = ids.slice(0, VISIBLE_CITATIONS); + const rest = ids.slice(VISIBLE_CITATIONS); return ( -
      +

      {title}

      -
        - {ids.map((id) => ( -
      • {messages.get(id) ?? id}
      • +
          + {shown.map((id) => ( +
        • + +
        • ))}
        + {rest.length > 0 && ( +
        + + Show {rest.length} more + Show fewer + +
          + {rest.map((id) => ( +
        • + +
        • + ))} +
        +
        + )}
      ); } -// Evidence is cited by event id; the page shows the event it names, from the -// incident's own evidence, so a citation cannot point outside the incident. function InvestigationCard({ investigation, - messages, + events, }: { investigation: Investigation; - messages: Map; + events: Map; }) { + const both = investigation.evidenceFor.length > 0 && investigation.evidenceAgainst.length > 0; return ( - - + + AI investigation @@ -85,50 +153,60 @@ function InvestigationCard({ A proposal from the model, judged by policy and a human. It never acts on its own. - + {investigation.failure && ( The model call failed ({humanise(investigation.failure)}). Nothing was changed. )} - {investigation.outcome && ( -

      - {humanise(investigation.outcome)}: {investigation.summary} -

      - )} -
      - {investigation.candidateCause && ( -

      Likely cause: {investigation.candidateCause}

      - )} -

      Confidence: {formatConfidence(investigation.confidence)}

      +
      +
      + {investigation.candidateCause && ( +

      Likely cause: {investigation.candidateCause}

      + )} + {investigation.outcome && ( +

      + {humanise(investigation.outcome)}:{' '} + {investigation.summary} +

      + )} +
      + +
      +
      + +
      - - {investigation.missingEvidence.length > 0 && ( -
      -

      Missing evidence

      -
        +
        +
          {investigation.missingEvidence.map((item) => ( -
        • {item}
        • +
        • + {item} +
        • ))}
        -
      + )} {investigation.diagnosticChecks.length > 0 && ( -
      -

      Checks worth running

      -
        - {investigation.diagnosticChecks.map((item) => ( -
      • {item}
      • +
        +
          + {investigation.diagnosticChecks.map((item, index) => ( +
        1. + {index + 1}. + {item} +
        2. ))} -
      -
      +
    + )} {investigation.recommendedAction && ( -

    - Recommended: {investigation.recommendedAction} on{' '} - {investigation.targetLabIds.length} lab(s) -

    +
    + + Recommended: + {investigation.recommendedAction} + on {investigation.targetLabIds.length} lab(s) +
    )} {investigation.droppedTargets.length > 0 && ( @@ -144,7 +222,7 @@ function InvestigationCard({ function ActionCard({ incidentId, action }: { incidentId: string; action: RecoveryAction }) { const verification = action.verificationResult; return ( - + @@ -178,7 +256,7 @@ function ActionCard({ incidentId, action }: { incidentId: string; action: Recove {verification && (
    @@ -194,16 +272,19 @@ function ActionCard({ incidentId, action }: { incidentId: string; action: Recove
    )} {action.status === 'awaiting_approval' && ( -
    -
    - -
    +
    +
    +

    Your decision

    + +
    - Expires {formatDateTime(action.expiresAt)} +
    + +
    )} @@ -213,13 +294,41 @@ function ActionCard({ incidentId, action }: { incidentId: string; action: Recove function Stat({ label, value }: { label: string; value: ReactNode }) { return ( -
    +

    {label}

    {value}

    ); } +// Who acted on each audit step: the operator, the background worker, or the system. +const ACTOR_ICON = { human: User, worker: Cpu, system: Bot } as const; + +function TimelineEntry({ entry, last }: { entry: AuditEntry; last: boolean }) { + const Icon = ACTOR_ICON[entry.actorType as keyof typeof ACTOR_ICON] ?? Bot; + const refused = /rejected|blocked|failed|error/.test(entry.outcome); + return ( +
  2. + {!last && } + + + +
    +

    + {humanise(entry.action)} · {entry.outcome} · {entry.actorType} +

    +

    {formatDateTime(entry.createdAt)}

    +
    +
  3. + ); +} + export default async function IncidentPage({ params, searchParams, @@ -241,6 +350,18 @@ export default async function IncidentPage({ const latest = investigations[0]; const canInvestigate = incident.status === 'open' || incident.status === 'manual_review'; const message = noticeFor(notice); + const labOfEvent = new Map(incident.labs.map((lab) => [lab.eventId, lab.labId])); + const events = new Map( + incident.events.map((event) => [ + event.id, + { + lab: labOfEvent.get(event.id) ?? 'unknown lab', + at: formatDateTime(event.occurredAt), + text: `${event.errorCategory}: ${event.message}`, + }, + ]), + ); + const cited = new Set([...(latest?.evidenceFor ?? []), ...(latest?.evidenceAgainst ?? [])]); return ( <> @@ -273,8 +394,41 @@ export default async function IncidentPage({ {formatDateTime(incident.resolvedAt)}} /> + + + From investigation to recovery + + The model proposes, deterministic policy decides, an operator approves, and only verification resolves. + + + + + + +
    + {latest ? ( + + ) : ( + canInvestigate && ( + + + + + +

    + No investigation yet. Investigate asks the AI analyst + for a likely cause over this incident's own, redacted evidence. It can only suggest. +

    +
    +
    + ) + )} + {actions.map((action) => ( + + ))} + Why these labs are grouped @@ -289,15 +443,27 @@ export default async function IncidentPage({ Lab Reason (recorded verbatim) - Correlation strength + Correlation strength {incident.labs.map((lab) => ( - + {lab.labId} - {lab.reason} - {formatScore(lab.signalScore)} + {lab.reason} + + + {lab.signalScore !== null && ( + + + + )} + {formatScore(lab.signalScore)} + + ))} @@ -306,29 +472,28 @@ export default async function IncidentPage({ - {latest && ( - [event.id, `${event.errorCategory}: ${event.message}`]))} - /> - )} - {actions.map((action) => ( - - ))} - Evidence - The failure events that put each lab here (redacted at ingestion). + + The failure events that put each lab here (redacted at ingestion). Events the AI cited are marked. + - + {incident.events.map((event) => ( -
    +
    {formatDateTime(event.occurredAt)} {event.errorCategory} {event.message} + {cited.has(event.id) && ( + cited + )}
    ))} @@ -341,15 +506,9 @@ export default async function IncidentPage({ This incident's audit history, in order. -
      - {audit.map((entry) => ( -
    1. - -

      - {humanise(entry.action)} · {entry.outcome} · {entry.actorType} -

      -

      {formatDateTime(entry.createdAt)}

      -
    2. +
        + {audit.map((entry, index) => ( + ))}
      diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 2b80337..5f46188 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -105,3 +105,76 @@ body { @apply bg-background text-foreground antialiased; } + +/* Motion: entrances, the confidence gauge and evidence highlights. Plain CSS so + server components animate without client JavaScript. */ +@keyframes rise { + from { + opacity: 0; + transform: translateY(6px); + } +} + +@keyframes gauge-fill { + from { + stroke-dashoffset: var(--gauge-length); + } +} + +@keyframes grow-x { + from { + transform: scaleX(0); + } +} + +@keyframes flash { + 0%, + 40% { + background-color: var(--info-bg); + box-shadow: inset 3px 0 0 var(--info); + } +} + +@keyframes ping-soft { + 75%, + 100% { + transform: scale(1.9); + opacity: 0; + } +} + +.animate-rise { + animation: rise 420ms cubic-bezier(0.2, 0.7, 0.2, 1) both; +} + +.animate-gauge { + animation: gauge-fill 1100ms cubic-bezier(0.2, 0.7, 0.2, 1) both; +} + +.animate-grow-x { + transform-origin: left; + animation: grow-x 700ms cubic-bezier(0.2, 0.7, 0.2, 1) both; +} + +.animate-ping-soft { + animation: ping-soft 1.6s cubic-bezier(0, 0, 0.2, 1) infinite; +} + +/* A cited evidence link jumps to its event, which flashes so the eye lands on it. */ +.evidence-row { + scroll-margin-top: 6rem; +} + +.evidence-row:target { + animation: flash 1.8s ease-out; +} + +@media (prefers-reduced-motion: reduce) { + .animate-rise, + .animate-gauge, + .animate-grow-x, + .animate-ping-soft, + .evidence-row:target { + animation: none; + } +} diff --git a/apps/web/src/components/incident/confidence-gauge.tsx b/apps/web/src/components/incident/confidence-gauge.tsx new file mode 100644 index 0000000..ee88221 --- /dev/null +++ b/apps/web/src/components/incident/confidence-gauge.tsx @@ -0,0 +1,47 @@ +// The model's own confidence as a ring that fills on load. It is the model's +// estimate, not a measured probability, so the label says so. + +import type { CSSProperties } from 'react'; +import { formatConfidence } from '@/lib/format'; +import { cn } from '@/lib/utils'; + +const RADIUS = 34; +const LENGTH = 2 * Math.PI * RADIUS; + +function tone(confidence: number): string { + if (confidence >= 0.75) return 'text-success'; + if (confidence >= 0.5) return 'text-warning'; + return 'text-danger'; +} + +export function ConfidenceGauge({ confidence }: { confidence: number | null }) { + const value = confidence ?? 0; + return ( +
      + + + {confidence !== null && ( + + )} + +
      +

      + {confidence === null ? '—' : `${Math.round(value * 100)}%`} +

      +

      Confidence: {formatConfidence(confidence)}

      +
      +
      + ); +} diff --git a/apps/web/src/components/incident/expiry-countdown.tsx b/apps/web/src/components/incident/expiry-countdown.tsx new file mode 100644 index 0000000..a588427 --- /dev/null +++ b/apps/web/src/components/incident/expiry-countdown.tsx @@ -0,0 +1,31 @@ +'use client'; + +// How long an approval stays valid. After it lapses the worker refuses the +// action, so the countdown is the operator's real deadline. + +import { useEffect, useState } from 'react'; +import { formatDateTime } from '@/lib/format'; + +function remaining(expiresAt: string, now: number): string { + const seconds = Math.max(0, Math.round((Date.parse(expiresAt) - now) / 1000)); + if (seconds === 0) return 'expired'; + const minutes = Math.floor(seconds / 60); + return `${minutes}:${String(seconds % 60).padStart(2, '0')} left`; +} + +export function ExpiryCountdown({ expiresAt }: { expiresAt: string | null }) { + const [now, setNow] = useState(null); + useEffect(() => { + setNow(Date.now()); + const timer = setInterval(() => setNow(Date.now()), 1000); + return () => clearInterval(timer); + }, []); + if (!expiresAt) return null; + return ( + + Expires {formatDateTime(expiresAt)} + {/* Rendered after mount only: the server's clock would not match the browser's. */} + {now !== null && · {remaining(expiresAt, now)}} + + ); +} diff --git a/apps/web/src/components/incident/flow-stepper.tsx b/apps/web/src/components/incident/flow-stepper.tsx new file mode 100644 index 0000000..a26e3fc --- /dev/null +++ b/apps/web/src/components/incident/flow-stepper.tsx @@ -0,0 +1,65 @@ +// The path from AI investigation to verified recovery, one step per stage, +// filled from the incident's own records. Live updates refresh the page, so a +// step lights up as the worker and the operator move it on. + +import { Ban, Check, Circle, Loader2, Minus, X } from 'lucide-react'; +import type { FlowStep, StepState } from '@/lib/investigation-flow'; +import { cn } from '@/lib/utils'; + +const MARKER: Record = { + done: 'border-success bg-success text-card', + active: 'border-info bg-info-bg text-info', + blocked: 'border-danger bg-danger text-card', + failed: 'border-danger bg-danger text-card', + pending: 'border-border bg-card text-muted-foreground', + skipped: 'border-dashed border-border bg-muted text-muted-foreground', +}; + +const ICON = { done: Check, active: Loader2, blocked: Ban, failed: X, pending: Circle, skipped: Minus } as const; + +const STATE_LABEL: Record = { + done: 'done', + active: 'in progress', + blocked: 'blocked', + failed: 'failed', + pending: 'not started', + skipped: 'skipped', +}; + +export function FlowStepper({ steps }: { steps: FlowStep[] }) { + return ( +
        + {steps.map((step, index) => { + const Icon = ICON[step.state]; + const next = steps[index + 1]; + return ( +
      1. + {next && ( + // The connector fills once this step is done, so progress reads left to right. + + {step.state === 'done' && } + + )} + + {step.state === 'active' && ( + + )} + + + + + + {step.label} + : {STATE_LABEL[step.state]}. + {step.detail} + +
      2. + ); + })} +
      + ); +} diff --git a/apps/web/src/lib/investigation-flow.ts b/apps/web/src/lib/investigation-flow.ts new file mode 100644 index 0000000..5f53630 --- /dev/null +++ b/apps/web/src/lib/investigation-flow.ts @@ -0,0 +1,75 @@ +// Where an incident stands on the path from AI investigation to verified +// recovery, derived only from records the API returned. The stepper renders +// this; nothing here decides anything, it describes what already happened. + +import type { Investigation, RecoveryAction } from '@/lib/schemas'; + +export type StepState = 'done' | 'active' | 'blocked' | 'failed' | 'pending' | 'skipped'; + +export interface FlowStep { + key: 'analysis' | 'validation' | 'policy' | 'approval' | 'verification'; + label: string; + state: StepState; + detail: string; +} + +type Outcome = Pick; + +// Statuses an action reaches only after an operator approved it. +const APPROVED = new Set(['approved', 'running', 'succeeded', 'failed', 'blocked']); + +function analysis(investigation: Investigation | undefined): Outcome { + if (!investigation) return { state: 'pending', detail: 'Not requested yet' }; + if (investigation.status === 'completed') return { state: 'done', detail: 'Model answered over bounded, redacted evidence' }; + if (investigation.status === 'error') return { state: 'failed', detail: 'The model call failed; nothing changed' }; + return { state: 'active', detail: 'Model is analysing the evidence' }; +} + +function validation(investigation: Investigation | undefined): Outcome { + if (investigation?.status === 'completed') return { state: 'done', detail: 'Strict schema; targets limited to this incident' }; + if (investigation?.status === 'error') return { state: 'failed', detail: 'Rejected before anything was proposed' }; + return { state: 'pending', detail: 'Waits for the model' }; +} + +function policy(investigation: Investigation | undefined, action: RecoveryAction | undefined): Outcome { + if (investigation?.status !== 'completed') return { state: 'pending', detail: 'Deterministic rules, never the model' }; + if (!action) return { state: 'skipped', detail: 'No action recommended' }; + if (action.status === 'rejected_by_policy') { + return { state: 'blocked', detail: `Blocked at the ${action.blockedAt ?? 'policy'} step` }; + } + return { state: 'done', detail: 'Every proposal-time rule passed' }; +} + +function approval(previous: Outcome, action: RecoveryAction | undefined): Outcome { + if (previous.state === 'blocked' || previous.state === 'skipped') return { state: 'skipped', detail: 'Nothing to approve' }; + if (previous.state !== 'done' || !action) return { state: 'pending', detail: 'An operator decides' }; + if (action.status === 'awaiting_approval') return { state: 'active', detail: 'Waiting for an operator' }; + if (action.status === 'rejected') return { state: 'blocked', detail: 'Rejected by an operator' }; + if (action.status === 'expired') return { state: 'blocked', detail: 'The approval expired unused' }; + if (APPROVED.has(action.status)) return { state: 'done', detail: 'Approved; policy re-checked before running' }; + return { state: 'pending', detail: 'An operator decides' }; +} + +function verification(previous: Outcome, action: RecoveryAction | undefined): Outcome { + if (previous.state === 'blocked' || previous.state === 'skipped') return { state: 'skipped', detail: 'Nothing ran' }; + if (previous.state !== 'done' || !action) return { state: 'pending', detail: 'Resolved only when every lab is ready' }; + if (action.status === 'blocked') return { state: 'blocked', detail: 'Blocked when policy was re-checked at execution' }; + const result = action.verificationResult; + if (!result) return { state: 'active', detail: 'Running the action, then re-reading every lab' }; + return result.passed + ? { state: 'done', detail: 'Every lab re-read and ready' } + : { state: 'failed', detail: 'Labs not ready; the incident stays open' }; +} + +/** The newest investigation and the newest action (the API lists both newest first). */ +export function flowSteps(investigation: Investigation | undefined, action: RecoveryAction | undefined): FlowStep[] { + const policyStep = policy(investigation, action); + const approvalStep = approval(policyStep, action); + return [ + { key: 'analysis', label: 'AI analysis', ...analysis(investigation) }, + { key: 'validation', label: 'Output checked', ...validation(investigation) }, + { key: 'policy', label: 'Policy check', ...policyStep }, + { key: 'approval', label: 'Human approval', ...approvalStep }, + { key: 'verification', label: 'Verified', ...verification(approvalStep, action) }, + ]; +} diff --git a/apps/web/test/unit/lib/investigation-flow.test.ts b/apps/web/test/unit/lib/investigation-flow.test.ts new file mode 100644 index 0000000..df176c5 --- /dev/null +++ b/apps/web/test/unit/lib/investigation-flow.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from 'vitest'; +import { flowSteps } from '@/lib/investigation-flow'; +import type { Investigation, RecoveryAction } from '@/lib/schemas'; + +const investigation = (status: string): Investigation => ({ + id: 'inv-1', + status, + outcome: status === 'completed' ? 'diagnosis' : null, + summary: null, + candidateCause: null, + evidenceFor: [], + evidenceAgainst: [], + missingEvidence: [], + diagnosticChecks: [], + confidence: null, + recommendedAction: null, + targetLabIds: [], + droppedTargets: [], + failure: status === 'error' ? 'timeout' : null, + modelMetadata: null, + createdAt: '2026-10-16T10:00:00.000Z', + completedAt: null, +}); + +const action = (status: string, extra: Partial = {}): RecoveryAction => ({ + id: 'act-1', + actionType: 'RETRY_PROVISIONING', + targetIds: [], + status, + proposedBy: 'worker', + blockedAt: null, + policyDecisions: [], + expiresAt: null, + approvedBy: null, + approvedAt: null, + executedAt: null, + result: null, + verificationResult: null, + createdAt: '2026-10-16T10:00:00.000Z', + ...extra, +}); + +const states = (...args: Parameters) => flowSteps(...args).map((step) => step.state); + +describe('flowSteps', () => { + it('waits at the start before anyone investigates', () => { + expect(states(undefined, undefined)).toEqual(['pending', 'pending', 'pending', 'pending', 'pending']); + }); + + it('shows the model working while the investigation runs', () => { + expect(states(investigation('running'), undefined)[0]).toBe('active'); + }); + + it('waits for the operator once policy passed', () => { + expect(states(investigation('completed'), action('awaiting_approval'))).toEqual([ + 'done', + 'done', + 'done', + 'active', + 'pending', + ]); + }); + + it('runs to verified when every lab is ready', () => { + const succeeded = action('succeeded', { verificationResult: { passed: true } }); + expect(states(investigation('completed'), succeeded)).toEqual(['done', 'done', 'done', 'done', 'done']); + }); + + // Negative paths: every way the flow stops must read as stopped, never as done. + it('stops at the model when the call fails, and nothing later runs', () => { + expect(states(investigation('error'), undefined)).toEqual(['failed', 'failed', 'pending', 'pending', 'pending']); + }); + + it('marks a policy refusal as blocked, naming the step, and skips the rest', () => { + const steps = flowSteps(investigation('completed'), action('rejected_by_policy', { blockedAt: 'state' })); + expect(steps.map((step) => step.state)).toEqual(['done', 'done', 'blocked', 'skipped', 'skipped']); + expect(steps[2]?.detail).toBe('Blocked at the state step'); + }); + + it('skips policy and approval when the model recommended nothing', () => { + expect(states(investigation('completed'), undefined)).toEqual(['done', 'done', 'skipped', 'skipped', 'skipped']); + }); + + it.each(['rejected', 'expired'])('stops at approval when the action was %s', (status) => { + expect(states(investigation('completed'), action(status)).slice(3)).toEqual(['blocked', 'skipped']); + }); + + it('marks the re-check at execution blocking the action', () => { + expect(states(investigation('completed'), action('blocked')).slice(3)).toEqual(['done', 'blocked']); + }); + + it('never calls a failed verification done', () => { + const failed = action('failed', { verificationResult: { passed: false } }); + expect(states(investigation('completed'), failed)[4]).toBe('failed'); + }); +}); From b5bbf0c22c4e6205c7a788e4db78d217d4cef09a Mon Sep 17 00:00:00 2001 From: Vishwas Tiwari Date: Fri, 16 Oct 2026 12:57:41 +0530 Subject: [PATCH 2/5] feat(web): animate the dashboard and make its charts interactive KPI figures count up once (the server renders the final value; reduced motion skips it), the failure timeline's bars animate in and its legend toggles categories (never the last one, which would read as no failures), the labs donut highlights a state on hover, and bar lists grow in. Co-Authored-By: Claude Opus 5.5 --- .../web/src/components/dashboard/bar-list.tsx | 5 +- .../web/src/components/dashboard/count-up.tsx | 27 +++++++++++ .../components/dashboard/failure-timeline.tsx | 47 +++++++++++++++---- .../web/src/components/dashboard/kpi-tile.tsx | 7 ++- .../src/components/dashboard/labs-donut.tsx | 32 +++++++++++-- .../components/dashboard/dashboard.test.tsx | 39 +++++++++++++++ 6 files changed, 141 insertions(+), 16 deletions(-) create mode 100644 apps/web/src/components/dashboard/count-up.tsx diff --git a/apps/web/src/components/dashboard/bar-list.tsx b/apps/web/src/components/dashboard/bar-list.tsx index bd7411f..e63d273 100644 --- a/apps/web/src/components/dashboard/bar-list.tsx +++ b/apps/web/src/components/dashboard/bar-list.tsx @@ -12,7 +12,10 @@ export function BarList({ items, colourFor }: { items: [string, number][]; colou {count}
    -
    +
    ))} diff --git a/apps/web/src/components/dashboard/count-up.tsx b/apps/web/src/components/dashboard/count-up.tsx new file mode 100644 index 0000000..b0593d0 --- /dev/null +++ b/apps/web/src/components/dashboard/count-up.tsx @@ -0,0 +1,27 @@ +'use client'; + +// Counts a headline number up from zero once, on mount. The server renders the +// final value, so it reads correctly before hydration, without JavaScript and +// for screen readers; reduced motion skips the animation entirely. + +import { useEffect, useState } from 'react'; + +const DURATION_MS = 900; + +export function CountUp({ value }: { value: number }) { + const [shown, setShown] = useState(value); + useEffect(() => { + if (value === 0 || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return; + let frame = 0; + const start = performance.now(); + const tick = (now: number) => { + const progress = Math.min(1, (now - start) / DURATION_MS); + // Ease out: fast at first, settling onto the real number. + setShown(Math.round(value * (1 - (1 - progress) ** 3))); + if (progress < 1) frame = requestAnimationFrame(tick); + }; + frame = requestAnimationFrame(tick); + return () => cancelAnimationFrame(frame); + }, [value]); + return {shown}; +} diff --git a/apps/web/src/components/dashboard/failure-timeline.tsx b/apps/web/src/components/dashboard/failure-timeline.tsx index 3703c5d..74468b8 100644 --- a/apps/web/src/components/dashboard/failure-timeline.tsx +++ b/apps/web/src/components/dashboard/failure-timeline.tsx @@ -5,9 +5,11 @@ // no values in between. Data arrives as props from the server; the browser // never calls the API. +import { useState } from 'react'; import { Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'; import { bucketLabel, colourFor } from '@/lib/charts'; import { humanise } from '@/lib/format'; +import { cn } from '@/lib/utils'; import type { FailureSeries } from '@/lib/schemas'; type TooltipEntry = { dataKey?: unknown; value?: unknown; color?: string }; @@ -31,6 +33,17 @@ function TimelineTooltip({ active, payload, label }: { active?: boolean; payload export function FailureTimeline({ series }: { series: FailureSeries }) { const categories = Object.keys(series.totals).filter((category) => (series.totals[category] ?? 0) > 0); + // Categories the operator switched off in the legend, to isolate one signal. + const [hidden, setHidden] = useState>(new Set()); + const visible = categories.filter((category) => !hidden.has(category)); + const toggle = (category: string) => + setHidden((current) => { + const next = new Set(current); + if (next.has(category)) next.delete(category); + // Never hide the last one: an empty chart reads as "no failures". + else if (visible.length > 1) next.add(category); + return next; + }); const data = series.buckets.map((bucket) => ({ label: bucketLabel(bucket.start, series.bucketMs ?? 60_000), ...bucket.counts, @@ -44,26 +57,40 @@ export function FailureTimeline({ series }: { series: FailureSeries }) { } cursor={{ fill: 'var(--muted)' }} /> - {categories.map((category, index) => ( + {visible.map((category, index) => ( ))}
    -
      - {categories.map((category) => ( -
    • - - {humanise(category)} -
    • - ))} +
        + {categories.map((category) => { + const on = !hidden.has(category); + return ( +
      • + +
      • + ); + })}
    ); diff --git a/apps/web/src/components/dashboard/kpi-tile.tsx b/apps/web/src/components/dashboard/kpi-tile.tsx index ae57de0..85179db 100644 --- a/apps/web/src/components/dashboard/kpi-tile.tsx +++ b/apps/web/src/components/dashboard/kpi-tile.tsx @@ -1,6 +1,7 @@ import type { LucideIcon } from 'lucide-react'; import type { ReactNode } from 'react'; import { cn } from '@/lib/utils'; +import { CountUp } from './count-up'; const TONES = { neutral: 'bg-muted text-muted-foreground', @@ -25,14 +26,16 @@ export function KpiTile({ tone?: keyof typeof TONES; }) { return ( -
    +

    {label}

    -

    {value}

    +

    + {typeof value === 'number' ? : value} +

    {caption}

    ); diff --git a/apps/web/src/components/dashboard/labs-donut.tsx b/apps/web/src/components/dashboard/labs-donut.tsx index 87a1a43..06702d5 100644 --- a/apps/web/src/components/dashboard/labs-donut.tsx +++ b/apps/web/src/components/dashboard/labs-donut.tsx @@ -1,6 +1,8 @@ 'use client'; +import { useState } from 'react'; import { Cell, Pie, PieChart, ResponsiveContainer, Tooltip } from 'recharts'; +import { cn } from '@/lib/utils'; // Lab states take the status palette, not the category one: a failed lab is // the same red here as on every badge. @@ -17,14 +19,33 @@ export function LabsDonut({ counts }: { counts: Record }) { .filter(([, value]) => value > 0) .map(([state, value]) => ({ state, value })); const total = data.reduce((sum, entry) => sum + entry.value, 0); + // Hovering a slice or its legend row brings that state forward. + const [focus, setFocus] = useState(null); + const dimmed = (state: string) => focus !== null && focus !== state; return (
    - + 1 ? 2 : 0} + animationDuration={800} + onMouseEnter={(_, index) => setFocus(data[index]?.state ?? null)} + onMouseLeave={() => setFocus(null)} + > {data.map((entry) => ( - + ))} }) {