Engineering Practices for Mobile Streaming AI Chat Applications

    As LLM capabilities become common in business systems, mobile AI chat applications must move from "can answer" to "usable, maintainable, and observable." This article presents a general engineering design for mobile streaming AI chat apps, covering layered architecture, streaming protocol parsing, message state management, rich content rendering, mobile UX and theming, and deployment with observability. Readers will learn how to handle real streaming over HTTP, incremental rendering without flicker, cancellation and retry semantics, and performance optimization for production-grade chat experiences.

    As large language model capabilities spread across business systems, mobile AI chat applications have moved from “can answer questions” to a stage where they must be “usable, maintainable, and observable.” A mature chat page does far more than send requests and display text: it must handle streaming responses, rich text rendering, code highlighting, math formulas and charts, theme switching, session persistence, weak-network retries, and mobile-specific scrolling and keyboard adaptation. This article abstracts the technical elements of a mobile streaming AI chat application into a general, vendor-neutral engineering design and implementation approach.

    1. Goals and Key Challenges

    The core goals of a mobile AI chat app can be summarized in four points: fast first paint, smooth output, stable rendering, and extensibility. Fast first paint means splitting static assets sensibly so heavy rendering dependencies are not loaded upfront. Smooth output requires applying streaming data in incremental batches rather than refreshing character by character, which causes layout thrashing. Stable rendering means Markdown, code highlighting, math formulas, and charts must not flicker or block under incremental updates. Extensibility means the session model, message states, renderers, and theme system have clear boundaries so new capabilities can be added later.

    Common challenges in practice include: proxy layers buffering server responses so the stream is “not really streaming”; network fragmentation splitting one protocol line across multiple chunks, requiring a client-side buffer; users switching sessions or tapping stop mid-generation, requiring request cancellation with consistent state; rich text re-parsed in full on every delta causing jank; and mobile keyboard pop-ups, scroll anchoring, and safe-area adaptation directly affecting the experience. A chat page should therefore not be built as just “an input box plus a message list,” but decomposed along three dimensions: transport, state, and rendering.

    2. Layered Architecture and Selection Principles

    A recommended structure has five layers: view, state, protocol, rendering, and infrastructure. The view layer owns the message list, input area, theme, and layout. The state layer maintains sessions, messages, generation status, and errors. The protocol layer handles streaming response parsing, cancellation, retries, and heartbeats. The rendering layer handles Markdown parsing, code highlighting, formulas, and charts. The infrastructure layer provides caching, logging, monitoring, and build optimization. When selecting technologies, prefer general capability categories: a component-based frontend framework, a mobile component library, a state management library, a modern build tool, a Markdown parser, code highlighting plugins, formula rendering, and chart rendering. The guiding principles are “load capabilities on demand, keep interfaces neutral, and keep business state serializable,” avoiding tight coupling between specific renderers and request logic.

    For module structure, the codebase can be organized into chat, renderer, store, transport, theme, and shared. The transport module only cares about the streaming protocol and error semantics; store only maintains persistable message state; renderer takes plain text and outputs a safe view. This way, swapping a rendering library or changing the API protocol later does not require rewriting page components.

    3. Streaming Chat Pipeline Design

    For streaming chat, HTTP-based Server-Sent Events or chunked text responses are recommended. On the client, use fetch to obtain a ReadableStream, decode it with TextDecoder, and maintain a cross-chunk buffer. Parsing must not assume each read yields a complete event; instead, split event blocks on blank lines, then identify data: fields line by line. For cancellation, use AbortController to abort the request and set the message status to aborted. For timeouts, network drops, and server errors, distinguish “retryable” from “non-retryable,” and ensure retries are idempotent or use a new message identifier.

    A generic consumption flow looks like this:

    1. type ChatMessage = {
    2. id: string
    3. role: 'user' | 'assistant' | 'system'
    4. content: string
    5. status: 'idle' | 'streaming' | 'done' | 'error' | 'aborted'
    6. createdAt: number
    7. }
    8. async function consumeStream(url, payload, onEvent, signal) {
    9. const res = await fetch(url, {
    10. method: 'POST',
    11. headers: { 'Content-Type': 'application/json' },
    12. body: JSON.stringify(payload),
    13. signal
    14. })
    15. if (!res.ok || !res.body) throw new Error('stream unavailable')
    16. const reader = res.body.getReader()
    17. const decoder = new TextDecoder()
    18. let buffer = ''
    19. while (true) {
    20. const { done, value } = await reader.read()
    21. if (done) break
    22. buffer += decoder.decode(value, { stream: true })
    23. const blocks = buffer.split('\n\n')
    24. buffer = blocks.pop() || ''
    25. for (const block of blocks) {
    26. for (const line of block.split('\n')) {
    27. if (!line.startsWith('data:')) continue
    28. const raw = line.slice(5).trim()
    29. if (!raw) continue
    30. const event = JSON.parse(raw)
    31. onEvent(event)
    32. }
    33. }
    34. }
    35. }

    The server should define explicit event types, such as text deltas, completion, errors, and heartbeats. Proxy layers must disable response buffering and preserve text/event-stream or chunked transfer semantics; otherwise, the client will appear to “wait a long time and then show everything at once.” The client should also handle empty deltas, duplicate completion events, and malformed JSON so that one bad chunk does not break the entire session.

    4. Message Model and State Management

    The message model should include role, content, status, timestamp, error code, and optional metadata. The state machine should cover at least idle, streaming, done, error, and aborted. When the user sends a message, insert the user message first, then an assistant placeholder; streaming deltas only append to the assistant message, and the status is finalized on completion. When generation is stopped, keep the already-produced content and mark it as aborted rather than deleting it. For retries, you can either “regenerate” (which creates a new message) or “continue from the error point” (which requires server-side support for resuming context).

    For persistence in multi-session scenarios, only persist essential fields: session title, message summaries, the message list, and update time. Sensitive information should not be written to disk by default. Large message volumes can use sharded IndexedDB storage, while lightweight configuration can use localStorage. Throttle writes so that not every token triggers a storage operation. When switching sessions, locate messages by identifier to prevent asynchronous streaming callbacks from writing into the wrong session.

    5. Rich Text Rendering and Security

    AI output typically includes Markdown, code blocks, lists, links, formulas, and chart descriptions. The rendering layer should follow the order “sanitize first, render second, enhance last”: apply whitelist-based sanitization to raw HTML, forbidding dangerous attributes and scripts; add safe attributes to links after Markdown parsing; load code highlighting languages on demand instead of bundling the full language pack; render formulas and charts asynchronously with placeholders shown until rendering completes. In streaming scenarios, do not re-parse everything on every received character. Instead, merge deltas per animation frame or within a fixed time window, then trigger a single render.

    1. let pending = ''
    2. let scheduled = false
    3. function pushDelta(text) {
    4. pending += text
    5. if (scheduled) return
    6. scheduled = true
    7. requestAnimationFrame(() => {
    8. renderAssistantContent(pending)
    9. pending = ''
    10. scheduled = false
    11. })
    12. }

    For unclosed code blocks, formulas, or chart syntax, the renderer should have a fault-tolerant strategy: display unclosed constructs as plain text and enhance them once closed; fall back to source text when chart rendering fails. This ensures stability during streaming and prevents half-written syntax from blanking the page.

    6. Mobile Experience and Theme System

    Key mobile experience concerns include scroll anchoring, keyboard avoidance, safe areas, and theme switching. The message list should follow the policy “pause auto-scrolling when the user scrolls up to read, resume following when they return to the bottom.” Listen for viewport changes when the input is focused to avoid keyboard occlusion, and use safe-area variables at the bottom for full-screen devices. For theming, use CSS variables to manage background, text, borders, code blocks, and overlay colors; dark and light themes only switch variables without duplicating component styles. On desktop, use a centered layout with a fixed maximum width; on mobile, keep full width to maintain a consistent content rhythm.

    For performance, long sessions can use virtualized lists or paged loading; code highlighting and chart libraries should be loaded asynchronously on demand; images and attachments should use lazy loading; and frequently updated message areas should avoid complex selectors and shadow animations. For accessibility, the streaming region can use aria-live announcements, but the announcement frequency should be controlled to avoid constantly interrupting screen readers.

    7. Engineering, Deployment, and Observability

    At build time, apply route-level and rendering-capability-level code splitting, moving language packs, formula rendering, and chart capabilities that the first screen does not need into async chunks. Enable minification and asset fingerprinting in production builds, and distribute static assets via a CDN. When deploying streaming endpoints, pay close attention to gateway timeouts, response buffering, connection keep-alive, and CORS configuration. General-purpose infrastructure capabilities such as compute, object storage, logging, and monitoring/alerting offered by Baidu AI Cloud can be used to decouple streaming endpoints, static assets, and the observability stack, though the specific architecture should follow business scale and compliance requirements.

    Recommended observability metrics include time to first token, full response duration, stream interruption rate, rendering frame rate, error code distribution, and retry success rate. Logs should avoid recording complete sensitive conversations; record message identifiers, state transitions, and durations instead. Before launch, cover test cases such as weak networks, session switching, repeated stop taps, very long code blocks, unclosed formulas, and chart rendering failures. Only by bringing protocol parsing, state consistency, and rendering performance into the engineering system together can a mobile streaming AI chat application grow from a demo template into a maintainable, production-grade capability.