Rebuilding an Open-Source AI Chat App in Vue 3: An Architecture Guide to Less Code

    This article presents a Vue 3 case study on rebuilding the core capabilities of a production AI chat application with less code. It explains a three-layer architecture that decouples the UI from the wire protocol, details four frequently underestimated implementation challenges—message branching trees, streaming chunk reassembly and recovery, citation provenance, and attachment retry with versioned archives—and shows how a register-validate-orchestrate pattern enables new capabilities without inflating component logic. It also outlines four structural levers for reducing code size, a four-phase evolution plan, and the quality checks that keep complexity under control.

    1. Background: Why Rebuilding Tests Architecture More Than Building From Scratch

    In AI chat web applications, the hard part is rarely drawing a chat interface. It is getting a full set of implicit protocols, a message state machine, a streaming render pipeline, and an attachment workflow to run reliably. Many teams move fast during prototyping, then discover once engineering work begins that message branches, citation tracing, history archiving, and failure retries push code volume up quickly.

    Rebuilding the core capabilities of an already-shipped product is essentially reverse architecture analysis: you infer the internal data model and state transition rules from observable interaction behavior, then reimplement them more concisely. That demands far more architectural discipline than implementing from a requirements document.

    This article uses a Vue 3 rebuild of an AI chat application as a case study and addresses three questions: how to cut code volume without cutting features, how to extend new capabilities while staying protocol-compatible, and how to avoid runaway complexity across multiple architecture iterations.

    2. Overall Design: Fully Decoupling the UI From the Protocol

    The most common mistake in rebuild projects is letting UI components depend directly on API details. Once a protocol field changes, the edit spreads across dozens of components. A safer approach introduces three layers:

    • Protocol adapter layer: handles message encoding and decoding, streaming chunk reassembly, version compatibility, and archive format conversion, exposing only a stable domain model.
    • Domain state layer: maintains core entities such as sessions, the message tree, attachments, and citations, and describes states like sending, streaming, completed, interrupted, and failed-pending-retry with a unified state machine.
    • Presentation layer: consumes only the domain model, never cares where fields came from, and reuses interaction logic through slots and composables.

    The layering constraint can be expressed schematically like this:

    1. // The presentation layer may depend only on the domain model, never on raw protocol fields
    2. function useMessageNode(nodeId) {
    3. const node = computed(() => domainState.messageTree.get(nodeId))
    4. return { node, status: computed(() => node.value?.status) }
    5. }

    The direct payoff is that protocol compatibility issues stay contained in a single directory, and new capabilities such as tool calling or instruction management do not intrude on rendering logic.

    3. Rebuilding Core Capabilities: Four Frequently Underestimated Details

    3.1 A Message Branch Tree, Not a Linear Array

    Once a chat app supports regeneration and branch editing, the message structure must be upgraded from an array to a tree. Each node needs a stable identifier, a parent pointer, sibling ordering, and status markers. The practical recommendation is to design immutable update paths for nodes so references do not get scrambled during streaming renders.

    3.2 Streaming Chunk Reassembly and Interrupted Recovery

    Streaming complexity concentrates on three anomalies: out-of-order chunks, duplicates, and timeout interruptions. A workable approach assigns a session-level cursor to each generation, writes idempotently by sequence number, and resumes from the cursor after a dropped connection instead of resending everything.

    3.3 Search Citations and Source Provenance

    Store citation data separately from message content and link them by identifier, merging them at render time. This keeps citations from polluting the body text during export, archiving, and copying, and makes source credibility labeling easier.

    3.4 Attachment Retry and Bidirectional History Archive Interchange

    Attachment handling should distinguish three states: uploaded successfully, pending retry, and expired, and should support resumable transfer on weak networks. For history archives, a versioned compressed package structure works well, with an internal manifest describing the protocol version and entity mapping, enabling bidirectional import and export across different implementation versions.

    4. Growing More Capabilities With Less Code

    After the rebuild, two categories of capability can be added in secondary UI areas without breaking the existing structure:

    • External tool connection and invocation: declare each tool’s name, input schema, and return structure in a capability registry; let the domain state layer orchestrate invocation timing and error fallbacks; the presentation layer only displays invocation status.
    • Instruction and skill management: support bulk import from local text files and directories, plus pulling instruction sets from remote code hosting repositories. Imported content is parsed, validated, and deduplicated before being written to the instruction library, and can be enabled or disabled per scenario.

    The key is the three-stage register-validate-orchestrate pattern: every new capability is first registered as a describable, verifiable entry, then scheduled by a unified orchestrator, avoiding piles of conditional branches inside components. This is the core reason code volume stays under control.

    5. Four Levers for Code Reduction

    With unified formatting and consistent measurement criteria, drops in code size typically come from structural optimization rather than compressed naming or deleted logic:

    1. Eliminate duplicate render branches: collapse differences between message types into a configuration-driven render mapping table.
    2. Reuse composables: extract scroll anchoring, auto-sizing input height, and retry logic into independent composable units.
    3. Centralize protocol field mapping: define mappings once instead of scattering fallback value lookups everywhere.
    4. Replace hand-written branches with declarative validation: describe inputs and configuration with schemas, then auto-generate validation and error messages.

    One caveat: the measurement criteria must stay consistent (whether type declarations, styles, tests, and scripts are included), otherwise conclusions like “how many lines were saved” are not comparable. A reasonable expectation in practice is a double-digit percentage reduction in production source size while features hold steady or grow, with local styles and edge-case details still likely to differ.

    6. Evolution Cadence and Quality Assurance

    A four-round sequence is recommended: get the protocol working, converge state, extend capabilities, then polish performance and accessibility, keeping a rollback-capable archive version after each round. Quality assurance should focus on streaming interruption recovery cases, branch tree consistency checks, cross-version archive interchange regression, and rendering performance under weak networks and very long sessions. If cloud inference is involved, a unified model service access layer can decouple it, making migration between general capabilities across cloud platforms (container platforms, object storage, logging services, monitoring and alerting) possible without touching upper-layer domain logic.

    7. Conclusion

    The value of a rebuild is not looking identical, but carrying equal or greater capability behind clearer boundaries. Decoupling the protocol, state, and presentation layers, replacing conditional stacking with registration and orchestration, and measuring gains with consistent criteria allows sustained evolution within a controlled code size—which is more meaningful engineering than chasing line-count reduction alone.