Repository navigation
Frontend
The frontend is a Next.js 15.5 application using the App Router, React 19, TypeScript, and TailwindCSS 4. It communicates with the backend exclusively via the REST API and SSE stream.
frontend/src/
βββ app/ # Next.js App Router
β βββ layout.tsx # Root layout β providers, theme, fonts
β βββ page.tsx # Home page β search box + results
β βββ sessions/ # Session management pages
β βββ admin/ # Admin-only pages (user management)
βββ components/
β βββ graph/
β β βββ CausalGraph.tsx # Main React Flow wrapper
β β βββ EventNode.tsx # Custom node component
β β βββ CausalEdge.tsx # Custom edge component
β βββ results/
β β βββ StreamingNarrative.tsx # Markdown + streaming text display
β β βββ SourceCitations.tsx # Citations panel, grouped by tier
β βββ search/
β β βββ SearchBox.tsx # Query input with submit
β β βββ PresetPrompts.tsx # 12 starter question cards
β βββ timeline/
β β βββ D3Timeline.tsx # D3 zoomable timeline
β βββ sessions/
β βββ SessionList.tsx # Sidebar session list
β βββ SaveDialog.tsx # Name-and-save modal
βββ hooks/
β βββ useStreamingQuery.ts # SSE connection + event parsing
β βββ useGraph.ts # React Flow state management
β βββ useSessions.ts # Session CRUD
β βββ usePresets.ts # Preset question fetching
βββ lib/
β βββ api.ts # Typed fetch wrappers for all API calls
β βββ sse.ts # SSE client utilities
β βββ types.ts # Shared TypeScript types
β βββ utils.ts # Helpers (classnames, date formatting)
βββ providers/
βββ AuthProvider.tsx # JWT context + login/logout
βββ ThemeProvider.tsx # next-themes dark/light wrapper
The app uses the App Router (not Pages Router). Route segments:
-
/β the main analysis page (search + results) -
/sessionsβ session list and session detail view -
/adminβ user management (redirects non-admins)
Client components (those using hooks, browser APIs, or event handlers) are marked with "use client". Server components are used for static layout, metadata, and font loading.
State is managed by a single Zustand store (frontend/src/lib/store.ts or similar). The store holds:
-
currentQueryβ the active question string -
sessionIdβ active session UUID -
narrativeβ accumulated streaming text -
nodes/edgesβ React Flow graph state -
timelineβ D3 timeline data -
sourcesβ citation list -
isStreamingβ boolean, true while SSE is open -
streamingPhaseβ current phase number (1β4), used for progress indicator
The store is not persisted to localStorage β sessions are persisted server-side. On page reload, the last active session is re-fetched from the API.
frontend/src/hooks/useStreamingQuery.ts
Opens an SSE connection to POST /api/query, parses each event type, and dispatches to the Zustand store. Key behaviours:
- Uses the Fetch API with
ReadableStream(not theEventSourceAPI) so POST requests with a body are supported βEventSourceonly does GET - Maintains an internal buffer to handle cases where multiple SSE events arrive in the same chunk
- On
narrativeevents: appends the chunk to thenarrativestore field - On first
graphevent: sets nodes and timeline, leaves edges empty - On second
graphevent: merges edges into existing node state - On
doneor error: setsisStreaming = false, closes the stream - Exposes a
cancel()function that aborts the fetch and closes the stream
frontend/src/hooks/useGraph.ts
Wraps React Flow's internal state with the app's graph data. Handles:
- Receiving node/edge arrays from the store and converting to React Flow format
- Running Dagre layout when edges are first added
- Exposing
onNodesChangeandonEdgesChangehandlers for user edits -
saveGraph()β debounced call toPATCH /api/sessions/{id}/graphafter user edits -
exportPNG()β uses React Flow'sgetNodes()+ HTML Canvas to export the graph as a PNG file
frontend/src/hooks/useSessions.ts
Manages session CRUD:
-
sessionsβ list of the user's sessions -
loadSession(id)β fetches full session detail and restores narrative + graph state -
saveCurrentSession(name)β creates or renames the active session -
deleteSession(id)β deletes and removes from list
frontend/src/hooks/usePresets.ts
Fetches the 12 preset questions from GET /api/presets on mount. Simple: no pagination, no caching beyond the component lifecycle.
CausalGraph.tsx wraps the React Flow <ReactFlow> component with:
-
nodeTypes={{ eventNode: EventNode }}β registers the custom node -
edgeTypes={{ causalEdge: CausalEdge }}β registers the custom edge - Controls panel (zoom in/out, fit view, export PNG)
- MiniMap for orientation on large graphs
- Background grid pattern
EventNode (graph/EventNode.tsx):
Renders as a styled card with: event name (bold), date (muted), type badge (colour-coded: political/military/economic/social/cultural), and a truncated description. Handle positions: left (target) and right (source). Selected state shows a highlighted border.
CausalEdge (graph/CausalEdge.tsx):
Custom edge component using React Flow's getStraightPath or getBezierPath. Opacity is set from data.confidence (0.3β1.0 β 30%β100% opacity). Edge label shows the relationship type on hover. Colour is determined by relationship type:
-
direct_causeβ red -
contributing_factorβ orange -
enabling_conditionβ yellow -
consequenceβ blue -
feedback_loopβ purple
D3Timeline.tsx renders a zoomable horizontal timeline using D3.js 7. Events are positioned by their date_numeric value (decimal year). Zoom is handled by d3.zoom() with x-axis rescaling. Clicking a timeline event highlights the corresponding node in React Flow (via shared event ID).
The timeline is rendered into a <svg> element via a useEffect hook that runs D3 imperatively. D3 manages the DOM inside the SVG directly; React manages the container. This is intentional β mixing React and D3 for the same DOM nodes causes conflicts.
The Fetch API returns a ReadableStream<Uint8Array>. The hook reads this with a TextDecoder and accumulates text until it finds complete event: / data: pairs. SSE events are separated by blank lines (\n\n). The parser:
- Splits on
\n\n - For each complete event block, extracts the
event:type anddata:JSON - Calls the appropriate Zustand action
- Leaves incomplete blocks in a carry buffer for the next chunk
ThemeProvider.tsx wraps next-themes's ThemeProvider. The root layout applies the theme class to <html>. TailwindCSS 4 uses CSS variables for all colour tokens β switching theme classes swaps the variable values, no JavaScript rerender needed.
The theme toggle button (in the top navigation) calls useTheme().setTheme(...) from next-themes.
AuthProvider.tsx holds the JWT token in memory (not localStorage, to reduce XSS surface area). On mount, it attempts to restore the session from a httpOnly cookie managed by Next.js middleware β if the cookie is present and the token is valid, the user is considered logged in without showing the login screen.
Protected routes check useAuth().isAuthenticated. If false, they redirect to the login page. The login form calls POST /auth/login, stores the returned token, and redirects to /.
Admin routes additionally check useAuth().user.is_admin and redirect non-admin users.