Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(ledger): add replayable timeline (WS-D3)
Beenu Arora748725c61cde
diff --git a/apps/web/src/components/cases/InvestigationLedger.tsx b/apps/web/src/components/cases/InvestigationLedger.tsxindex f53a202e9..bba104f5f 100644--- a/apps/web/src/components/cases/InvestigationLedger.tsx+++ b/apps/web/src/components/cases/InvestigationLedger.tsx@@ -24,7 +24,7 @@* - Export full ledger as signed JSON for auditor handoff*/-import { useEffect, useMemo, useState } from 'react';+import { useEffect, useMemo, useRef, useState } from 'react';import useSWR from 'swr';import { clsx } from 'clsx';import { format, formatDistanceToNow } from 'date-fns';@@ -40,6 +40,8 @@ import {} from '@/lib/api';import { Skeleton } from '@/components/ui/Skeleton';import { EmptyState } from '@/components/ui/EmptyState';+import { ReplayControls } from '@/components/cases/replay/ReplayControls';+import { useReplayController } from '@/components/cases/replay/useReplayController';// ─── Style maps ───────────────────────────────────────────────────────────────@@ -209,6 +211,41 @@ export function InvestigationLedger({setSelectedSeq(null);}, [resolvedRunId]);+ // ─── Replay controller ────────────────────────────────────────────────────+ // Drives `selectedSeq` through `filteredEvents` like a media player so an+ // auditor can step (or auto-play) through the agent's decisions instead of+ // staring at a wall of rows. We pass `filteredEvents` (not the full list) so+ // the kind/agent filter scopes the replay too — handy for replaying just the+ // tool calls. While a run is still streaming we disable replay: tailing the+ // tip + auto-advancing the cursor would fight each other.+ const replay = useReplayController({+ events: filteredEvents,+ selectedSeq,+ setSelectedSeq,+ enabled: !isLive,+ });++ // The current event under the replay cursor — passed to ReplayControls for+ // its trailing label, and used as the "you are here" marker for auto-scroll.+ const currentReplayEvent = useMemo<LedgerEvent | null>(() => {+ if (selectedSeq == null) return null;+ return filteredEvents.find((e) => e.seq === selectedSeq) ?? null;+ }, [filteredEvents, selectedSeq]);++ // Auto-scroll the active row into view while replay is playing. We scope+ // the lookup to the timeline `<ol>` so we never accidentally grab another+ // element with the same `data-seq` (e.g. a future minimap).+ const timelineListRef = useRef<HTMLOListElement | null>(null);+ useEffect(() => {+ if (!replay.isPlaying || selectedSeq == null) return;+ const root = timelineListRef.current;+ if (!root) return;+ const row = root.querySelector<HTMLElement>(`[data-seq="${selectedSeq}"]`);+ // `block: 'nearest'` keeps the row visible without yanking the page when+ // the user has scrolled the rest of the layout.+ row?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });+ }, [replay.isPlaying, selectedSeq]);+// ─── Export signed JSON ───────────────────────────────────────────────────const exportLedger = async () => {if (!resolvedRunId || !activeRun) return;@@ -360,6 +397,14 @@ export function InvestigationLedger({<ModelCostsCard costs={runDetail.model_costs} />)}+ {/* Replay controls — only render once we actually have events to step+ through. While a run is still tailing live we render the disabled+ state of the controls (controlled via `enabled: !isLive` above) so+ the layout doesn't jump when the run finishes. */}+ {(events?.length ?? 0) > 0 && (+ <ReplayControls controller={replay} currentEvent={currentReplayEvent} />+ )}+{/* Two-pane layout: timeline on the left, explain on the right */}<div className="grid grid-cols-1 gap-4 lg:grid-cols-12"><div className="lg:col-span-5">@@ -394,7 +439,10 @@ export function InvestigationLedger({/></div>) : (- <ol className="max-h-[640px] space-y-1 overflow-y-auto p-1">+ <ol+ ref={timelineListRef}+ className="max-h-[640px] space-y-1 overflow-y-auto p-1"+ >{filteredEvents.map((evt) => (<TimelineRowkey={evt.id}@@ -596,8 +644,10 @@ function TimelineRow({selected: boolean;onClick: () => void;}) {+ // `data-seq` is consumed by the parent's replay scroll-into-view effect so+ // we can auto-track the cursor through the list without threading refs.return (- <li>+ <li data-seq={event.seq}><buttononClick={onClick}className={clsx(diff --git a/apps/web/src/components/cases/replay/ReplayControls.test.tsx b/apps/web/src/components/cases/replay/ReplayControls.test.tsxnew file mode 100644index 000000000..60c12cd71--- /dev/null+++ b/apps/web/src/components/cases/replay/ReplayControls.test.tsx@@ -0,0 +1,180 @@+import { describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { ReplayControls } from './ReplayControls';+import type { ReplayController } from './useReplayController';+import type { LedgerEvent } from '@/lib/api';++// The hook is unit-tested in `useReplayController.test.ts`; here we just+// assert that the component wires its props onto the visible control surface+// (transport, scrubber, mode, speed) and forwards user input back to the+// controller. We pass a hand-rolled controller mock instead of rendering the+// real hook so we can isolate UI behaviour from playback timing.++function makeController(over: Partial<ReplayController> = {}): ReplayController {+ return {+ isPlaying: false,+ speed: 1,+ mode: 'fixed',+ progress: 0,+ currentIndex: 0,+ total: 5,+ play: vi.fn(),+ pause: vi.fn(),+ toggle: vi.fn(),+ stop: vi.fn(),+ stepForward: vi.fn(),+ stepBackward: vi.fn(),+ seekToIndex: vi.fn(),+ setSpeed: vi.fn(),+ setMode: vi.fn(),+ ...over,+ };+}++function makeEvent(seq: number, summary = `step ${seq}`): LedgerEvent {+ return {+ id: `evt-${seq}`,+ run_id: 'run-1',+ seq,+ ts: '2026-05-09T00:00:00Z',+ kind: 'tool_call',+ agent: 'investigator',+ summary,+ payload: null,+ input_hash: null,+ output_hash: null,+ duration_ms: 1000,+ };+}++describe('ReplayControls', () => {+ it('renders the play button when paused and forwards toggle()', async () => {+ const controller = makeController({ isPlaying: false });+ render(<ReplayControls controller={controller} currentEvent={makeEvent(1)} />);++ const play = screen.getByRole('button', { name: 'Play replay' });+ expect(play).toHaveAttribute('aria-pressed', 'false');+ await userEvent.click(play);+ expect(controller.toggle).toHaveBeenCalledTimes(1);+ });++ it('renders the pause button when playing and reflects aria-pressed', () => {+ const controller = makeController({ isPlaying: true });+ render(<ReplayControls controller={controller} currentEvent={makeEvent(2)} />);+ const pause = screen.getByRole('button', { name: 'Pause replay' });+ expect(pause).toHaveAttribute('aria-pressed', 'true');+ expect(pause).toHaveTextContent(/Pause/i);+ });++ it('disables ◀︎ at the start and ▶︎ at the end', () => {+ const atStart = makeController({ currentIndex: 0, total: 5 });+ const { rerender } = render(+ <ReplayControls controller={atStart} currentEvent={makeEvent(1)} />,+ );+ expect(screen.getByRole('button', { name: 'Step backward' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Step forward' })).not.toBeDisabled();++ const atEnd = makeController({ currentIndex: 4, total: 5 });+ rerender(<ReplayControls controller={atEnd} currentEvent={makeEvent(5)} />);+ expect(screen.getByRole('button', { name: 'Step backward' })).not.toBeDisabled();+ expect(screen.getByRole('button', { name: 'Step forward' })).toBeDisabled();+ });++ it('disables every transport button when total is 0', () => {+ const controller = makeController({ total: 0, currentIndex: null });+ render(<ReplayControls controller={controller} currentEvent={null} />);+ expect(screen.getByRole('button', { name: 'Play replay' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Step backward' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Step forward' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Stop and rewind' })).toBeDisabled();+ expect(screen.getByText('No events')).toBeInTheDocument();+ });++ it('forwards step + stop callbacks to the controller', async () => {+ const controller = makeController({ currentIndex: 2, total: 5 });+ render(<ReplayControls controller={controller} currentEvent={makeEvent(3)} />);++ await userEvent.click(screen.getByRole('button', { name: 'Step backward' }));+ await userEvent.click(screen.getByRole('button', { name: 'Step forward' }));+ await userEvent.click(screen.getByRole('button', { name: 'Stop and rewind' }));+ expect(controller.stepBackward).toHaveBeenCalledTimes(1);+ expect(controller.stepForward).toHaveBeenCalledTimes(1);+ expect(controller.stop).toHaveBeenCalledTimes(1);+ });++ it('drives the speed picker with the active speed', async () => {+ const controller = makeController({ speed: 2 });+ render(<ReplayControls controller={controller} currentEvent={makeEvent(1)} />);++ const select = screen.getByLabelText('Replay speed') as HTMLSelectElement;+ expect(select.value).toBe('2');+ await userEvent.selectOptions(select, '4');+ expect(controller.setSpeed).toHaveBeenLastCalledWith(4);+ });++ it('toggles between fixed and realtime mode', async () => {+ const controller = makeController({ mode: 'fixed' });+ render(<ReplayControls controller={controller} currentEvent={makeEvent(1)} />);++ const fixedBtn = screen.getByRole('button', { name: 'Fixed' });+ const realtimeBtn = screen.getByRole('button', { name: 'Realtime' });+ expect(fixedBtn).toHaveAttribute('aria-pressed', 'true');+ expect(realtimeBtn).toHaveAttribute('aria-pressed', 'false');++ await userEvent.click(realtimeBtn);+ expect(controller.setMode).toHaveBeenLastCalledWith('realtime');+ });++ it('drives the scrubber with the controller index and seeks on input', () => {+ const controller = makeController({ currentIndex: 3, total: 5, progress: 0.75 });+ render(<ReplayControls controller={controller} currentEvent={makeEvent(4)} />);++ const slider = screen.getByLabelText('Seek to step') as HTMLInputElement;+ expect(slider.value).toBe('3');+ expect(slider.max).toBe('4'); // total - 1+ expect(slider.min).toBe('0');++ // userEvent.type doesn't reliably drive native ranges in jsdom — fire a+ // testing-library synthetic change so React picks it up via SyntheticEvent.+ fireEvent.change(slider, { target: { value: '1' } });+ expect(controller.seekToIndex).toHaveBeenLastCalledWith(1);++ expect(screen.getByText('Step 4 of 5')).toBeInTheDocument();+ });++ it('disables the scrubber when there is only one event', () => {+ const controller = makeController({ currentIndex: 0, total: 1 });+ render(<ReplayControls controller={controller} currentEvent={makeEvent(1)} />);+ expect(screen.getByLabelText('Seek to step')).toBeDisabled();+ expect(screen.getByText('Step 1 of 1')).toBeInTheDocument();+ });++ it('shows the current event hint when one is provided', () => {+ const controller = makeController({ currentIndex: 1, total: 5 });+ const evt = makeEvent(2, 'Pulled the failing pod logs');+ render(<ReplayControls controller={controller} currentEvent={evt} />);++ expect(screen.getByText('#2')).toBeInTheDocument();+ expect(screen.getByText(/tool call/i)).toBeInTheDocument();+ expect(screen.getByText('investigator')).toBeInTheDocument();+ expect(screen.getByText('Pulled the failing pod logs')).toBeInTheDocument();+ });++ it('omits the event hint when nothing is selected', () => {+ const controller = makeController({ total: 5, currentIndex: 0 });+ render(<ReplayControls controller={controller} currentEvent={null} />);+ expect(screen.queryByText('#1')).not.toBeInTheDocument();+ });++ it('exposes a screen-reader-only live status for play/pause transitions', () => {+ const controller = makeController({ isPlaying: false });+ const { rerender } = render(+ <ReplayControls controller={controller} currentEvent={makeEvent(1)} />,+ );+ expect(screen.getByText('Replay paused')).toBeInTheDocument();+ const playing = makeController({ isPlaying: true });+ rerender(<ReplayControls controller={playing} currentEvent={makeEvent(1)} />);+ expect(screen.getByText('Replay playing')).toBeInTheDocument();+ });+});diff --git a/apps/web/src/components/cases/replay/ReplayControls.tsx b/apps/web/src/components/cases/replay/ReplayControls.tsxnew file mode 100644index 000000000..d35dbbdbf--- /dev/null+++ b/apps/web/src/components/cases/replay/ReplayControls.tsx@@ -0,0 +1,246 @@+'use client';++/**+ * Replay controls for the investigation ledger (WS-D3).+ *+ * The visible "tape deck" that drives `useReplayController`. Renders five+ * concerns in a single horizontal strip so it can sit beside the timeline+ * filter toolbar without dominating the screen:+ *+ * 1. Mode toggle — fixed cadence vs realtime (each step's own duration)+ * 2. Transport — step back / play–pause / step forward / stop+ * 3. Speed picker — 0.5×, 1×, 2×, 4×, 8×+ * 4. Scrubber — drag any point in the run; shows "step N of M"+ * 5. Cursor label — current event's seq + summary, for at-a-glance context+ *+ * Styling intentionally mirrors `InvestigationLedger.tsx` toolbars+ * (rounded-xl border-slate-800/80 bg-slate-900/40) so the component slots+ * in without bespoke design tokens.+ */++import { clsx } from 'clsx';+import type { LedgerEvent } from '@/lib/api';+import {+ REPLAY_SPEEDS,+ type ReplayController,+ type ReplaySpeed,+} from './useReplayController';++interface ReplayControlsProps {+ controller: ReplayController;+ /** Event currently under the cursor, used for the trailing label. */+ currentEvent: LedgerEvent | null;+}++const baseBtn =+ 'inline-flex items-center justify-center rounded-md border border-slate-700/70 bg-slate-800/50 px-2.5 py-1.5 text-xs font-medium text-slate-200 hover:border-slate-600 disabled:opacity-40 disabled:hover:border-slate-700/70';++const accentBtn =+ 'inline-flex items-center justify-center rounded-md border border-emerald-500/40 bg-emerald-500/10 px-3 py-1.5 text-xs font-semibold text-emerald-200 hover:border-emerald-400/60 disabled:opacity-40 disabled:hover:border-emerald-500/40';++export function ReplayControls({ controller, currentEvent }: ReplayControlsProps) {+ // We deliberately use `toggle` for the play/pause button rather than+ // destructuring `play`/`pause` separately — keeps the click handler simple+ // and makes the play→pause→play cycle feel like a single keyboard target.+ const {+ isPlaying,+ speed,+ mode,+ progress,+ currentIndex,+ total,+ toggle,+ stop,+ stepForward,+ stepBackward,+ seekToIndex,+ setSpeed,+ setMode,+ } = controller;++ const disabled = total === 0;+ // Scrubber uses 0..total-1 indices (clamped). A single-event run still+ // renders the slider (max=0) but it can't be dragged — that's fine; the+ // cursor label still gives the operator something to look at.+ const scrubberMax = Math.max(0, total - 1);+ const scrubberValue = currentIndex ?? 0;++ return (+ <div+ className="flex flex-wrap items-center gap-2 rounded-xl border border-slate-800/80 bg-slate-900/40 px-3 py-2"+ role="region"+ aria-label="Investigation replay controls"+ >+ {/* Mode toggle — fixed vs realtime */}+ <div className="flex items-center gap-1 rounded-md border border-slate-700/70 bg-slate-900/60 p-0.5">+ <ModeButton+ active={mode === 'fixed'}+ onClick={() => setMode('fixed')}+ title="Fixed 1s cadence per step (good for screen recording)"+ >+ Fixed+ </ModeButton>+ <ModeButton+ active={mode === 'realtime'}+ onClick={() => setMode('realtime')}+ title="Use each step's own duration (real agent pacing, clamped 50–8000ms)"+ >+ Realtime+ </ModeButton>+ </div>++ {/* Transport */}+ <div className="flex items-center gap-1">+ <button+ type="button"+ onClick={stepBackward}+ disabled={disabled || (currentIndex ?? 0) <= 0}+ className={baseBtn}+ aria-label="Step backward"+ title="Previous step"+ >+ ◀︎+ </button>+ <button+ type="button"+ onClick={toggle}+ disabled={disabled}+ className={accentBtn}+ aria-label={isPlaying ? 'Pause replay' : 'Play replay'}+ aria-pressed={isPlaying}+ title={isPlaying ? 'Pause' : 'Play'}+ >+ {isPlaying ? '⏸︎ Pause' : '▶︎ Play'}+ </button>+ <button+ type="button"+ onClick={stepForward}+ disabled={disabled || (currentIndex ?? -1) >= total - 1}+ className={baseBtn}+ aria-label="Step forward"+ title="Next step"+ >+ ▶︎+ </button>+ <button+ type="button"+ onClick={stop}+ disabled={disabled}+ className={baseBtn}+ aria-label="Stop and rewind"+ title="Rewind to first step"+ >+ ⏮︎+ </button>+ </div>++ {/* Speed picker */}+ <div className="flex items-center gap-1">+ <span className="text-[11px] uppercase tracking-wide text-slate-500">+ Speed+ </span>+ <select+ value={String(speed)}+ onChange={(e) => setSpeed(Number(e.target.value) as ReplaySpeed)}+ disabled={disabled}+ className="rounded-md border border-slate-700/70 bg-slate-900/60 px-2 py-1.5 text-xs text-slate-200 focus:border-emerald-500/40 focus:outline-none"+ aria-label="Replay speed"+ >+ {REPLAY_SPEEDS.map((s) => (+ <option key={s} value={String(s)}>+ {s}×+ </option>+ ))}+ </select>+ </div>++ {/* Scrubber + cursor label fill remaining space */}+ <div className="ml-auto flex min-w-[260px] flex-1 items-center gap-2">+ <input+ type="range"+ min={0}+ max={scrubberMax}+ step={1}+ value={scrubberValue}+ onChange={(e) => seekToIndex(Number(e.target.value))}+ disabled={disabled || total <= 1}+ aria-label="Seek to step"+ className="h-1.5 w-full cursor-pointer appearance-none rounded-full bg-slate-800 accent-emerald-400 disabled:cursor-not-allowed disabled:opacity-50"+ // Browsers don't expose progress styling for native range inputs, so+ // a simple gradient fills the played portion to the left of the+ // thumb. Falls back gracefully when the slider is disabled.+ style={+ !disabled && total > 1+ ? {+ background: `linear-gradient(to right, rgb(16 185 129 / 0.6) 0%, rgb(16 185 129 / 0.6) ${+ progress * 100+ }%, rgb(15 23 42) ${progress * 100}%, rgb(15 23 42) 100%)`,+ }+ : undefined+ }+ />+ <span+ className={clsx(+ 'whitespace-nowrap text-[11px] tabular-nums',+ disabled ? 'text-slate-600' : 'text-slate-400',+ )}+ >+ {disabled+ ? 'No events'+ : `Step ${(currentIndex ?? 0) + 1} of ${total}`}+ </span>+ </div>++ {/* Current event hint — full-width on small screens, inline on wide */}+ {currentEvent && (+ <div className="basis-full pt-1 text-[11px] text-slate-500">+ <span className="font-mono text-slate-400">#{currentEvent.seq}</span>{' '}+ <span className="uppercase tracking-wide text-slate-500">+ {currentEvent.kind.replace(/_/g, ' ')}+ </span>{' '}+ <span className="text-slate-400">·</span>{' '}+ <span className="text-slate-300">{currentEvent.agent}</span>+ {currentEvent.summary && (+ <>+ {' '}+ <span className="text-slate-400">·</span>{' '}+ <span className="text-slate-400">{currentEvent.summary}</span>+ </>+ )}+ </div>+ )}++ {/* Live-region hint so screen readers announce the playback transition+ without us having to wire a separate aria-live element. */}+ <span className="sr-only" aria-live="polite">+ {isPlaying ? 'Replay playing' : 'Replay paused'}+ </span>+ </div>+ );+}++interface ModeButtonProps {+ active: boolean;+ onClick: () => void;+ title?: string;+ children: React.ReactNode;+}++function ModeButton({ active, onClick, title, children }: ModeButtonProps) {+ return (+ <button+ type="button"+ onClick={onClick}+ title={title}+ aria-pressed={active}+ className={clsx(+ 'rounded px-2 py-1 text-[11px] font-medium transition-colors',+ active+ ? 'bg-emerald-500/15 text-emerald-200 ring-1 ring-inset ring-emerald-500/30'+ : 'text-slate-400 hover:text-slate-200',+ )}+ >+ {children}+ </button>+ );+}diff --git a/apps/web/src/components/cases/replay/useReplayController.test.ts b/apps/web/src/components/cases/replay/useReplayController.test.tsnew file mode 100644index 000000000..e32f290ca--- /dev/null+++ b/apps/web/src/components/cases/replay/useReplayController.test.ts@@ -0,0 +1,328 @@+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";+import { act, renderHook } from "@testing-library/react";+import {+ FIXED_BASE_MS,+ MAX_DELAY_MS,+ MIN_DELAY_MS,+ useReplayController,+} from "./useReplayController";+import type { LedgerEvent } from "@/lib/api";++/**+ * These tests pin the playback contract for WS-D3. The visible behaviour+ * during a customer demo is "press ▶, watch each step light up at a+ * predictable cadence" — so the suite focuses on cadence, ordering, and+ * the auto-pause / auto-snap edge cases that would otherwise silently+ * stall the timeline.+ */++const makeEvent = (seq: number, durationMs = 1000): LedgerEvent => ({+ id: `evt-${seq}`,+ run_id: "run-1",+ seq,+ ts: new Date(2026, 0, 1, 0, 0, seq).toISOString(),+ kind: "tool_call",+ agent: "investigator",+ summary: `step ${seq}`,+ payload: null,+ input_hash: null,+ output_hash: null,+ duration_ms: durationMs,+});++const FIVE = [makeEvent(1), makeEvent(2), makeEvent(3), makeEvent(4), makeEvent(5)];++describe("useReplayController", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ function setup(opts: {+ events?: readonly LedgerEvent[];+ initialSeq?: number | null;+ enabled?: boolean;+ } = {}) {+ const events = opts.events ?? FIVE;+ const setSelectedSeq = vi.fn<(seq: number) => void>();+ let selectedSeq: number | null = opts.initialSeq ?? null;+ setSelectedSeq.mockImplementation((s) => {+ selectedSeq = s;+ });++ const view = renderHook(+ ({ s }: { s: number | null }) =>+ useReplayController({+ events,+ selectedSeq: s,+ setSelectedSeq,+ enabled: opts.enabled ?? true,+ }),+ { initialProps: { s: selectedSeq } },+ );++ const sync = () => view.rerender({ s: selectedSeq });+ return {+ view,+ setSelectedSeq,+ events,+ get selectedSeq() {+ return selectedSeq;+ },+ sync,+ };+ }++ it("starts paused with no cursor when nothing is selected", () => {+ const { view } = setup({ initialSeq: null });+ expect(view.result.current.isPlaying).toBe(false);+ expect(view.result.current.currentIndex).toBeNull();+ expect(view.result.current.progress).toBe(0);+ expect(view.result.current.total).toBe(5);+ });++ it("play() snaps to first event when cursor is null and starts playback", () => {+ const ctx = setup({ initialSeq: null });+ act(() => ctx.view.result.current.play());+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(1);+ expect(ctx.view.result.current.isPlaying).toBe(true);+ });++ it("advances at FIXED_BASE_MS / speed in fixed mode", () => {+ const ctx = setup({ initialSeq: 1 });+ act(() => ctx.view.result.current.play());+ ctx.sync();++ // 1× → 1s per step.+ act(() => {+ vi.advanceTimersByTime(FIXED_BASE_MS - 1);+ });+ expect(ctx.setSelectedSeq).not.toHaveBeenCalled();+ act(() => {+ vi.advanceTimersByTime(1);+ });+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(2);++ // Cursor moves → next tick scheduled.+ ctx.sync();+ act(() => {+ vi.advanceTimersByTime(FIXED_BASE_MS);+ });+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(3);+ });++ it("respects 4× speed in fixed mode", () => {+ const ctx = setup({ initialSeq: 1 });+ act(() => ctx.view.result.current.setSpeed(4));+ act(() => ctx.view.result.current.play());+ ctx.sync();++ act(() => {+ vi.advanceTimersByTime(FIXED_BASE_MS / 4);+ });+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(2);+ });++ it("uses each event's duration_ms in realtime mode (clamped to MIN/MAX)", () => {+ const events = [+ makeEvent(1, 200), // below MIN if MIN > 200? MIN is 50, so 200 is fine.+ makeEvent(2, 60_000), // above MAX, must be clamped.+ makeEvent(3, 1500),+ ];+ const ctx = setup({ events, initialSeq: 1 });+ act(() => ctx.view.result.current.setMode("realtime"));+ act(() => ctx.view.result.current.play());+ ctx.sync();++ // Step 1 → 2 should fire at 200ms (since 200 ∈ [MIN, MAX]).+ act(() => {+ vi.advanceTimersByTime(199);+ });+ expect(ctx.setSelectedSeq).not.toHaveBeenCalled();+ act(() => {+ vi.advanceTimersByTime(1);+ });+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(2);++ // Step 2 → 3 should fire after MAX_DELAY_MS, not 60s.+ ctx.sync();+ act(() => {+ vi.advanceTimersByTime(MAX_DELAY_MS - 1);+ });+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(2);+ act(() => {+ vi.advanceTimersByTime(1);+ });+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(3);+ });++ it("auto-pauses on the last event (no looping)", () => {+ // Start at seq 1 — play() at the last event would re-snap to seq 1, but+ // testing the auto-pause separately keeps the harness simpler.+ const ctx = setup({ initialSeq: 1 });+ act(() => ctx.view.result.current.play());+ ctx.sync();++ // Fast-forward to the end (4 ticks for 5 events starting at index 0).+ for (let i = 0; i < 4; i++) {+ act(() => {+ vi.advanceTimersByTime(FIXED_BASE_MS);+ });+ ctx.sync();+ }+ expect(ctx.selectedSeq).toBe(5);+ // One more tick must not fire any more updates and should auto-pause.+ const callsAtEnd = ctx.setSelectedSeq.mock.calls.length;+ act(() => {+ vi.advanceTimersByTime(FIXED_BASE_MS * 2);+ });+ expect(ctx.setSelectedSeq.mock.calls.length).toBe(callsAtEnd);+ expect(ctx.view.result.current.isPlaying).toBe(false);+ });++ it("play() at the last event rewinds to the first event", () => {+ // Familiar media-player UX: pressing ▶ when parked at the end rewinds.+ const ctx = setup({ initialSeq: 5 });+ act(() => ctx.view.result.current.play());+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(1);+ expect(ctx.view.result.current.isPlaying).toBe(true);+ });++ it("pause() halts playback without changing the cursor", () => {+ const ctx = setup({ initialSeq: 1 });+ act(() => ctx.view.result.current.play());+ ctx.sync();+ act(() => {+ vi.advanceTimersByTime(FIXED_BASE_MS);+ });+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(2);+ ctx.sync();+ act(() => ctx.view.result.current.pause());+ expect(ctx.view.result.current.isPlaying).toBe(false);+ const callsAtPause = ctx.setSelectedSeq.mock.calls.length;+ act(() => {+ vi.advanceTimersByTime(FIXED_BASE_MS * 5);+ });+ expect(ctx.setSelectedSeq.mock.calls.length).toBe(callsAtPause);+ });++ it("stop() pauses and rewinds to the first event", () => {+ const ctx = setup({ initialSeq: 4 });+ act(() => ctx.view.result.current.stop());+ expect(ctx.view.result.current.isPlaying).toBe(false);+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(1);+ });++ it("stepForward / stepBackward clamp at the bounds", () => {+ const ctx = setup({ initialSeq: 5 });+ act(() => ctx.view.result.current.stepForward());+ // Already at last → no-op (still calls with 5).+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(5);++ act(() => ctx.view.result.current.stepBackward());+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(4);+ });++ it("seekToIndex clamps to [0, total - 1]", () => {+ const ctx = setup({ initialSeq: 1 });+ act(() => ctx.view.result.current.seekToIndex(99));+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(5);+ act(() => ctx.view.result.current.seekToIndex(-3));+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(1);+ });++ it("toggle() flips between playing and paused", () => {+ const ctx = setup({ initialSeq: 1 });+ expect(ctx.view.result.current.isPlaying).toBe(false);+ act(() => ctx.view.result.current.toggle());+ expect(ctx.view.result.current.isPlaying).toBe(true);+ act(() => ctx.view.result.current.toggle());+ expect(ctx.view.result.current.isPlaying).toBe(false);+ });++ it("disabling replay pauses without resetting the cursor", () => {+ const setSelectedSeq = vi.fn<(seq: number) => void>();+ let selectedSeq: number | null = 3;+ setSelectedSeq.mockImplementation((s) => {+ selectedSeq = s;+ });+ const view = renderHook(+ ({ enabled, s }: { enabled: boolean; s: number | null }) =>+ useReplayController({+ events: FIVE,+ selectedSeq: s,+ setSelectedSeq,+ enabled,+ }),+ { initialProps: { enabled: true, s: selectedSeq } },+ );+ act(() => view.result.current.play());+ expect(view.result.current.isPlaying).toBe(true);+ view.rerender({ enabled: false, s: selectedSeq });+ expect(view.result.current.isPlaying).toBe(false);+ expect(view.result.current.currentIndex).toBe(2); // seq 3 → index 2+ });++ it("snaps cursor to the last event when filter drops the active step", () => {+ const setSelectedSeq = vi.fn<(seq: number) => void>();+ let selectedSeq: number | null = 5;+ setSelectedSeq.mockImplementation((s) => {+ selectedSeq = s;+ });+ const view = renderHook(+ ({+ events,+ s,+ }: {+ events: readonly LedgerEvent[];+ s: number | null;+ }) =>+ useReplayController({+ events,+ selectedSeq: s,+ setSelectedSeq,+ enabled: true,+ }),+ { initialProps: { events: FIVE, s: selectedSeq } },+ );+ expect(view.result.current.currentIndex).toBe(4);++ // Apply a filter that drops seq=5.+ const filtered = FIVE.slice(0, 3); // seq 1..3+ view.rerender({ events: filtered, s: selectedSeq });+ expect(setSelectedSeq).toHaveBeenLastCalledWith(3);+ });++ it("respects MIN_DELAY_MS lower bound when speed × duration is tiny", () => {+ const events = [makeEvent(1, 10), makeEvent(2, 10)];+ const ctx = setup({ events, initialSeq: 1 });+ act(() => ctx.view.result.current.setMode("realtime"));+ act(() => ctx.view.result.current.setSpeed(8));+ act(() => ctx.view.result.current.play());+ ctx.sync();++ // 10ms duration → clamped to MIN_DELAY_MS (50ms).+ act(() => {+ vi.advanceTimersByTime(MIN_DELAY_MS - 1);+ });+ expect(ctx.setSelectedSeq).not.toHaveBeenCalled();+ act(() => {+ vi.advanceTimersByTime(1);+ });+ expect(ctx.setSelectedSeq).toHaveBeenLastCalledWith(2);+ });++ it("progress reflects cursor position", () => {+ const ctx = setup({ initialSeq: 1 });+ expect(ctx.view.result.current.progress).toBe(0);++ const view2 = setup({ initialSeq: 5 });+ expect(view2.view.result.current.progress).toBe(1);++ const view3 = setup({ initialSeq: 3 });+ expect(view3.view.result.current.progress).toBeCloseTo(0.5, 5);+ });+});diff --git a/apps/web/src/components/cases/replay/useReplayController.ts b/apps/web/src/components/cases/replay/useReplayController.tsnew file mode 100644index 000000000..6937f0af8--- /dev/null+++ b/apps/web/src/components/cases/replay/useReplayController.ts@@ -0,0 +1,257 @@+/**+ * Replay controller for the investigation ledger (WS-D3).+ *+ * Drives the parent timeline's `selectedSeq` programmatically while playing,+ * supporting two cadences:+ *+ * - `fixed` each event holds for FIXED_BASE_MS / speed (default 1s)+ * - `realtime` each event holds for its own `duration_ms / speed`,+ * clamped to [MIN_DELAY_MS, MAX_DELAY_MS] so demos stay snappy+ * even when the agent had a 30s LLM call mid-run+ *+ * The hook is intentionally agnostic about how the parent renders the+ * timeline — it just consumes an ordered events list and the parent's+ * `selectedSeq` setter. That keeps `InvestigationLedger.tsx` free of new+ * playback logic and lets us unit-test the controller in isolation.+ *+ * Auto-pause behavior:+ * - Reaching the last event pauses (instead of looping).+ * - Flipping `enabled=false` pauses but preserves the cursor position.+ * - When the events list shrinks below the cursor (filter change), the+ * cursor snaps to the new last event.+ */++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import type { LedgerEvent } from "@/lib/api";++export type ReplayMode = "fixed" | "realtime";++export type ReplaySpeed = 0.5 | 1 | 2 | 4 | 8;++export const REPLAY_SPEEDS: readonly ReplaySpeed[] = [0.5, 1, 2, 4, 8] as const;++/** Base cadence (ms) per event in `fixed` mode at 1× speed. */+export const FIXED_BASE_MS = 1000;++/** Lower bound on tick delay so the UI never appears frozen. */+export const MIN_DELAY_MS = 50;++/** Upper bound so a single 30s LLM call doesn't stall replay. */+export const MAX_DELAY_MS = 8000;++export interface ReplayControllerArgs {+ /** Ordered events list (post-filter). Drives playback ordering. */+ events: readonly LedgerEvent[];+ /** Currently highlighted seq in the parent timeline. */+ selectedSeq: number | null;+ /** Setter the parent uses to highlight a step. */+ setSelectedSeq: (seq: number) => void;+ /**+ * Whether replay mode is on. When off, playback halts but the controller+ * keeps its position so toggling back on resumes from the same step.+ */+ enabled: boolean;+}++export interface ReplayController {+ isPlaying: boolean;+ speed: ReplaySpeed;+ mode: ReplayMode;+ /** 0..1 fraction of progress (0 if total <= 1). */+ progress: number;+ /** 0-based index of the current cursor event in `events` (or null). */+ currentIndex: number | null;+ /** Total event count (filtered). */+ total: number;+ // Controls+ play: () => void;+ pause: () => void;+ toggle: () => void;+ /** Pause and reset cursor to the first event. */+ stop: () => void;+ stepForward: () => void;+ stepBackward: () => void;+ seekToIndex: (index: number) => void;+ setSpeed: (s: ReplaySpeed) => void;+ setMode: (m: ReplayMode) => void;+}++export function useReplayController({+ events,+ selectedSeq,+ setSelectedSeq,+ enabled,+}: ReplayControllerArgs): ReplayController {+ const [isPlaying, setIsPlaying] = useState(false);+ const [speed, setSpeed] = useState<ReplaySpeed>(1);+ const [mode, setMode] = useState<ReplayMode>("fixed");++ const total = events.length;++ // seq → index lookup, recomputed only when the events list changes. Avoids+ // O(n) work in the playback loop on every tick.+ const seqIndex = useMemo(() => {+ const m = new Map<number, number>();+ events.forEach((e, i) => m.set(e.seq, i));+ return m;+ }, [events]);++ const currentIndex = useMemo(() => {+ if (total === 0 || selectedSeq == null) return null;+ return seqIndex.get(selectedSeq) ?? null;+ }, [selectedSeq, seqIndex, total]);++ // Disabling replay mode pauses without clearing position.+ useEffect(() => {+ if (!enabled && isPlaying) setIsPlaying(false);+ }, [enabled, isPlaying]);++ // If a filter change drops the cursor's event from `events`, snap to last.+ // Without this, replay would silently sit on a no-longer-rendered step.+ useEffect(() => {+ if (+ total > 0 &&+ selectedSeq != null &&+ seqIndex.get(selectedSeq) === undefined+ ) {+ setSelectedSeq(events[total - 1]!.seq);+ }+ }, [total, selectedSeq, seqIndex, events, setSelectedSeq]);++ // Playback loop. Whenever the cursor moves or playback flips on, schedule+ // a single timeout for the next step. We deliberately avoid setInterval —+ // it accumulates drift and ignores per-event duration in `realtime` mode.+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ // Set by play() when it snaps the cursor back to the first event so the+ // user can replay from the start. The parent's `selectedSeq` prop only+ // updates on the next render cycle, so without this flag the auto-pause+ // branch below would fire on the in-between render where currentIndex+ // still points at the terminal event. Cleared on the first render where+ // currentIndex is no longer terminal.+ const pendingRewindRef = useRef(false);+ useEffect(() => {+ if (timeoutRef.current) {+ clearTimeout(timeoutRef.current);+ timeoutRef.current = null;+ }+ if (!isPlaying || !enabled || total === 0) return;+ if (currentIndex == null) {+ // Playing with nothing selected → snap to first event so the next+ // tick has a defined starting point.+ setSelectedSeq(events[0]!.seq);+ return;+ }+ if (currentIndex >= total - 1) {+ if (pendingRewindRef.current) {+ // The user pressed play at the end; wait one render for the parent+ // to propagate the rewind, then resume normally.+ return;+ }+ // Reached the end — auto-pause rather than loop.+ setIsPlaying(false);+ return;+ }+ // Cursor has advanced past the terminal event — rewind handshake done.+ pendingRewindRef.current = false;+ const here = events[currentIndex]!;+ const baseMs =+ mode === "realtime"+ ? Math.max(MIN_DELAY_MS, here.duration_ms || FIXED_BASE_MS)+ : FIXED_BASE_MS;+ const delay = Math.min(+ MAX_DELAY_MS,+ Math.max(MIN_DELAY_MS, baseMs / speed),+ );+ timeoutRef.current = setTimeout(() => {+ const next = events[currentIndex + 1];+ if (next) setSelectedSeq(next.seq);+ }, delay);++ return () => {+ if (timeoutRef.current) {+ clearTimeout(timeoutRef.current);+ timeoutRef.current = null;+ }+ };+ }, [+ isPlaying,+ enabled,+ currentIndex,+ total,+ events,+ mode,+ speed,+ setSelectedSeq,+ ]);++ const play = useCallback(() => {+ if (total === 0) return;+ if (currentIndex == null || currentIndex >= total - 1) {+ // Pressing play with nothing selected, or while parked at the end,+ // should restart from the beginning. This matches typical media+ // player UX where ▶ at the end rewinds.+ setSelectedSeq(events[0]!.seq);+ // Tell the playback effect that the impending currentIndex change is+ // expected, so it doesn't auto-pause on the in-between render where+ // selectedSeq still points to the terminal event.+ pendingRewindRef.current = true;+ }+ setIsPlaying(true);+ }, [total, currentIndex, events, setSelectedSeq]);++ const pause = useCallback(() => setIsPlaying(false), []);++ const toggle = useCallback(() => {+ if (isPlaying) setIsPlaying(false);+ else play();+ }, [isPlaying, play]);++ const stop = useCallback(() => {+ setIsPlaying(false);+ if (total > 0) setSelectedSeq(events[0]!.seq);+ }, [total, events, setSelectedSeq]);++ const stepForward = useCallback(() => {+ if (total === 0) return;+ const next =+ currentIndex == null ? 0 : Math.min(currentIndex + 1, total - 1);+ setSelectedSeq(events[next]!.seq);+ }, [currentIndex, total, events, setSelectedSeq]);++ const stepBackward = useCallback(() => {+ if (total === 0) return;+ const prev =+ currentIndex == null ? 0 : Math.max(currentIndex - 1, 0);+ setSelectedSeq(events[prev]!.seq);+ }, [currentIndex, total, events, setSelectedSeq]);++ const seekToIndex = useCallback(+ (index: number) => {+ if (total === 0) return;+ const clamped = Math.max(0, Math.min(index, total - 1));+ setSelectedSeq(events[clamped]!.seq);+ },+ [total, events, setSelectedSeq],+ );++ const progress =+ total <= 1 || currentIndex == null ? 0 : currentIndex / (total - 1);++ return {+ isPlaying,+ speed,+ mode,+ progress,+ currentIndex,+ total,+ play,+ pause,+ toggle,+ stop,+ stepForward,+ stepBackward,+ seekToIndex,+ setSpeed,+ setMode,+ };+}