Frontend Implementation and Engineering Practices for Mobile Streaming AI Chat

    Large language model (LLM) chat applications require streaming output to provide a real-time user experience, which is particularly challenging on mobile devices with constrained resources and unstable networks. This article explores frontend implementation strategies for mobile streaming AI chat interfaces, covering SSE data parsing, optimized per-character rendering, handling incomplete Markdown syntax, theming, mobile adaptation, and state management. It outlines a layered architecture approach to ensure maintainable and performant AI conversational applications.

    1. Background and Objectives

    AI chat capabilities have become a standard feature in many products. Unlike traditional request-response models, large language models (LLMs) typically generate and return content simultaneously. If users have to wait for the entire response to complete before seeing the result, the experience degrades significantly. Therefore, the frontend must handle “streaming output,” updating the interface in real-time as data chunks arrive.

    Implementing this on mobile devices introduces additional constraints: narrow screens, unstable networks, limited memory and compute power. Meanwhile, users expect the interface to switch between dark and light themes seamlessly and to display code, mathematical formulas, and charts correctly. This article uses a typical mobile AI chat template as a backdrop to outline the design considerations for each component.

    The goal of this article is to answer three questions:

    1. How streaming data is transmitted from the server to the page and parsed correctly.
    2. How to ensure that Markdown, code blocks, formulas, and charts render correctly without lagging during per-character output.
    3. How to organize the engineering structure so that theming, layout, caching, and error handling remain maintainable.

    2. Overall Architecture Design

    2.1 Technology Selection Principles

    Technology selection should revolve around business requirements rather than chasing the latest or trendiest components. For this type of application, consider the following dimensions:

    • Build speed and developer experience: Fast dev server startup and stable hot module replacement (HMR).
    • Responsive state management: Message lists, streaming status, themes, and other data need to automatically drive UI updates.
    • Mobile component library: Provides mature components like buttons, modals, input fields, and dropdowns, with support for theme variable customization.
    • State persistence: Chat history should persist across page refreshes.

    A common approach is to combine a modern frontend build tool, a component-based reactive framework, a mobile UI component library, a lightweight state management library, and a local storage plugin.

    2.2 Layered Structure

    It is recommended to divide the codebase into four layers:

    1. API Layer: Encapsulates the request logic for communicating with the LLM service, including streaming requests, request cancellation, and error mapping.
    2. Data Layer: Manages sessions, messages, streaming status, and persistence.
    3. Rendering Layer: Handles Markdown parsing, code highlighting, formula rendering, and chart rendering.
    4. View Layer: Includes message bubbles, input areas, sidebars, theme switchers, and layout containers.

    The benefit of layering is that each layer focuses solely on its responsibilities. For example, replacing the model service only requires changes in the API layer, while switching themes only requires adjusting style variables in the View layer.

    2.3 Security Boundaries for API Keys

    Frontend code is downloaded and visible to users, so server-side API keys must never be hardcoded into the page. The correct approach is to use your own backend as a proxy: the frontend requests your own API, the backend attaches the key and forwards the request to the model service, and then returns the streaming response as-is or filtered. This protects the key and facilitates unified rate limiting, authentication, and auditing.

    3. Streaming Communication with Model Services

    3.1 Streaming Protocol

    Currently, most model services use the Server-Sent Events (SSE) format to output streaming data. Each data chunk starts with data:, contains a JSON payload, and the stream terminates with a [DONE] marker. The incremental text carried in each chunk is typically found in the choices[0].delta.content field.

    Note that field names may vary across different services. Implementation should refer to the official API documentation and include fallback handling for missing fields.

    3.2 Parsing SSE Data Streams

    Using the fetch API to read the ReadableStream of the response body allows you to access raw bytes. Since network packets can split a single line of data, parsing requires maintaining a buffer to process only complete lines. Example code:

    1. async function streamChat(messages: ChatMessage[], onToken: (t: string) => void, signal: AbortSignal) {
    2. const res = await fetch('/api/chat/stream', {
    3. method: 'POST',
    4. headers: { 'Content-Type': 'application/json' },
    5. body: JSON.stringify({ messages, stream: true }),
    6. signal,
    7. })
    8. if (!res.ok || !res.body) throw new Error(`Request failed: ${res.status}`)
    9. const reader = res.body.getReader()
    10. const decoder = new TextDecoder()
    11. let buffer = ''
    12. while (true) {
    13. const { done, value } = await reader.read()
    14. if (done) break
    15. buffer += decoder.decode(value, { stream: true })
    16. const lines = buffer.split('\n')
    17. buffer = lines.pop() ?? '' // The last segment might be incomplete, keep it for the next iteration
    18. for (const line of lines) {
    19. if (!line.startsWith('data:')) continue
    20. const payload = line.slice(5).trim()
    21. if (payload === '[DONE]') return
    22. const json = JSON.parse(payload)
    23. const token = json.choices?.[0]?.delta?.content ?? ''
    24. if (token) onToken(token)
    25. }
    26. }
    27. }

    Three key points in this code:

    • decode uses { stream: true } to prevent multi-byte characters (like Chinese) from being split and causing garbled text.
    • The buffer only consumes complete lines ending with a newline; unfinished tails are preserved for the next read.
    • The signal is used to cancel the request; calling abort() when the user clicks “Stop generating” interrupts the reading process.

    3.3 Error and Interruption Handling

    Streaming request failures can occur in three phases: before establishing a connection, during transmission, and during parsing. It is recommended to handle them separately:

    • Connection failure: Prompt network anomaly and provide a retry button.
    • Transmission interruption: Retain the partial content already received and mark the end of the message with “Response incomplete.”
    • Parsing failure: Log the raw data fragment for debugging while preventing the entire session from crashing.

    When a user actively stops the generation, the already generated text should be preserved rather than cleared.

    4. Rendering Strategy for Per-Character Output

    4.1 Avoiding Per-Character Reflows

    Updating the interface for every single character received causes massive reflows and repaints, which is especially noticeable on mobile devices. A common practice is to buffer tokens first, then flush them in batches at a fixed rhythm, such as every 30 milliseconds or once per animation frame.

    1. let pending = ''
    2. let scheduled = false
    3. function enqueue(token: string, flush: (text: string) => void) {
    4. pending += token
    5. if (scheduled) return
    6. scheduled = true
    7. requestAnimationFrame(() => {
    8. flush(pending)
    9. pending = ''
    10. scheduled = false
    11. })
    12. }

    This ensures that even if the server returns dozens of small chunks per second, the UI only updates at the frame rate, resulting in smoother animations.

    4.2 Handling Unclosed Markdown Syntax

    During streaming output, text frequently stops in the middle of a syntax block. For example, if a code block only outputs the opening three backticks, rendering it directly will treat all subsequent content as code. The solution is to perform a temporary completion each time the text refreshes. For instance, check if the number of code block fences is odd; if so, append a closing marker to the rendering copy. The original text remains unchanged, and the completion only affects the rendered output until the next data chunk arrives for recalculation.

    4.3 Cursor and Status Indicators

    During generation, a blinking cursor can be displayed at the end, and the input area can switch to a “Stop generating” button. Once generation finishes, remove the cursor and restore the send button. These states should be managed centrally by the Data layer (e.g., using a streaming boolean or a status enum) to prevent different parts of the UI from making independent judgments and causing inconsistent states.

    5. Markdown Rendering and Security

    5.1 Parsing and Sanitization

    Model outputs may contain HTML tags, scripts, or malicious links. Security processing is mandatory before rendering:

    1. Disable raw HTML parsing by default, or only allow whitelisted tags.
    2. Validate link protocols, permitting only http, https, and in-site relative paths.
    3. Add attributes like rel="noopener noreferrer" to external links, and prompt users if necessary when navigating away from the current page.

    Writing model outputs directly to innerHTML can trigger cross-site scripting (XSS) attacks. This is a critical consideration on mobile as well.

    5.2 Tables, Lists, and Line Breaks

    On narrow mobile screens, tables can easily break the layout. Wrap tables in horizontally scrollable containers and set maximum widths. Lists and paragraphs should maintain reasonable line heights and spacing for comfortable reading.

    6. Code Highlighting and Copy

    Code blocks are the most common content in technical conversations. A good code display should include:

    • Language label: Display the language name in the top right corner of the code block for easy identification.
    • Syntax highlighting: Color the code based on the language. Highlighting should execute after the code block is closed to avoid repeated calculations during streaming.
    • One-click copy: Prefer navigator.clipboard.writeText, falling back to a temporary textarea and selection method in unsupported environments.
    1. async function copyCode(text: string) {
    2. try {
    3. await navigator.clipboard.writeText(text)
    4. } catch {
    5. const ta = document.createElement('textarea')
    6. ta.value = text
    7. document.body.appendChild(ta)
    8. ta.select()
    9. document.execCommand('copy')
    10. document.body.removeChild(ta)
    11. }
    12. }

    Code blocks should also support horizontal scrolling rather than automatic line wrapping, which destroys indentation and readability.

    7. Mathematical Formulas and Chart Rendering

    7.1 LaTeX-Style Formulas

    Inline and block formulas are common in technical Q&A. Two points to note during rendering:

    • Inline formulas share a line with regular text; control the font size to avoid expanding line height.
    • Block formulas can be very wide and should allow horizontal scrolling.

    Formula rendering libraries are large in size and should be loaded on demand. Only load the corresponding module when formula delimiters are detected in a message.

    7.2 Flowcharts and Sequence Diagrams

    Some models output text-described chart syntax to represent flows or sequence relationships. Three recommendations for rendering these charts:

    1. Lazy loading: Chart rendering modules are large; defer loading if not needed on the first screen.
    2. Error fallback: If the syntax is invalid, display the raw text with a prompt instead of leaving a blank area.
    3. Wait for completion: Chart syntax usually requires complete content to parse; attempt rendering only after the code block is closed.

    8. Theme System Design

    8.1 Using CSS Variables

    The simplest way to implement dark and light theme switching is to define a set of semantic CSS variables (e.g., background color, text color, bubble color, border color) and switch the entire set of values via a root element attribute.

    1. :root[data-theme='light'] {
    2. --bg-page: #f5f6f8;
    3. --bubble-ai: #ffffff;
    4. --text-main: #1f2328;
    5. }
    6. :root[data-theme='dark'] {
    7. --bg-page: #111418;
    8. --bubble-ai: #1d2127;
    9. --text-main: #e6e8eb;
    10. }

    Components should only reference variable names, not hardcode color values, so adding a new theme requires no changes to component code.

    8.2 System Preference and Persistence

    Theme settings should offer three options: Light, Dark, and System. In System mode, read the system preference and listen for changes. User choices need to be saved locally and restored directly on the next visit.

    8.3 Code Highlighting and Theme Synchronization

    The color scheme for code highlighting should also switch with the theme. A common practice is to prepare two sets of highlight styles for light and dark modes, controlled by the same attribute selector.

    9. Mobile Adaptation and Desktop Layout

    Mobile pages should use the viewport meta tag to set width and scaling. The font size of input fields should not be smaller than 16 pixels; otherwise, some mobile browsers will automatically zoom the page on focus. The bottom input area should account for safe areas to avoid being obscured by system gesture bars.

    In desktop browsers, displaying chat content full-screen results in overly long text lines, making reading difficult. A practical solution is to constrain the main container to a fixed maximum width (e.g., 750 pixels), center it horizontally, and fill the outer area with a background color. This allows mobile and desktop to share the same codebase, presenting as a centered narrow column on wide screens.

    1. .app-container {
    2. max-width: 750px;
    3. margin: 0 auto;
    4. height: 100dvh;
    5. display: flex;
    6. flex-direction: column;
    7. }

    Using 100dvh better adapts to height changes caused by mobile browser address bar expansion and contraction.

    10. State Management and Local Caching

    10.1 Data Structure

    Session data can be structured as follows:

    1. interface Session {
    2. id: string
    3. title: string
    4. createdAt: number
    5. messages: { role: 'user' | 'assistant'; content: string }[]
    6. }

    The session list and the current session ID are placed in the global state, and message contents are stored grouped by session ID. This way, switching sessions only requires updating the current ID, and the UI refreshes automatically.

    10.2 Persistence Strategy

    Local persistence can be achieved using a storage plugin to sync critical state to the browser’s local storage. Considerations include:

    • Storage space is limited. Common browsers typically cap local storage at around 5MB. Long conversations will quickly fill this; limit the number of saved sessions and truncate or shard excessively long content.
    • Sensitive information like API keys and user credentials should not be saved.
    • Write operations should include exception handling. Prompt the user when storage is full instead of failing silently.

    11. Performance and Engineering Recommendations

    1. List Virtualization: When there are many messages, render only the messages within the viewport to reduce memory usage.
    2. Auto-scrolling: During streaming output, auto-scroll only if the user is near the bottom. If the user has scrolled up, do not force jump back to the bottom.
    3. Debouncing and Throttling: High-frequency operations like search and save should be merged for execution.
    4. Code Splitting: Place large dependencies like formulas, charts, and highlighting into separate chunks to reduce first-screen load time.
    5. Type Constraints: Define types for messages, sessions, and streaming events to facilitate maintenance in large projects.
    6. Test Coverage: Focus tests on SSE parsing packet splitting scenarios, unclosed syntax completion logic, and state recovery after interruptions.

    12. Conclusion

    The core of mobile streaming AI chat lies in three things: correctly parsing chunked streaming data, controlling the refresh rhythm of per-character rendering, and ensuring the correct display of Markdown, code, formulas, and charts during unstable output. On this foundation, the theme system, mobile adaptation, and local caching determine the product’s usability.

    Following the layered approach in this article, developers can first build the API and Data layers to verify the streaming pipeline, then gradually add rendering capabilities and UI details. Maintaining clear boundaries at each stage ensures that future changes—whether replacing the model service, extending features, or adjusting visual styles—remain within a predictable scope.