Building a Mobile H5 AI Chat Assistant: A Practical Engineering Guide
This guide walks through building a mobile H5 AI chat assistant, covering a four-layer architecture, a streaming state machine for handling incremental deltas, incremental Markdown rendering with sanitization, theme and accessibility details, state persistence, responsive desktop display, security and cost control, and a testing checklist. It focuses on solving state consistency, rendering performance, and mobile UX challenges so the result is a maintainable, cross-platform baseline.
1. Why Choose H5 for AI Chat Capabilities
As generative AI capabilities become more widely available, conversational interaction is becoming the most natural information entry point on mobile. Compared with native apps, the H5 form factor has three structural advantages. First, distribution cost is low: a link is the entry point, with no app store review required. Second, iteration is fast: front-end assets can be updated instantly, making it easy to validate prompts and interaction strategies quickly. Third, cross-platform consistency is strong: the same codebase can be reused in mobile browsers, embedded containers, and desktop narrow views.
However, delivering streaming chat in H5 also introduces new engineering challenges: network jitter can cause incremental chunks to arrive out of order, long-text rendering can block the main thread, rendering code blocks and math formulas is expensive, and switching between dark and light themes must happen without flicker. This article addresses these real pain points with a clearly layered implementation approach.
2. Overall Architecture and Technology Selection Logic
It is recommended to divide the system into four layers that communicate through explicit contracts, avoiding coupling between business logic and rendering.
- Interaction layer: handles the input box, message list, quick prompts, and scroll anchoring.
- Session state layer: maintains the message array, session metadata, and generation state machine.
- Capability integration layer: encapsulates communication with the large model server endpoint, and uniformly handles authentication, timeouts, retries, and stream parsing.
- Rendering layer: converts text increments into rich text, and handles code highlighting, formulas, charts, and copy/download.
For technology selection, focus on cold start and incremental compilation speed for the build tool, on responsiveness precision and ecosystem maturity for the view framework, on touch experience and on-demand loading for the mobile component library, on modularity and persistence for state management, and on plugin support and security for rich text rendering. Each of these categories has multiple industry-standard options, so selection should be based on team familiarity and bundle size budget rather than blindly chasing the newest.
An illustrative dependency organization (expressing layering intent only, not specific products):
{"dependencies": {"framework": "vue^3.5.x","router": "^5.x","store": "^3.x","ui-mobile": "^4.x"},"devDependencies": {"bundler": "^8.x","md-renderer": "^14.x","highlight": "^11.x","math-render": "^0.25.x"}}
3. The Core of Streaming Chat: Incremental Parsing and the State Machine
The essence of streaming output is splitting a complete answer into a large number of incremental chunks. Engineering practice must model state explicitly to avoid the race conditions caused by a binary “loading/done” judgment.
A recommended state machine includes: idle, connecting, streaming, finalizing, error, and aborted. Every state transition must be idempotent, and the user must be able to interrupt at any time.
// Pseudocode: stream consumption and state transitionsasync function streamChat(messages, { onDelta, onDone, onError, signal }) {setState('connecting');try {const resp = await fetch(endpoint, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ messages, stream: true }),signal});setState('streaming');const reader = resp.body.getReader();const decoder = new TextDecoder();let buffer = '';while (true) {const { value, done } = await reader.read();if (done) break;buffer += decoder.decode(value, { stream: true });const frames = buffer.split('\n\n');buffer = frames.pop(); // keep the incomplete framefor (const f of frames) {const delta = parseFrame(f);if (delta) onDelta(delta);}}setState('finalizing');onDone();setState('idle');} catch (e) {if (e.name === 'AbortError') setState('aborted');else { setState('error'); onError(e); }}}
There are four key practices. First, frame boundaries cannot be assumed to match network packet boundaries; you must buffer and split them yourself. Second, incremental updates should be throttled; merging multiple deltas within a window of about 16 milliseconds is recommended to reduce re-renders. Third, interruption must actually release the underlying connection to avoid continued background billing and bandwidth usage. Fourth, on failure, preserve the already-generated content and give the user a clear “retry/continue” exit.
4. Rich Text Rendering: Balancing Performance and Security
Chat content often contains code, tables, quotes, and math formulas. Parsing the entire text at once causes noticeable jank. A strategy of “incremental concatenation + deferred tail rendering” can be used: fully parse and cache the results of stable historical messages, apply only lightweight text updates to the message being generated, and perform unified rich rendering after generation completes.
// Only re-parse stable messages; the generating message takes the lightweight pathconst stableHtml = computed(() => renderMarkdown(msg.content));const streamingText = computed(() => msg.pending ? msg.content : '');
For security, always sanitize the rendered output, filtering out scripts and dangerous attributes; route external links through a relay or add noopener; escape code blocks by default, and provide the original text only when the user actively copies.
For experience, code blocks provide one-click copy and download as a file; formulas use a mature math typesetting approach, handling inline and block-level cases separately; flowchart-type content is rendered with chart syntax, with a loading placeholder reserved to avoid layout shift.
5. Theme, Accessibility, and Mobile Details
The dark and light themes should be determined before the first screen to avoid a white flash. It is recommended to drive design tokens with a root element attribute or class name, with tokens covering color, border radius, shadow, and spacing; also listen for system theme changes, allow the user to manually override, and persist the choice.
Mobile also requires attention to: safe area adaptation and viewport changes when the keyboard pops up; virtual scrolling or paginated loading for long lists; scroll anchoring that pauses auto-follow when the user scrolls up and resumes when back at the bottom; touch targets no smaller than about 44 pixels; contrast that meets readability requirements; and semantic labels added to icons.
6. State Management and Persistence Design
Session state is recommended to be split into modules: session metadata, message map, generation queue, and user preferences. Persistence should store only necessary fields; long text can be compressed before writing to local storage, with capacity limits and an eviction policy. In multi-session scenarios, partition by session identifier, and cancel unfinished requests when switching to prevent cross-talk.
// Pseudocode: persistence boundary for preferences and sessionsconst persistable = {theme: 'dark',fontSize: 'md',sessions: [{ id, title, updatedAt }]};
7. Desktop Display and Responsive Strategy
When the page is opened in a desktop browser, a centered container with a maximum width constraint can present the mobile layout, preserving the mobile-first interaction while avoiding stretched content. For breakpoints, base them on content width rather than device models; on wide screens, moderately increase padding and information density, and on narrow screens, compress non-critical elements.
8. Security, Compliance, and Cost Control
Keys must never be delivered to the front end; all calls must go through your own backend proxy for authentication and rate limiting; filter sensitive information and keep audit logs for input and output; set rate limits by session and user dimensions to prevent abuse. On the cost side, consumption can be reduced through prompt streamlining, context window trimming, history summary compression, and result caching. If you need to extend capabilities, you can use object storage for attachments, a message queue for peak shaving, and logging services with monitoring and alerting for observability, with a container platform hosting the elastic backend; these are all general cloud capability categories.
9. Testing and Acceptance Checklist
- Stream parsing: whether chunks that span frames, half frames, empty frames, and abnormal frames are all handled correctly.
- Interruption and retry: no residual requests after interruption, and retries do not produce duplicate messages.
- Rendering: whether very long code, nested lists, block-level formulas, and chart loading placeholders work properly.
- Theme: no white flash on the first screen, and no leftover styles after switching.
- Compatibility: viewport, scrolling, and keyboard behavior in mainstream mobile browsers and embedded containers.
- Performance: time to interactive on the first screen, frame drop rate during generation, and memory growth curve.
10. Conclusion
The difficulty of an H5 AI chat assistant lies not in “being able to chat,” but in state consistency under streaming increments, the performance and security of rich text rendering, and the detail experience on mobile. Making architecture layering, the state machine, throttled rendering, and the security proxy solid yields an engineering baseline that can evolve long-term and be reused across platforms, leaving room for integrating more modalities and business capabilities later.
