UI Architecture

How the Next.js frontend is structured — the RSC/client boundary, how SSE streaming is consumed, and where conversation state lives.


The frontend is a Next.js App Router app split between two rendering environments. The server fetches branding data before the page reaches the browser, so the page arrives fully styled on first load. All chat state — messages, streaming, input — lives in the browser.


Component tree

page.tsx  (RSC — runs on server)
│  fetches /api/clients/:id/branding at render time
│  passes BrandingData down as props
│
└─ ClientShell.tsx  ("use client")
   │  header, theme toggle, back nav
   │
   └─ ChatPanel.tsx  ("use client")
        message list, streaming state, input
        drives SSE stream to FastAPI
        renders text + citation popovers

RSC / client boundary

page.tsx is a React Server Component. It calls the FastAPI branding endpoint before the page reaches the browser, so ClientShell and ChatPanel receive primary_color, assistant_name, and the client name as props — no client-side fetch, no loading flash.

The boundary sits exactly at ClientShell. Everything above it (the branding fetch) runs once per request and produces no JS bundle output. Everything below it ("use client") is interactive and ships to the browser.

The alternative — fetching branding inside a client component — adds a waterfall: the JS bundle loads, hydrates, requests branding, then renders. The RSC path collapses all of that to a single server round-trip.

If the branding fetch fails (unknown client_id), the RSC throws, Next.js renders its error boundary, and ChatPanel never mounts.


SSE consumer

ChatPanel connects to FastAPI’s streaming endpoint with a fetch POST, not EventSource. The browser’s EventSource API is GET-only, which means it cannot send a request body. Since each message needs a body (message, conversation_id), the chat panel uses fetch with a ReadableStream reader and a hand-written parseSse parser:

const res = await fetch(`/api/c/${branding.id}/chat/stream`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ message: question, conversation_id: conversationId }),
});

const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";

for (;;) {
  const { done, value } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });
  const { events, rest } = parseSse(buffer);
  buffer = rest;
  for (const { event, data } of events) handleEvent(event, data);
}

parseSse splits on \n\n and returns unparsed bytes as rest. This handles chunks that arrive mid-frame — the next iteration picks up where the previous one left off. Malformed frames are dropped silently.

handleEvent dispatches into React state:

EventEffect
runStores the run_id for the turn
stepAppends a stage to the live step trail and to the message
tool startShows a “Searching…” indicator below the last message
tool endRemoves the indicator
textAppends the delta to the current assistant message
citationPushes a citation part onto the current message’s part list
doneStores conversation_id; attaches the cost and latency badge
errorRenders the error string inside the assistant bubble

Unknown events are dropped silently. Backend work on a new event type stays invisible until a case is added here — which is why the graph’s step events needed a frontend change to become visible at all.

For the full SSE event contract, see SSE Streaming.


The step trail

Graph turns render an audit trail above the reply. It is the deliverable, not decoration: it shows why a question was answered, searched again or escalated, which is what an escalation decision has to be able to justify.

interface RunStep {
  seq: number;
  stage: string;         // retrieve | grade | converse | rewrite | hybrid_retrieve
                         // | regrade | answer | escalate | ticket
  status: string;
  reasoning?: string;
  latency_ms?: number;
  // node-specific: n_hits, top_similarity, confidence, queries, keywords,
  //                category, n_citations, ticket_id
}

ChatPanel attaches each step to the assistant message as it arrives (msg.steps), so the trail renders before the assistant has produced any text and stays after the stream ends.

StepTrail renders a collapsible timeline, open while live and collapsed afterwards. stageLabel maps node names to human phrasing (“Graded the evidence”, “Searched again: keyword + semantic”), and stageDetail renders the number that mattered for that node: the confidence, the hit count, the rewrite count and keywords, the ticket id. Escalated runs colour their trail differently from answered ones.

The amber “escalated” badge fires on escalate and ticket steps only. A greeting ends at its own converse node, labelled “Not a support request · no ticket”, so it can never be badged as an escalation.

The trail survives a reload. Steps live in the runs table, not on the message row, and the assistant Message carries a run_id to join back through. Replaying a conversation rehydrates msg.steps from that join. See Runs & Durability.


The ticket proposal

An escalating turn ends with a ticket_proposal event, not a filed ticket. ChatPanel stores it on the assistant message alongside a proposalState of open | filing | filed | declined, and TicketProposalCard renders the draft — subject, category, priority — under the reply, with Open this ticket and Not now.

Confirming posts to /api/c/{client_id}/runs/{run_id}/ticket through a Next route handler, with no request body. The draft lives in the run’s checkpoint server-side, so the client can accept an offer but cannot author a ticket of its own. The response’s reply is appended as a new assistant message rather than mutating the one that made the offer, so the conversation reads as offer-then-confirmation, which is what actually happened.

A pending offer does not survive a reload. The filed confirmation is persisted as its own assistant turn and comes back with history; an unanswered proposal is only a button, and historyToMessages does not rebuild it. What is lost is the shortcut, not the record — the user can ask again. Restoring it would mean reading the paused graph’s pending interrupt back through the history endpoint, which is more API surface than a re-ask costs.


Conversation state

The API is stateless between turns. ChatPanel stores conversationId in React state, receives it from the done event on the first turn, and sends it back in the body of every subsequent POST. The server uses it to load history from Postgres.

No cookie, no session middleware, no in-memory store on the server. The client owns continuity; the server looks up the row.

Refreshing the page clears conversationId and starts a new conversation. That is an intentional trade-off for a demo tool — it eliminates an entire class of session-management complexity with no meaningful cost to the use case.


Message model

Messages are not plain strings. Each assistant message is a list of Part values:

type Part =
  | { kind: "text"; text: string }
  | { kind: "cite"; index: number; source: string; title: string; cited_text: string };

Text and citation events from the SSE stream arrive interleaved. The part list preserves that order, so citations render inline immediately after the passage they annotate — not as a footnote list at the bottom.

groupParts clusters a text run with the citations that immediately follow it before rendering. This produces { text, cites[] } groups, where each group renders as a paragraph with inline citation badges.

See Citations for how citation data is generated on the backend.