Engineering Streaming AI Chat on Mobile: A Practical Guide

    This article explains how to build a streaming AI chat experience on mobile, covering the four-layer architecture of transport, state, rendering, and views. It walks through the streaming data pipeline, incremental rendering and scroll behavior, safe rendering of Markdown, formulas, and charts, theming and persistence, mobile viewport adaptation, and robustness, observability, and compliance. Readers will find implementation details and engineering practices for a maintainable, model-agnostic mobile AI chat foundation.

    1. Why Mobile AI Chat Needs a Streaming Architecture

    The traditional one-shot request-response model delivers a poor experience in conversational scenarios: after submitting a question, the user waits for a long time while the interface stays blank, with no way to tell whether the system is thinking, queued, or has already failed. Streaming output splits a complete answer into incremental fragments and presents them as they are generated, so the user gets clear progress feedback as soon as the first token arrives, significantly reducing perceived wait time.

    From an engineering perspective, streaming is more than a “typewriter effect.” It requires three foundational capabilities on the frontend:

    1. A long-lived data pipeline that can be consumed continuously;
    2. Incremental concatenation and re-rendering of incomplete text;
    3. Consistent interface state even after interruption at any point.

    These three requirements mean the overall architecture cannot use a simple “request-then-assign” approach.

    2. A Vendor-Neutral Note on Technology Choices

    The original practice used a specific build tool, a specific progressive framework, a specific mobile component library, and a specific large model service. To avoid binding to particular products, this article describes them by generic technical categories:

    • Build layer: a modern frontend build tool that supports native ESM, fast cold starts, and on-demand compilation;
    • View layer: a progressive frontend framework with a compositional API, plus declarative routing and centralized state management;
    • UI layer: a general-purpose mobile component library covering common interactions such as dialogs, action sheets, and pull-to-refresh;
    • Model layer: incremental responses obtained through a model service compatible with a common chat interface specification, with an interface shape consistent with the mainstream “message array + streaming flag” pattern;
    • Rendering layer: a Markdown parser + syntax highlighter + math formula plugin + chart rendering plugin;
    • Persistence: a state management plugin combined with local storage to retain sessions and preferences locally.

    This way of describing the stack does not affect implementation details, but makes the solution portable to any service that meets the same capability boundaries.

    3. Overall Architecture and Directory Organization

    A recommended approach is to decouple into four layers: transport, state, rendering, and view.

    1. src/
    2. api/ # streaming request wrapper, protocol parsing
    3. stores/ # sessions, messages, topics, settings
    4. composables/ # useStreamChat / useAutoScroll
    5. components/ # message bubbles, input area, code blocks, chart containers
    6. utils/ # markdown rendering, incremental concatenation, throttling
    7. views/ # chat page, settings page

    The value of decoupling: when replacing the model service, only the api layer changes; when adjusting the visuals, only components change; when adding analytics or monitoring, only composables change, without touching business views.

    4. Key Implementation Points of the Streaming Data Pipeline

    The core is “readable stream + incremental decoding + event dispatch.” Example code:

    1. export async function streamChat({ messages, onDelta, signal }) {
    2. const res = await fetch('/api/chat', {
    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('stream unavailable')
    9. const reader = res.body.getReader()
    10. const decoder = new TextDecoder('utf-8')
    11. let buffer = ''
    12. while (true) {
    13. const { value, done } = await reader.read()
    14. if (done) break
    15. buffer += decoder.decode(value, { stream: true })
    16. const chunks = buffer.split('\n\n')
    17. buffer = chunks.pop() ?? ''
    18. for (const chunk of chunks) {
    19. const data = chunk.replace(/^data:\s*/, '')
    20. if (data === '[DONE]') return
    21. try { onDelta(JSON.parse(data)) } catch { /* ignore heartbeat and comment lines */ }
    22. }
    23. }
    24. }

    Engineering details: multi-byte characters must be handled with incremental decoding using stream: true, otherwise Chinese characters and emoji will appear garbled; the residual buffer must be preserved to avoid parsing half a JSON object prematurely; AbortController cancellation must be supported so the connection is released immediately when the user switches sessions or taps stop.

    5. Incremental Rendering and Scrolling Experience

    Message state should distinguish status: pending | streaming | done | error, with the content field holding the concatenated text. On each delta arrival, append to the string and trigger rendering instead of replacing the entire array, which reduces unnecessary component re-creation.

    Auto-scroll needs a “stick-to-bottom” check: follow the scroll only when the user is currently at the bottom of the list. Once the user scrolls up to read history, stop auto-following and show a “back to bottom” entry at the bottom. The logic can be expressed as:

    1. const atBottom = () => el.scrollHeight - el.scrollTop - el.clientHeight < 40

    Under high-frequency deltas, rendering should also be throttled, for example by merging multiple deltas within a window of about 60ms, balancing smoothness and CPU usage.

    6. Safe Rendering of Markdown, Formulas, and Charts

    Chat content is untrusted input, so the rendering pipeline must follow “sanitize first, then parse, then highlight”:

    1. Use a mature HTML sanitization strategy to filter scripts and dangerous attributes;
    2. Enable code block and table support when parsing Markdown, and route all links through safe navigation;
    3. Run syntax highlighting only after a fragment is closed, to avoid repeated highlighting mid-stream that causes flicker;
    4. Use deferred rendering for math formulas and charts: render only when the corresponding code block marker is closed and the element enters the viewport;
    5. Provide folding and one-click copy for long code blocks, with copied content stripped of line numbers and extra whitespace.

    7. Theming, Persistence, and Mobile Adaptation

    Themes are switched via CSS variables on the root node, combined with a system preference media query for first-screen prediction to avoid a white flash. Sessions and user preferences are persisted with local storage, with three things to note: persist only necessary fields to control capacity; impose a count or size limit on very long sessions; use a version number field for compatibility migration when the structure is upgraded.

    Mobile adaptation points include: using safe area variables to handle notches and bottom gesture bars; adjusting the layout based on the visual viewport height when the input is focused to prevent the keyboard from covering it; presenting centered with a fixed maximum width on desktop while keeping a mobile-first visual proportion; keeping touch targets no smaller than the usual clickable size, and supporting selection and copy for long text.

    8. Robustness, Observability, and Compliance

    Exception handling should cover network interruption, authentication failure, rate limiting, content moderation blocks, and model-side errors, with recoverable user messages and a “retry” action for each error type; retry should support continuing from the last complete message rather than starting the whole thing over.

    For observability, it is recommended to record metrics such as time to first token, overall completion time, number of deltas, and error code distribution, and aggregate and analyze them through general logging and monitoring/alerting capabilities. However, outputting the full conversation text or keys in client logs is strictly prohibited. Keys must be held by a server-side proxy, and the frontend only accesses its own backend interfaces; this is both a security requirement and a prerequisite for cost control.

    9. Conclusion

    The technical difficulty of a streaming chat template lies not in the “typing effect,” but in the robustness of the data pipeline, the performance boundaries of incremental rendering, the rendering security of untrusted content, and experience consistency under complex mobile viewports. By decoupling the four layers of transport, state, rendering, and view, and completing cancellation, retry, throttling, and safe sanitization, you get a high-quality mobile AI chat foundation that can evolve over the long term and freely swap model services.