Streaming Rendering Architecture for Cross-Platform AI Chat Applications: Design and Practice
A complete cross-platform AI chat solution goes beyond displaying model output as plain text. It must stream incremental content reliably, render formulas, code blocks, tables and links, track request states, and adapt to the differences between web, mini-program, and mobile environments. This article presents a layered architecture for streaming chat UIs, covering streaming communication, message state machines, incremental rich-text rendering, content safety, scrolling behavior, and testing strategies, along with practical implementation guidance for each layer.
From UI Templates to a Complete Cross-Platform Solution
The core experience of an AI chat application is not simply displaying text returned by a model. It is about keeping users engaged with visible content while they wait, and letting them read formulas, view code, open links, and track request status.
When targeting mini-programs, mobile apps, and web pages, the real difficulty lies in differences between runtime environments: whether network requests can continuously receive chunks, which node types rich-text components support, how scroll containers respond to growing content, and whether connections survive when the app goes to the background.
Therefore, a cross-platform AI chat template should be understood as a foundational engineering system covering communication, state, parsing, rendering, and interaction—not a set of chat pages. This article presents a general architecture and key implementation points toward that goal. Module names and code in this article are illustrative and do not correspond to any product’s proprietary APIs.
Define Capability Boundaries Across the Three Platforms First
Cross-platform development does not mean every platform uses an identical implementation. A safer goal is to unify business semantics while allowing underlying capabilities to differ.
We recommend building a capability matrix before development:
| Capability | Web | Mini-program | Mobile App |
|---|---|---|---|
| Incremental text display | Implement per network capabilities | Verify chunk-receiving limits | Verify network layer and lifecycle |
| Math formulas | Page-based rendering | Controlled nodes or image-based rendering | Depends on rendering container |
| Code blocks and copy | Usually feasible | Requires clipboard and node adaptation | Requires clipboard and scrolling adaptation |
| Tables and links | Per page capabilities | Constrained by component whitelist | Constrained by rendering container |
| Image preview | Per page interactions | Per runtime environment APIs | Per app preview capabilities |
| Charts | Enhanced rendering feasible | Prepare static fallback | Depends on container capabilities |
This table describes design direction, not unverified compatibility promises. Actual implementations must be tested on target runtimes, OS versions, and real devices.
For unsupported features, prefer graceful degradation. For example, show a static image or structured text when interactive chart rendering is unavailable, and keep the raw expression when formula rendering fails—rather than displaying blank space.
Use a Layered Architecture to Isolate Platform Differences
We recommend splitting the project into six clearly-scoped layers.
1. Page and Interaction Layer
Handles the input box, message list, send button, stop generation, retry, copy, and image preview. This layer only consumes business state; it does not parse network chunks directly and does not hold server access credentials.
2. Conversation State Layer
Maintains conversation lists, message ordering, request states, and the current active task. Every message should have a unique identifier—avoid associating async responses with array positions.
3. Streaming Communication Layer
Responsible for establishing connections, receiving bytes, parsing events, and handling timeouts and cancellation. Web, mini-program, and mobile can use different adapters, but all output unified business events.
4. Content Processing Layer
Handles incremental text merging, rich-text structure recognition, formula processing, code block detection, and safety filtering. Parsing is decoupled from UI components so it can be tested independently.
5. Rendering Adaptation Layer
Converts unified content nodes into display structures supported by each platform. Platforms can share business definitions for text, tables, and code, but do not need to share underlying nodes.
6. Server Access Layer
Centrally handles authentication, access credentials, request limits, model invocation, and logging. Clients only access your business services and never hold long-lived keys for model services.
An illustrative directory structure:
project/pages/shared-components/conversation-state/streaming/web-adapter/miniprogram-adapter/app-adapter/content-parsing/rendering-adaptation/server-access/tests/
The value of the directory lies not in its names but in clear dependency direction: pages depend on business modules; business modules never depend back on pages.
Handle Streaming Data Correctly: Chunks Are Not Complete Messages
A streaming response consists of continuously arriving data blocks, but network chunk boundaries usually do not align with business event boundaries. One event may be split across multiple chunks, and one chunk may contain multiple events.
Therefore, never attempt to parse each chunk directly as a complete object. A reliable processing pipeline looks like this:
Receive bytes→ Incremental character decoding→ Write to buffer→ Extract complete events by protocol boundaries→ Parse business content→ Update message state→ Schedule UI rendering
Incremental character decoding is equally important. Multi-byte characters may span two chunks; decoding each chunk independently can produce garbled output or lost characters.
Here is protocol-agnostic illustrative logic:
onChunkReceived(bytes):text = decoder.incrementalDecode(bytes)buffer.append(text)while buffer contains a complete event:eventText = buffer.extractCompleteEvent()businessEvent = parseEvent(eventText)dispatch(businessEvent)onConnectionClosed():flushDecoderRemainder()verifyProtocolCompleteness()recordFinalState()
How to determine a “complete event” must follow the actual protocol—never assume all services use the same delimiters and field names.
Also distinguish a closed transport connection from completed business generation. If the connection drops without an explicit completion signal, mark the message as interrupted or pending confirmation, rather than declaring success.
Manage Send, Stop, and Recovery with a State Machine
Message states should cover at least:
- Pending: content not yet submitted
- Requesting: request initiated, but no body received yet
- Generating: receiving incremental content
- Completed: explicit completion signal received
- Cancelled: user actively terminated
- Failed: an error occurred in the request or processing
- Interrupted: generation incomplete; the connection or app lifecycle changed
State transitions need explicit rules. For example, even if a cancelled request later receives cached fragments, it must not continue modifying the current message.
In implementation, create an independent task ID for each generation. Upon receiving an event, first verify that the event’s task is still valid before updating state. This prevents message cross-contamination when users rapidly switch conversations or tap retry repeatedly.
Stopping generation should be split into two actions: stop the client from receiving or applying updates, and attempt to notify the server to cancel the upstream task. Hiding a loading spinner does not mean server-side computation has stopped.
For recovery, never assume lossless resumption after a disconnect. Automatic resumption is appropriate only when the server protocol explicitly supports resume positions, event sequence numbers, or an equivalent mechanism; otherwise, preserve existing content and offer a regenerate option.
Incremental Rich-Text Rendering: Balancing Stability and Responsiveness
During generation, AI answers are typically incomplete text. Code blocks may not be closed yet, tables may only have headers, and formulas may only have opening markers. Re-parsing the entire answer on every character causes structural jumps and redundant computation.
We recommend a “keep full raw text, parse in stages, throttle display” approach:
- Store all received content in a raw buffer as the trusted source for rebuilding;
- Parse structured content in already-stable text regions;
- Temporarily render unclosed structures at the tail;
- Batch UI updates within a configurable short time window;
- Run a full parse after generation completes to correct temporary structures.
Raw content and rendered output should be stored separately. This makes it easy to copy the original text and to re-render historical messages after changing parsing rules.
Throttling should only reduce UI refresh frequency—never discard incremental content. For long answers, split content into paragraph-level nodes to avoid replacing the entire message area on each update.
Implementation Strategies for Formulas, Code, Tables, and Charts
1. Math Formulas: Handle Incomplete Expressions and Caching
Distinguish inline formulas from block-level formulas. When an unclosed expression appears mid-generation, display the raw text temporarily and render it once the structure is complete.
If a target platform cannot render complex formulas directly, use a sanitized image-based approach. In that case, account for font size, theme colors, clarity, and alternative text, and generate a cache key from the expression and rendering configuration to avoid repeated processing.
If formulas are rendered on the server, strictly limit input length, execution time, and resource consumption—never concatenate expressions directly into executable commands.
2. Code Blocks: Separate Copyable Content from Visual Content
Code blocks need to handle long lines, indentation, line numbers, and copy feedback. Keep the original code text intact and treat line numbers as a display-layer concern, so copying never includes them.
Put long lines in a horizontally scrollable container to prevent breaking the message layout. A sticky code toolbar can be used when the runtime supports it, but it must be validated against nested scrolling, virtual lists, and mobile touch interactions; when it cannot be made stable, a regular toolbar fixed at the top of the code block is sufficient.
3. Tables, Links, and Images: Readability and Safety First
Wide tables work best with independent horizontal scrolling—do not blindly compress all columns on small screens. For complex tables, consider a row-by-row expanded reading mode.
Restrict link protocols to an allowlist and open links through each platform’s appropriate mechanism. Images need handling for load failures, size placeholders, source restrictions, and preview entry points, preventing layout jumps from post-load height changes.
4. Charts: Separate Enhanced Capabilities from Baseline Information
Chart rendering involves more than displaying descriptive text—it includes syntax parsing, layout computation, and node drawing. Web can serve as the enhanced rendering platform; other platforms provide static images or textual structures based on their capabilities.
Chart descriptions are untrusted input too. Limit node count and complexity, disable executable content and unauthorized external resource references, and prevent oversized charts from blocking the UI.
Reasoning-Related Displays Must Follow Actual Service Capabilities
Some model services may expose displayable reasoning summaries or separate explanation fields, but you cannot infer that all models expose their full internal reasoning process.
UI design should follow only what the service actually returns and permits: when a public explanation exists, it can be shown in a section separate from the final answer; when it does not, show only generation status and the final answer—never fabricate a so-called chain of thought.
Status indicators like “generating” or “organizing the answer” must remain clearly distinct from actual model output. Handle such content carefully in logs and local storage to avoid unnecessarily expanding the retention of sensitive information.
Scrolling, Performance, and Lifecycle Are Experience-Critical
Auto-scrolling to the bottom during streaming seems reasonable, but forcing users back to the bottom after they scroll up to read history severely hurts the experience.
Decide whether to follow new content based on the user’s distance from the bottom:
- When the user is near the bottom, keep auto-following;
- Once the user scrolls up, pause following;
- Show a “new content available” indicator;
- Resume following after the user taps the indicator or returns to the bottom.
Long conversations can use on-demand loading and list windowing, but note that rich-text message heights change as formulas, images, and streaming content load. Use stable message identifiers and height-update mechanisms to preserve reading anchors.
When the app goes to the background, record task state and decide whether to maintain the connection based on runtime capabilities. After returning to the foreground, verify whether the task actually finished—do not keep showing a loading state based on a stale UI.
Close the Loop with Security, Storage, and Testing
Model output must never be treated as inherently trusted content. Rich-text processing should enforce allowlists for nodes, attributes, and link protocols, filtering scripts, event handlers, and dangerous resource references. When the server downloads images or other resources, also protect against access to internal network addresses.
Access credentials must stay on the server. Business services should provide authentication, request rate limiting, input length controls, and concurrency protection, while avoiding logging full sensitive conversations. Retention periods, deletion mechanisms, and user isolation policies for conversation history must be explicitly defined.
Testing should cover abnormal scenarios beyond the happy path:
- Characters and events split across chunks; multiple events arriving merged;
- Network loss, timeouts, cancellation, duplicate submissions, and rapid conversation switching;
- Unclosed code blocks, complex formulas, ultra-wide tables, and failed images;
- Malicious links, dangerous nodes, and oversized chart inputs;
- Long messages, long conversations, frequent incremental updates, and background recovery.
For performance evaluation, track time to first content, UI update latency, memory usage in long conversations, and scrolling stability. Measure metrics under clearly defined devices, networks, data volumes, and test conditions—avoid making performance promises divorced from context.
Evolvable Engineering Capability Over Feature Piling
A cross-platform AI chat template ready for real projects must first guarantee reliable communication, clear message states, safe content processing, and predictable degradation across platforms. Formula, code, chart, and conversation-history capabilities can then be extended incrementally.
The recommended implementation order is: first get plain-text streaming chat working end to end, then refine cancellation and error handling, then add rich-text parsing and per-platform adaptation, and finally complete storage, security, and performance testing.
The value of a cross-platform solution lies not in claiming feature parity everywhere, but in delivering a stable, understandable, and continuously iterable AI chat experience across devices through a unified business model, clear module boundaries, and validated adaptation strategies.
