Frontend Refactoring and Simplification for AI Chat Web Applications
This article examines the core engineering challenges of building AI chat web applications, including streaming responses, reasoning display, web search, file uploads, voice interaction, conversation branching, archive migration, and tool integration. It presents a layered architecture, practical implementation patterns, and strategies for keeping the codebase maintainable as functionality grows.
1. Background and Problem Definition
Large language model chat capabilities are moving from demos into everyday products. A usable chat web application needs more than an input box and a message list. It must also handle streaming output, reasoning display, web search, file uploads, voice interaction, conversation history, and other capabilities. These features are closely coupled, and a design mistake in one module can increase maintenance costs across the application.
Several open-source web examples already call model APIs directly from the browser. They often provide broad functionality, but their codebases can become relatively large. This article does not evaluate any specific product. Instead, it breaks this type of application down into general engineering problems and discusses how modern frontend practices can implement the required features while keeping the codebase manageable.
The article is intended for developers with some frontend experience. After reading it, you should be able to design a conversation state model, implement streaming parsers, manage branches and data migrations, and preserve code readability during ongoing iteration.
2. Feature Breakdown and Technical Considerations
2.1 Streaming Conversations
Models typically return generated content incrementally. A browser can read the response body as a stream, decode each chunk, and parse the resulting events.
The frontend needs to handle three common problems:
- A chunk boundary may split a data line.
- The network connection may close unexpectedly.
- The user may cancel the request while generation is in progress.
The parser should cache incomplete lines and perform consistent cleanup when it receives a completion signal or an error.
2.2 Reasoning and Web Search
Some models expose reasoning content. Reasoning and the final answer should be stored separately. By default, the interface should collapse the reasoning section while allowing users to expand it when needed. This preserves transparency without interrupting the reading experience.
Web search results often appear in the response as numbered references. Before rendering, the frontend should parse these markers, replace them with clickable citation badges, and list the sources at the bottom of the message. Displaying the raw markers would expose strings that are difficult for users to understand.
2.3 Reading Web Pages
Directly fetching arbitrary web pages from a browser is restricted by the same-origin policy. As a result, page retrieval is usually handled by a server or intermediary proxy.
The frontend only needs to display the retrieval state:
- Pending
- Successful
- Failed
When a request fails, the interface should provide an actionable message.
2.4 Multimodal File Uploads and Resumable Transfers
Large uploads can fail because of network instability. A better approach is to split the file into multiple chunks and record the status of each chunk. If the upload is interrupted, only failed chunks need to be sent again instead of restarting the entire upload.
The frontend can perform preliminary checks for file type and size, but final validation must still be handled by the server.
2.5 Voice Input and Streaming Playback
The voice input flow consists of recording audio, transcribing it, and writing the result into the input field. Transcription should support intermediate updates so that users can see text appear in real time.
The main goal of streaming text-to-speech playback is to reduce perceived latency. Text can be split by sentence, synthesized separately, and added to a playback queue. The first sentence can begin playing while later content is still being generated.
Sentence segmentation should account for both English and Chinese punctuation and avoid splitting inside numbers or abbreviations.
2.6 Message Branch Trees
A conversation is not always a linear array. Editing an earlier message or requesting a new answer creates a new branch. A linear array cannot represent these relationships effectively.
Instead, messages should be stored as nodes in a tree. The currently displayed conversation is determined by an active path through that tree.
2.7 Importing and Exporting Conversation Archives
Conversation archives are often stored as compressed packages containing a manifest file and one or more conversation data files. The manifest should include a format version.
During import, the application should validate the version first and then perform any required field migrations. During export, node IDs should remain stable. This allows repeated imports to identify existing data and avoid creating duplicate conversations.
2.8 Tool Connections and Skill Management
Tool connections allow an application to discover external tools through a standardized protocol, read parameter definitions, make calls, and return results. The frontend should provide configuration controls and authorization prompts, while the actual call logic should be centralized in a shared invocation layer rather than scattered across individual components.
Skills are reusable prompt templates. They may come from a single Markdown file, a folder, or a remote code repository. The parser reads metadata from the file header for the name and description, while the body becomes the instruction content. Although the sources differ, all imported skills should be converted into the same internal data structure.
3. Architecture
A three-layer architecture is recommended:
- Protocol adapter layer: Encapsulates requests, authentication, and stream parsing, and exposes a consistent event format.
- Domain state layer: Manages conversations, message trees, attachments, and user settings.
- View layer: Handles rendering and interaction. It reads application state but does not process protocol-specific details directly.
A unified event type helps isolate changes in upstream protocols:
type ChatEvent =| { type: "reasoning"; delta: string }| { type: "content"; delta: string }| { type: "search"; results: { title: string; url: string }[] }| { type: "done" }| { type: "error"; message: string };
When a protocol changes, only the mapping logic in the adapter layer needs to be updated. The state and view layers can remain unchanged. This is one of the main ways to control maintenance costs.
4. Key Implementation Details
4.1 Streaming Parsing
The following example demonstrates the basic approach: read the response in chunks, cache incomplete lines, and emit data lines.
async function* readLines(response) {const reader = response.body.getReader();const decoder = new TextDecoder();let buffer = "";while (true) {const { done, value } = await reader.read();if (done) break;buffer += decoder.decode(value, { stream: true });const lines = buffer.split("\n");buffer = lines.pop() ?? "";for (const line of lines) {if (line.startsWith("data: ")) yield line.slice(6);}}if (buffer.startsWith("data: ")) yield buffer.slice(6);}
The stream option passed to decoder.decode prevents corrupted characters when a multibyte character spans two chunks. The remaining final line must also be processed; otherwise, the last piece of content may be lost.
4.2 Message Trees and Active Paths
Each message stores its parent node ID, a list of child nodes, and the currently selected child:
const nodes = {"m1": {id: "m1",parentId: null,role: "user",content: "...",childIds: ["m2", "m3"],activeChildId: "m3"},"m2": {id: "m2",parentId: "m1",role: "assistant",content: "...",childIds: [],activeChildId: null},"m3": {id: "m3",parentId: "m1",role: "assistant",content: "...",childIds: [],activeChildId: null}};function getActivePath(nodes, leafId) {const path = [];let cursor = leafId;while (cursor !== null) {path.unshift(nodes[cursor]);cursor = nodes[cursor].parentId;}return path;}
Switching branches only requires changing the parent node’s activeChildId. The displayed path then updates automatically. The cost of switching branches is proportional to the tree depth rather than the total conversation length.
4.3 Deduplication and Migration During Archive Import
The import process can be divided into four steps:
- Read the manifest.
- Validate the format version.
- Merge nodes by node ID.
- Write the result to local storage.
Nodes with the same ID are treated as the same message. The version with the newer modification time takes precedence.
When the archive version is older than the current version, migration functions should be executed one version at a time. Typical migrations may add missing fields or rename legacy fields. Migration functions should be implemented as pure functions so they can be tested independently.
5. Ways to Control Codebase Growth
Codebases usually grow because of duplicated logic and branches that are never removed. The following practices are effective in real-world development.
- Extract shared capabilities. Images, documents, and audio files can use the same chunked upload function, with differences limited to validation rules.
- Use data instead of conditional branches. Store the relationship between message types and rendering components in a mapping table. Adding a new type then requires only one additional configuration entry.
- Normalize state. Store each piece of data in one place. For example, message content should exist only in the message node, while the view derives display data through selectors.
- Load modules on demand. The voice and archive modules can be loaded only when the user first uses them.
- Standardize formatting and validation rules. When measuring code size, use the same formatting rules and measurement criteria. Otherwise, figures from different versions cannot be compared directly.
All of these practices reduce duplicated decisions. When a given task has one consistent implementation, the codebase becomes smaller and easier to read.
