Refactoring a Streaming AI Chat App with Vue 3: A Cost-Reduction Practice

    This article walks through refactoring a browser-only streaming AI chat application with Vue 3 while keeping the external protocol and data formats unchanged. It covers the engineering gaps between a demo and a usable chat app, a three-layer constraint checklist, a three-round architecture evolution, key implementation details for message branch trees, citations, multimodal attachments, voice streaming, and history archives, and why the production source dropped from about 18,000 to 13,000 lines. It closes with acceptance testing and deployment recommendations.

    1. Background: Why “It Chats” Is Far From “It Works”

    A sample with just an input box that calls a text streaming endpoint usually only proves the pipeline is connected. A conversational web app meant for daily use has to solve four classes of engineering problems: rendering and interruption recovery for streaming output; organizing multi-turn context and message branches; asynchronous orchestration for external information sources (retrieval, files, voice); and migration and archiving of historical data. These four problems are coupled, and any careless design in one of them gets amplified into an experience defect in real use.

    An open-source community recently released an official web sample that brings deep thinking, web retrieval, search-while-thinking, link reading, multimodal file upload, voice input, streaming text-to-speech, a full message branch tree, and import/export of history archives as a compressed package into a single front-end project that connects directly to the API from the browser. The original was written with a mainstream front-end framework and state management library, and the production source alone was close to 18,000 lines. The general technical question this article discusses is: without changing the external protocol or data formats, can an equivalent implementation be completed with another mainstream progressive framework while also reducing code size and improving maintainability?

    2. Capability Inventory and Constraints Before Refactoring

    The first step of refactoring is not writing code but listing the “non-negotiables.” It helps to split the constraints into three layers:

    • Protocol layer: request body fields, streaming chunk semantics, end markers, error codes, and retry semantics must stay consistent; otherwise historical data and cross-client interoperability break.
    • Data layer: the persistence structures for sessions, messages, branches, attachments, and citations must remain compatible, especially the directory layout and version number of the archive package.
    • Interaction layer: shortcuts, scroll anchoring, stop generation, regenerate, branch switching, and similar details determine whether it “feels the same.”

    Once the three layers of constraints are written into an acceptance checklist, evaluate the room for component reuse. The chat interface is highly patterned structurally and can be abstracted into five component types: message list, message item, input area, attachment preview, and citation panel. On the state side, it can be abstracted into three main lines: session state, generation state, and external resource state.

    3. Three Rounds of Architecture Evolution

    The first round was “equivalent migration.” A single session store was built with the Composition API, a reactive object carried the message tree, and each arriving stream chunk was appended to the buffer of the last message, with frame-by-frame merging to avoid high-frequency rendering. The goal of this stage was to get the protocol and branches working.

    The second round was “separation of concerns.” The network and protocol were wrapped into an independent adapter layer, and retrieval, file parsing, speech synthesis, and recognition were split into replaceable capability interfaces, with the UI consuming only unified events. Sample code:

    1. // Protocol adapter: the UI is unaware of the specific API details
    2. export function createChatTransport(fetchImpl) {
    3. return async function* send(payload, signal) {
    4. const resp = await fetchImpl('/api/chat', {
    5. method: 'POST',
    6. body: JSON.stringify(payload),
    7. signal,
    8. });
    9. const reader = resp.body.getReader();
    10. const decoder = new TextDecoder();
    11. while (true) {
    12. const { value, done } = await reader.read();
    13. if (done) return;
    14. for (const line of decoder.decode(value).split('\n')) {
    15. if (line.startsWith('data:')) yield JSON.parse(line.slice(5));
    16. }
    17. }
    18. };
    19. }

    The third round was “built-in extensibility.” Tool connection and instruction management were added to the sidebar: on the tool side, a unified description format declares the name, input schema, and invocation entry, and a scheduler triggers them at the right moment during generation and writes the results back as citable snippets; on the instruction side, support was added for bulk import from local text files or directories, or pulling from a hosted repository and caching locally, with size and format validation on import to keep abnormal content out of the context.

    4. Key Implementation Points

    Message branch tree. Do not model it as a linear array; it should be a “node + child index” structure where each node records a parent pointer, generation parameters, and attachment references. Switching branches only changes the current leaf pointer, and regenerating creates a sibling node, so history and comparison come naturally.

    Citations and provenance. Retrieval results first land in a numbered snippet pool, and the generation stage injects only the numbers and summaries into the context. During content rendering, the numbers are mapped to clickable sources, avoiding stuffing long text repeatedly into the message body and bloating its size.

    Multimodal attachments. Upload follows a three-step flow: local validation first, then chunked or direct upload to object storage, and finally submitting the reference identifier. Parse failures must degrade to a placeholder card so the conversation is not blocked.

    Voice pipeline. Both recognition and synthesis are streaming, so a unified playback queue and interruption strategy are needed: new segments enqueue on arrival, and pressing again clears the queue and releases resources to prevent echo and memory buildup.

    History archive. Import and export must strictly align with the directory structure and version fields so they are bidirectionally usable with the other implementation. On import, perform structure validation and field migration first, then write atomically to local storage.

    5. Why the Code Size Dropped

    The reduction did not come from “writing fewer features” but from eliminating duplication and clarifying boundaries: state was consolidated into a few stores to avoid mirrored copies; protocol details were centralized in one layer so the UI no longer scatters conditional branches; and common capabilities (validation, formatting, queues) were pushed down into utility functions. Under unified formatting and counting rules, the production source dropped from about 18,000 lines to about 13,000 lines, a net reduction of more than 5,000 lines, or about 27%, with the new capabilities still included. This shows that size metrics only make sense with consistent rules; before comparing, fix the formatting rules and exclude static assets and generated code.

    6. Acceptance and Rollout Recommendations

    Acceptance should cover four categories of cases: protocol consistency (chunks, interruption, error recovery), data compatibility (bidirectional archive import/export), interaction completeness (branches, stop, regenerate), and robustness under exceptions (oversized attachments, timeouts, concurrent requests). On performance, watch time to first token, rendering frame rate, and memory curves for long sessions. If you need to support multiple users and audit requirements, you can then add common cloud capabilities such as containerized services, object storage, logging services, and monitoring and alerting, keeping keys and quotas on the server side while the browser retains only the experience layer.