Rebuilding an AI Chat App with a Modern Framework: Code Reduction and Feature Expansion

    This article describes how a team rebuilt an open-source, browser-based AI chat app with a modern reactive framework and an AI chat runtime toolkit. Production code dropped from about 18,000 to about 13,000 lines, roughly 27%, while the core features stayed in place and two new capabilities were added. Readers will learn where the complexity of a chat interface sits beyond the input box, how the team ran three refactoring rounds, and which design points to check for MCP tool connections and skill instruction imports.

    Where the Complexity Sits: Beyond the Chat Box

    Many open-source AI chat examples have one input box and one text stream interface. They are simple, and that simplicity leads many developers to assume a chat page only needs to loop over messages and read a Server-Sent Events (SSE) text stream.

    The app in this project already runs directly in the browser. It supports deep thinking, web search, multimodal uploads, voice input and output, message branching, and ZIP history archives. The original version was built on a traditional component framework and a state management library, and its production source code was about 18,000 lines. We wanted to test whether we could cut code noticeably while reproducing the core features and adding new ones. We used an open-source AI chat runtime toolkit for the refactor. Production source dropped to about 13,000 lines, a reduction of about 27%.

    Reading through the source of a mature app shows that the complexity concentrates in three areas.

    1. A Rich Content Block Protocol

    A model reply is not always plain text. Some APIs compatible with the Anthropic message format split one reply into several content blocks. The block types include thinking, text, and tool_use. A single reply can show the model’s reasoning first, then trigger a web search, read web page content during the search, and finally output the answer. Thinking blocks usually carry a signature field. In multi-turn conversations, you must send that field back unchanged, or later requests may fail validation.

    For this kind of event stream, the front-end state machine needs to handle these steps:

    • On content_block_start, record the block’s type and index.
    • On content_block_delta, append text, thinking content, or tool arguments, depending on the block type.
    • On content_block_stop, finalize the block.
    • If the connection drops midway, keep the completed blocks, mark the unfinished blocks as failed, and provide a retry option.

    Not every model uses this structure. Read the documentation for the specific API before you integrate it.

    2. A Branching Message Tree and History Archives

    A conversation lets users return to an earlier node and switch to another branch. Because of this, the data structure is a tree, not a linear array. Each node needs at least id, parentId, role, content, and createdAt fields. The node also records which child node is currently selected.

    ZIP import and export require exact serialization. In practice, three points matter:

    • Exported files include a schemaVersion field, so future versions can identify the format.
    • On import, validate the manifest file and check that node references are complete. For example, confirm that the node a parentId points to exists.
    • When an id conflict occurs, the user chooses whether to overwrite the existing conversation or save the import as a new one.

    3. A Streaming Voice Pipeline

    The app supports streaming text-to-speech (TTS) and speech recognition (ASR). The front end must keep the audio stream and the text stream in sync. It also needs to limit the number of concurrent requests. After playback ends, it must release the audio tracks from AudioContext and MediaStream to avoid memory leaks in the browser.

    The voice interaction here is streaming, not full duplex. Full duplex means audio moves in both directions at the same time, and it requires echo cancellation. This implementation does not cover that.

    Three Refactoring Rounds

    Round Goal Result
    Round 1 Port the original business logic directly, converting only framework syntax Line count rose slightly
    Round 2 Hand streaming protocol handling to the runtime Redundant code in the network and protocol parsing layers dropped noticeably
    Round 3 Rewrite branch management with a reactive state tree Removed much of the code that triggered rendering manually

    Round 1: Porting Made the Code Larger

    The original state management works differently from the update mechanism of modern reactive frameworks. To bridge the two, we wrote a lot of boilerplate code, and the line count went up instead of down. Translating syntax alone does not make code smaller.

    Round 2: Letting the Runtime Handle the Protocol

    We moved the rich content block handling, SSE connection management, and signature passback into the runtime layer. The business layer now only assembles data and renders the interface. This step removed most of the network and protocol parsing code.

    Round 3: Managing Branches with a Reactive State Tree

    Computed properties and automatic dependency tracking now update the branch tree nodes. As a result, we could delete the logic that triggered rendering by hand in the original version.

    By our count, production source dropped from about 18,000 lines to about 13,000, a net reduction of about 5,000 lines. This result reflects only our own measurement. Different counting methods produce different numbers. Before you compare results, agree on the counting scope. For example, decide whether test files, auto-generated files, and dependencies are included.

    Migration Checklist

    • List every user-visible feature of the original app, and write an acceptance test for each one.
    • Confirm that each content block type has matching rendering and error handling.
    • Include a version number in serialized branch tree data, and provide migration functions for older versions.
    • Run regression tests with ZIP files exported from the old version.
    • Record the counting scope, tool versions, and the commit IDs you compared.

    Two New Extensions

    1. MCP Tool Connections

    We added an MCP entry at the bottom of the sidebar. After the user enters the address of an MCP server, the app reads the list of available tools. When the model makes a tool call, the front end forwards the request and displays the result. This turns the app from a plain chat box into a front end that can call external tools.

    The design needs attention in three areas:

    • Browsers connecting directly to an MCP service are subject to cross-origin restrictions, so the server must have suitable CORS rules.
    • For tools that perform write operations, show a confirmation dialog before the call, so the user decides whether to proceed.
    • If the connection fails, the chat can continue. Only tool calls are disabled, and the app tells the user the reason.

    2. Skill Instruction Management and Multi-Source Import

    The skill instruction module lets users write instructions in Markdown. It can also import instruction sets from a local folder or from a repository on a code hosting platform. Users can save frequently used system prompts and reuse them.

    Imported instructions are sent to the model as part of the prompt. That means a remote repository may contain malicious instructions. Before an import, show the user the full text and ask for confirmation. Only then should the instructions join the library.

    Use Cases and Limits

    A pure front-end approach suits a single user with a small data volume and no server-side authentication needs. Supporting multiple users, large file volumes, or protocol conversion that requires server-side processing calls for a back end. For example, object storage can host multimodal files. A container platform can run a protocol conversion service. Logging and monitoring services can record the latency and error rate of model calls.

    These combinations bring trade-offs in cost, latency, data compliance, and vendor lock-in. Evaluate each one before you choose. If your team already uses a modern reactive framework and is willing to maintain the protocol parsing layer, this approach is worth trying.