Skip to content

    Frontend System Design

    Chat Interface State and the Message Model

    Model a chat screen's state: messages with ids and statuses, Stop and Regenerate, late chunks refused by attempt number, and what is sent to a model next.

    By Published 12 min read

    • frontend-system-design
    • ai-ui
    • chat
    • state-management
    Share

    Standard lessonintermediateReact labFrontend System Design

    Before this: Streaming LLM Responses in the Browser

    What you'll learn: By the end of this lesson you will be able to design the state of a chat screen as a list of messages with an id, a role, text and a status, write one pure reducer for it, say what Stop, Failure and Regenerate must do to a half-written answer, stop a late chunk from a finished or replaced stream from writing into the screen, and explain why the list on screen is not the list you send to a model.

    Think of a group chat on your phone with a friend who types slowly. You see "typing..." and then words appear. If you cancel mid-sentence, the words so far stay. If their phone drops out, you see a half-sentence and a warning. If you ask them to say it again, the old half-sentence must not mix with the new one. A chat screen for an AI model is that conversation, with one participant that writes in small pieces.

    The running example is a support assistant on a shop. The lab's questions and answers are made up. The streaming transport (fetch and the stream of chunks) belongs to the lesson on streaming model responses in the browser; this lesson starts when a chunk has arrived and asks what the screen's state must be.

    The core idea

    1. A message is not finished when it appears. An assistant message starts empty and grows. It needs a status: streaming, complete, stopped or failed. Every rule in a chat screen is a rule about what each status allows.
    2. One pure function owns the rules. applyChat(state, action) takes the old state and one action and returns the next state. Timers, fetch and React sit around it, because React says reducers "must be pure": same inputs, same output, no requests, no timeouts, no mutation.
    3. Chunks must say which stream they came from. A chunk that arrives after Stop, or from an answer the user regenerated, has to be refused. An attempt number on every chunk makes that a one-line check.

    Three illustrations run through the lesson: a minimal example (one question, one streamed answer), a realistic example (Stop, a failure and Regenerate on the support assistant) and a failure example (a late chunk from a replaced answer).

    What a message is

    The lab's message has seven fields.

    Field Meaning Why it exists
    id Stable identity, made by a counter in the lab A React key, and the target of every chunk
    role user or assistant Who said it
    text The words so far Grows while streaming
    status streaming, complete, stopped, error What the row shows and what actions are allowed
    attempt 1, then 2 after Regenerate Tells a chunk which stream it belongs to
    replyTo The user message this answers Keeps the pair together
    error A short message Shown under the partial text

    The state around it is a list of ids, a map of messages by id, the id that is streaming (or null) and a counter. Keeping the ids and the messages apart means a chunk replaces one entry in the map and leaves the list alone. React says to treat arrays in state as read-only and create a new one instead, and the same idea applies to the map.

    The lab uses one text string. Real products give a message parts (text, a tool call, a source). The Vercel AI SDK documentation says its UI messages have "a new parts property that contains the message parts", and its chat status values are submitted, streaming, ready and error. The lab names its states per message instead of per chat, and the idea is the same: the UI state is not only the text. Tool calls are a later lesson in this course.

    Figure 1. Where the state lives

    A pure reducer owns the rules; a small store, a fake provider and thin React components sit around itComposer to Chat store (submit, stop); Chat store to Rows (notify); Provider to Chat store (delta, finish)Composer: Send, StopComposerSend, StopChat store: reducer, subscribeChat storereducer,subscribeRows: one per messageRowsone per messageProvider: fake streamProviderfake streamsubmit, stopnotifydelta, finish

    How to read this: user actions and stream events enter the same store through the same actions. Rows only read.

    Status: the life of one answer

    Figure 2. Statuses of an assistant message

    stateDiagram-v2 accTitle: Statuses of an assistant message accDescr: A new assistant message is streaming. A finish event makes it complete, a fail event makes it error, and Stop makes it stopped. From complete, stopped or error, Regenerate returns it to streaming with the attempt number increased by one. [*] --> streaming: submit streaming --> complete: finish streaming --> error: fail streaming --> stopped: stop complete --> streaming: regenerate stopped --> streaming: regenerate error --> streaming: regenerate

    How to read this: only a streaming message accepts chunks, and only a message that is not streaming accepts Regenerate.

    Three decisions in the lab are worth making on purpose.

    • Keep partial text on Stop and on failure. The user has read it. Deleting it makes the screen jump and loses information; the status says what happened. The lab shows "Stopped", or "Failed:" plus the error, under the text.
    • One stream at a time. While a message is streaming, Send is refused and the screen shows Stop instead. The reducer enforces it by returning the same state object, so the rule does not depend on a disabled button.
    • Regenerate only the last assistant message. The AI SDK documentation describes its regenerate as one that will "regenerate the last message and replace the current one correspondingly". Regenerating an earlier answer means deciding what happens to everything after it, which this lab does not do.

    Late chunks and attempt numbers

    A stream is asynchronous, and the user is not. Stop makes the message stopped, but a chunk may already be on its way. Because a message that is not streaming ignores chunks, that one is harmless. Regenerate is harder: the message is streaming again, with the same id, so a straggler from the first answer looks valid. The attempt number separates them.

    Figure 3. A straggler from attempt 1 meets attempt 2

    sequenceDiagram accTitle: A late chunk from a replaced answer accDescr: The user presses Stop while attempt 1 streams. Regenerate starts attempt 2 on the same message. A chunk from attempt 1 arrives late and is refused because its attempt does not match. A chunk from attempt 2 is applied. participant U as User participant S as Chat store participant P as Provider P->>S: delta (attempt 1, "Kafka") U->>S: stop U->>S: regenerate (attempt 2) P->>S: delta (attempt 1, " and more") Note over S: refused: stale attempt P->>S: delta (attempt 2, "RabbitMQ") Note over S: applied

    How to read this: the same message id is reused, so the id alone cannot tell the two streams apart. The number the request was started with can.

    On the network side, stopping a request means aborting it: the MDN AbortController page says abort() "is able to abort fetch requests, consumption of any response bodies, and streams". That tells the browser to stop reading. It does not guarantee that no chunk is already queued in your own code, so the reducer check stays. The lesson on request cancellation covers the signal itself: Request Cancellation, Timeouts and Race Conditions.

    The same principle appears in React's own advice for effects that fetch: the cleanup should "either abort the fetch or ignore its result", and React adds that aborting alone is not enough because more async steps may follow, so an explicit flag is "the most reliable way". The attempt number is that flag, stored in state.

    Build it: statuses, stale chunks and the wire list

    Goal. Run the model through stop, failure, regenerate and refused actions, and see what would be sent to a model.

    Setup. The lab is examples/frontend/labs/chat-message-model (Node 26.13.1, React 19, Vitest 5.1.0, jsdom). The core is pure TypeScript; React is a thin layer tested under jsdom, which is not a browser.

    cd examples/frontend
    pnpm install
    cd labs/chat-message-model
    pnpm test           # 24 tests
    node src/demo.ts

    Steps. Run the tests and the demo. In the first block below find that the late chunk and the late finish both return ignored-not-streaming and leave the state object unchanged. Then find the stale attempt in section 4.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01; sections 2 to 4 of the demo):

    === 2. Stop: the user keeps the partial text, and a chunk that arrives afterwards is ignored
    stop -> applied
    late chunk -> ignored-not-streaming
    late finish -> ignored-not-streaming
    state unchanged by the late events: true
      m1 user      complete  attempt 1 "Explain CDNs"
      m2 assistant stopped   attempt 1 "A CDN serves copies "
    stop again -> ignored-not-streaming
    
    === 3. Failure after some text: the partial answer stays on screen, marked as failed
      m1 user      complete  attempt 1 "List three HTTP methods"
      m2 assistant error     attempt 1 "GET, POST, " error="connection lost"
    composer can send again: true
    
    === 4. Regenerate: attempt 2 reuses the message id, so a chunk from attempt 1 must be refused
    regenerate -> applied
    attempt of the new stream: 2
    late chunk from attempt 1 -> ignored-stale-attempt
      m1 user      complete  attempt 1 "Name a queue"
      m2 assistant complete  attempt 2 "RabbitMQ"

    The React tests render the real components. A chunk for the streaming message commits only that row, typing in the composer commits no row, and a refused Send commits nothing. The rows read the store with useSyncExternalStore, whose getSnapshot "must return the same value" while the store has not changed, which is why the reducer keeps unchanged messages as the same objects. The sibling lesson on Real-Time Data in React State and Query Caches goes further into batching many chunks into one redraw.

    What the lab does not show. There is no model, no network and no real timing. Chunks are released by hand. jsdom does no layout, so scrolling to the newest message and how streaming looks are not covered. Messages are plain text; showing model output as rich text or HTML is a security question for another lesson in this course. Persisting the conversation is covered in Offline Queues and Background Sync for the sending side.

    Break it. In src/chat.ts, delete the line if (message.attempt !== action.attempt) return ignored(state, "ignored-stale-attempt");. A chunk from attempt 1 now writes into attempt 2, and two tests fail. Restore the line.

    The list on screen is not the list you send

    The next request is built from the state, and it is a different list. Some APIs expect alternating turns. Anthropic's Messages documentation says its models "are trained to operate on alternating user and assistant conversational turns" and that "consecutive user or assistant turns in your request will be combined into a single turn". The same page says that a final assistant message is prefill: "the response content will continue immediately from the content in that message", and that on models without prefill support a request ending in a partial assistant message returns a 400 error. So sending a stopped half-answer as the last message is not a neutral choice.

    The lab's rules are its own, and are labelled so in the code: leave out streaming and failed messages, keep a stopped message that has text (the user saw it), and merge neighbours with the same role.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01; section 7 of the demo):

    === 7. What the next request would carry (not the same list as the screen)
    on screen:
      m1 user      complete  attempt 1 "Q1"
      m2 assistant complete  attempt 1 "A1"
      m3 user      complete  attempt 1 "Q2"
      m4 assistant stopped   attempt 1 "Half of A2"
      m5 user      complete  attempt 1 "Q3"
      m6 assistant error     attempt 1 "" error="timeout"
      m7 user      complete  attempt 1 "Q4"
      m8 assistant streaming attempt 1 ""
    sent to the model:
      user      "Q1"
      assistant "A1"
      user      "Q2"
      assistant "Half of A2"
      user      "Q3\n\nQ4"

    A system prompt is not a message in this list: the Anthropic page says to use the top-level system parameter for it. The shape differs between providers, so keep the conversion in one function and test it.

    Trade-offs

    Choice Gain Cost
    Per-message status Each row knows what to show; rules are testable More states to design and test
    Keep partial text on Stop and error Nothing the user read disappears A partial answer can be misleading and must be marked
    Attempt number on chunks Stale chunks are refused in one line Every chunk must carry it, and the request must capture it
    Ids and a map A chunk changes one entry Two structures to keep in step
    Reducer refuses actions (same object) No dependence on disabled buttons Callers must read the outcome

    In practice: a support assistant that mixed two answers

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A shop adds an assistant to its help page. The first version keeps one useState holding the last answer as a string and a loading boolean. Users press Regenerate when the answer is unhelpful.

    Starting architecture

    Figure 4. Starting point: one string, one flag

    Starting architecture: every chunk writes to one string, and nothing says which request it came fromRegenerate to One string (reset text); Two streams to One string (append)Regenerate: starts a requestRegeneratestarts a requestOne string: plus loading flagOne stringplus loading flagTwo streams: old and newTwo streamsold and newreset textappend

    How to read this: both streams append to the same string, so whichever sends a chunk last decides what the user reads.

    Options considered

    Option What it fixes What it costs Risk
    Disable Regenerate until the stream ends Only one stream at a time The user must wait or cannot restart a stuck answer Does not help after Stop or a timeout
    Message model with status and attempt Late chunks are refused; Stop, failure and retry are defined A reducer, tests, and a request that captures the attempt None beyond the work

    The decision

    Field Decision record
    Context Users restart answers, and old streams can still deliver chunks.
    Decision Messages with id, status and attempt; one pure reducer; chunks carry id and attempt; Stop and failure keep the partial text.
    Consequences, good Mixed answers become impossible by construction, and the rules are unit tested.
    Consequences, bad More code than one string.
    Revisit when Messages need parts (tool calls, sources) or branching history.

    Rollout and verification

    1. Write the reducer tests first, including a stop followed by a late chunk and a regenerate followed by a stale chunk.
    2. Ship the store behind the old screen, logging each refused action by outcome.
    3. Switch the screen and watch the counts of ignored-stale-attempt: a non-zero count shows the guard is doing real work.

    The 2 a.m. failure

    Support reports answers that start with one sentence and end with another (illustrative). A user pressed Stop on a slow answer, then Regenerate within a second. The old connection had not closed, and a chunk from it appended to the new answer. First three checks: (1) is there a request id or attempt on each chunk; (2) does the reducer apply a chunk to a message that is no longer on that attempt; (3) did the first request really get aborted. Mitigation: refuse chunks whose attempt does not match. Follow-up: add the stop then regenerate test, and count refused chunks in monitoring.

    Architect's notes

    • Give every message a status before writing any component. The rows follow from it.
    • Refuse in the reducer, not only in the button. A disabled button is not a guarantee.
    • Capture the attempt when the request starts, not when a chunk arrives.
    • Convert to the provider format in one tested function, because the screen's list and the wire list differ.
    • Mark partial text. A stopped or failed answer must not look finished.

    Common mistakes

    • One string and a boolean for the whole assistant reply.
    • Reusing a message id without an attempt, so a straggler writes into a new answer.
    • Clearing the partial text on failure, so the screen jumps and the user cannot copy what was readable.
    • Sending the screen's list as it is, including failed and still-streaming messages.
    • Re-rendering every row per chunk because the whole list lives in one useState.

    Key takeaways

    • A chat message has an id, role, text and status, and the status decides what the row shows and what is allowed.
    • One pure reducer owns the rules; React reads it with useSyncExternalStore.
    • A message that is not streaming ignores chunks, and an attempt number separates a replaced stream from its replacement.
    • Stop and failure keep the partial text and mark it.
    • Refused actions return the same state object, so nothing redraws.
    • The list sent to a model is built from the state by rules of its own.

    Practice exercises

    Exercise 1 - Starter (45 min): Add a Retry action that works like regenerate but only for a message in error. Write the tests that show it refuses a complete message.

    Exercise 2 - Intermediate (2 hours): Give each message a parts array of text parts and make delta append to the last text part. Keep the identity rule for messages that did not change.

    Exercise 3 - Advanced (half day): Add an edit action for the last user message that discards the answer after it and starts a new stream. Decide what the attempt number means now and write the late-chunk test.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments