Refactoring an AI Chat Application with Vue 3: Architecture Evolution and Code Reduction Practices
This article covers the refactoring of a complex AI chat application from React to Vue 3. It explains the core challenges of AI chat frontends—rich-semantic SSE stream parsing, message branch management, and multimodal resource handling—walks through three rounds of architectural evolution, interprets a 27% source code reduction, and presents a plugin-based design for tool and skill management, API security boundaries, and a pre-launch checklist.
The Bottom Line First
The difficulty of a complex AI chat application lies not in calling APIs, but in stream protocol parsing, message state organization, and multimodal resource management. The original project was built with React and a state management library, with roughly 18,000 lines of production source code. After the refactoring, production source code was reduced by about 27%, while tool calling and skill management features were added. This result comes from one specific project; the original article did not disclose the counting tool details, so the numbers only describe this project’s overall change and should not be applied directly to other projects.
1. Core Challenges of a Complex AI Chat Application
1.1 Parsing Rich-Semantic Streaming Protocols
Streaming responses in modern AI chat are typically delivered via SSE (Server-Sent Events), but the content goes far beyond plain text. A backend may return different types of data chunks in a single stream—reasoning traces, web search status, tool call arguments, and more. The frontend must first split the byte stream into complete events, then dispatch each event by type to the corresponding UI component.
The most error-prone part of event splitting is network fragmentation. One event may be split across two reads, and a single read may contain multiple events. The following code uses a buffer to handle both cases:
async function readSSE(response: Response,onData: (payload: string) => void,signal: AbortSignal,) {const reader = response.body!.getReader();const decoder = new TextDecoder();let buffer = '';const onAbort = () => reader.cancel();signal.addEventListener('abort', onAbort, { once: true });try {while (true) {const { done, value } = await reader.read();if (done) break;buffer += decoder.decode(value, { stream: true });const events = buffer.split('\n\n');buffer = events.pop() ?? '';for (const event of events) {const data = event.split('\n').filter((line) => line.startsWith('data:')).map((line) => line.slice(5).trimStart()).join('\n');if (data && data !== '[DONE]') onData(data);}}} finally {signal.removeEventListener('abort', onAbort);}}
The parsed data is still a string. The caller should wrap JSON.parse in a try/catch, because proxies or the server occasionally return incomplete JSON fragments. When parsing fails, log it and skip that fragment rather than letting the entire session break.
1.2 Managing Message Branch Structures
Users edit historical messages and regenerate replies, and each of these operations creates a new branch. The original article calls this structure a directed acyclic graph (DAG). In practice, it is closer to a tree: each message has exactly one parent, a parent can have multiple children, and each child represents a sibling branch. A DAG is only necessary when two nodes need to share the same child (for example, merging branches).
Under a tree structure, each node needs at least the following fields:
id: unique node identifier.parentId: parent identifier; null for the root node.childIds: list of child nodes.activeChildIndex: the currently active child branch index.
When switching branches, the program starts from the root and walks down along each level’s activeChildIndex to a leaf, producing the currently displayed message path. This path can be generated automatically with a computed property, with no manual synchronization needed.
Edge cases require separate handling:
- When deleting a message that has children, decide whether to cascade the deletion or promote the children to the parent node.
- When importing a ZIP archive, node IDs may conflict with existing data and need to be remapped.
- If an archive contains orphan nodes (missing parents), place them in a dedicated recovery area instead of discarding them.
1.3 Multimodal and Voice Pipelines
File uploads, voice input, and text-to-speech all depend on low-level browser capabilities and fail more often than ordinary API calls. Key points to watch:
- Resumable uploads: record uploaded offsets per chunk so that after a network recovery, uploading resumes from that position instead of restarting the whole file.
- Memory release: preview URLs created with
URL.createObjectURLmust be released withURL.revokeObjectURLwhen the component is destroyed or the file is removed. - Audio context: an
AudioContextusually can only start after a user gesture (such as a click); callresume()on the first click. - Media stream release: after recording ends, call
stop()on every track of theMediaStream, or the microphone indicator stays on and resources are never reclaimed. - Permission degradation: when the user denies microphone permission, the UI should hide the voice button or suggest switching to text input, rather than throwing an unhandled exception.
2. Three Rounds of Evolution in the Vue 3 Refactoring
| Phase | Approach | Gains | Problems |
|---|---|---|---|
| Round 1: Logic porting | Mapped the React component tree to Vue templates and extracted lifecycle logic into composables | Basic streaming chat worked | Still relied on a global store; heavy component coupling; no significant code reduction |
| Round 2: Reactivity optimization | Managed the message tree directly with reactive and ref; tracked the active path with computed |
Eliminated large amounts of manual synchronization code | The boundary between state and view was still unclear |
| Round 3: Adopting a runtime kit | Integrated an AI chat runtime kit from the Vue 3 ecosystem | Gained standardized message and streaming lifecycles | The kit’s standard flow conflicted with the project’s custom protocol parsing; glue code grew and total size increased instead |
Round 3’s problem is the most instructive. The project’s protocol structure was custom, and the kit assumed a different default data format. The initial approach was to write conversion code at every mapping point, which made the intermediate layer thicker and thicker.
The solution was to switch to the kit’s middleware mechanism: write a streaming data interceptor that performs protocol parsing inside the kit, converting rich-semantic chunks directly into message fragments the kit understands. After that, business components no longer cared about the underlying protocol, the glue code essentially disappeared, and the parsing logic lived in exactly one place.
Note that the original article did not disclose the name or version of the kit, and the project name was anonymized. Therefore, the specific gains and problems above cannot be mapped directly to any particular library. Before migrating, verify whether the target kit’s extension points support custom protocols.
3. Interpreting the Code Reduction Numbers
The original project had 18,412 lines of production source code; after refactoring it had 13,368 lines—a reduction of 5,044 lines, or about 27.40% (5,044 divided by 18,412).
Three caveats apply:
- The counting methodology was not disclosed. The original article did not specify the counting tool, its version, or whether blank lines, comments, and generated code were included. Readers should count both versions with the same tool (for example,
cloc) before comparing. - The feature scope is not identical. The 13,368 lines include newly added tool and skill management features. So the percentage reflects the project’s overall size change, not the savings for an equivalent feature set.
- The reduction came from three sources:
- Vue single-file component templates are more compact than JSX, eliminating many closing tags and variable declarations.
- Common logic—file upload, voice recording, SSE parsing—was extracted into composables, removing duplicated implementations across components.
- Reactive objects can be mutated directly, with no need to write Actions, Mutations, or Reducers.
4. Plugin-Based Design for Tool and Skill Management
The new features let users connect external tools and import skill sets. Skills can come from local Markdown files, folders, or remote code repositories. To decouple these extensions from the chat core, define a unified tool interface:
interface ToolPlugin {name: string;description: string;inputSchema: Record<string, unknown>;invoke(args: unknown, ctx: { signal: AbortSignal }): Promise<unknown>;}
Implementation points to note:
- Permission isolation: each plugin can only access the resources it declares. Operations involving writing, deleting, or sending must require user confirmation first.
- Timeout and cancellation:
invokeshould accept anAbortSignalso it aborts promptly on timeout or when the user stops generation. - Failure handling: when a tool errors, return the error message to the model as a result instead of crashing the whole conversation.
- Rollback of partial writes: if a tool fails midway, undo completed steps or clearly inform the user of the current state.
- Treat external content as data: skill files imported from remote repositories are processed as text only; their commands must never be executed automatically, and their text must not alter system behavior.
5. Security Boundaries of Calling APIs Directly from the Frontend
The original project called the API directly from the browser. This is simple to develop but carries obvious risks. If an API key is embedded in frontend code, any user can find it in developer tools or the build output.
Safer approaches include:
- Forwarding requests through a server-side proxy, keeping the key only in server environment variables.
- Using short-lived tokens issued by the server that expire automatically.
- Rate-limiting the API and restricting which models and permission scopes each token can access.
- If users must bring their own keys, keep them in memory only—never in
localStorage—and warn about the risks in the UI.
If none of these conditions can be met, “direct API calls” should not be presented as a recommended approach in documentation.
6. Implementation Checklist
Before putting a similar architecture into production, verify each item:
- Does the stream parsing handle fragmentation, coalesced packets, JSON parse failures, and the
[DONE]marker? - When the user aborts generation, are both the network request and the reader cancelled?
- Are there clear rules for message-tree deletion, import conflicts, and orphan nodes?
- Are file preview URLs, media streams, and audio contexts released when components unmount?
- When microphone or file permissions are denied, does the UI offer a usable fallback path?
- Is the API key absent from frontend code and local storage?
- Does the code-size count record the tool, version, and counting methodology?
The key to refactoring a complex AI chat application is placing protocol parsing, state organization, and resource management each in its proper place. Vue 3’s reactivity system and Composition API reduce boilerplate, but they cannot replace careful design around protocol boundaries and edge cases.
