跪拜 Guibai
← Back to the summary

Vue 3 Rebuild of DeepSeek's Chat Demo Cuts Source by 27% and Adds MCP and Skills

On November 13, DeepSeek released its family of application APIs and simultaneously open-sourced the official web client example chat-demo on GitHub.

Unlike the common toy demos of "an input box + a text-stream call," what DeepSeek open-sourced this time is a complete browser-direct API web application: in addition to streaming conversation, it packs deep thinking, web search, think-while-search, web-link reading, multimodal file upload, voice input, streaming voice playback, a full message branch tree, and ZIP history archive import/export all into a single frontend project.

The official original is written in React 18 + Zustand. The production source under src alone (excluding icons and static payload) amounts to 18,412 lines.

When I saw this project, as a Vue developer, the thought immediately crossed my mind: if I rebuilt this application in Vue 3, could I replicate 100% of its core features, add the MCP tools and Skill command management that developers have been calling for, and at the same time reduce the code volume?

So I got to work. With the help of OpenTiny's open-source Vue 3 AI dialogue component library and runtime suite TinyRobot , I used AI and a few hours to run through the core replication and three rounds of architectural evolution:

Here's a side-by-side UI comparison under the same data conditions:

1.png

DeepSeek official React original UI

2.png

Vue 3 + TinyRobot replica UI (bottom-left has added MCP / Skills extension entries)

This article uses the real source code and three architecture iterations (including a counterintuitive pitfall where "introducing a higher-level suite increased the code") to discuss how to efficiently build a full-featured complex AI conversation application with Vue 3 + TinyRobot.


I. The Real Replication Difficulties Are All Hidden Outside the Chat Box

Many people think writing an AI chat page is simple: v-for over a few messages, fetch an SSE text stream, and you're done. But when you actually dissect the source of DeepSeek's official chat-demo, you'll find that 90% of the complexity of a mature AI web application is hidden below the surface:

  1. It's not a plain text stream, but a rich-semantic content block protocol The official chat-demo and this replica use the Anthropic-compatible Messages/Files extended interface (model deepseek-flash). A single reply can interleave streaming thinking processes (with thinking signature passthrough), server-side web search (deepseek_web_search), web-page reading (deepseek_read_url), inline citation overlays, and a separate right-side search-source drawer. Simply swapping to a plain text-stream interface loses these structural content blocks and cannot fully restore the corresponding interactions.
  2. It's not a linear message array, but a complete "message branch tree" Editing a prior question, clicking regenerate, switching between historical answer versions, and continuing generation under certain conditions all operate on a full tree stored at the session level. The UI rendering and context assembly only project the currently selected branch path.
  3. Complex multimodal file and voice lifecycle Files support click-to-select, clipboard paste, full-window drag-and-drop upload, with concurrent upload status and failure retry. A more nuanced detail: when importing historical conversations from a ZIP archive, local images don't have a server-side file_id (or the old file_id has expired), so before sending, the app must automatically read the local original from IndexedDB, silently re-upload it, and write the new serverId back to all nodes in the session tree that reference that attachment. On the voice side, it includes up to 120 seconds of browser WAV recording (with real-time waveform drawing and ASR transcription) and streaming PCM TTS that plays as it downloads.
  4. Rich text and multi-device experience details Markdown rendering must handle Prism light/dark syntax highlighting, KaTeX math formulas, Mermaid flowcharts, and source-view toggling all at once. It also supports Chinese/English, light/dark/system theme, desktop three-column and mobile drawer adaptive layouts.
  5. Official v3 ZIP archive bidirectional interoperability Importing a ZIP archive exported from the official React version into our Vue version must restore all message branches and image originals; conversely, exporting from the Vue version and importing back into the official version must also be compatible. And if import validation or transaction fails midway, it must not corrupt existing browser history.

3.png

Dark mode and right-side search source panel

4.png

Mobile adaptive layout and rich-text formula rendering

In this replica, the underlying API protocol parsing, archive format conversion, and audio processing logic that were validated in the original retain the upstream MIT licensed implementation and attribution statements. The entire view layer, reactive state orchestration, conversation runtime, and interactive components are rebuilt from scratch on Vue 3 + TinyRobot.


II. More Than 100% Parity: Added Skills and MCP Extension Capabilities

Since we're using a component library specifically for AI scenarios, just matching the original isn't enough. We added a ✧ MCP / Skills extension panel at the bottom of the sidebar, giving this pure-frontend app two practical enhancements:

1. Skills Command Management (One-Click Import from Local or GitHub)

In daily use of large models, we often need to switch between different preset guidelines (e.g., code review rules, translation styles, SQL writing constraints). In the extension panel:

2. Browser-Direct MCP Tool Services

By integrating the official @modelcontextprotocol/sdk StreamableHTTPClientTransport, the app can directly configure and connect to CORS-enabled HTTPS (or local HTTP) MCP services in the browser:

5.png

Connect local real HTTP MCP service and complete tool discovery and invocation

Engineering boundary note: constrained by the pure-frontend browser sandbox, the web page cannot directly launch local stdio processes (if needed, a local HTTP bridge can be used); and the MCP here is designed for user-explicit selection and confirmation of calls, distinct from DeepSeek's native web search on the server side—each uses its own real protocol chain, never mocking fake tool calls.


III. Three Architecture Evolutions: Why Can Code Be Reduced by 5,044 Lines?

The most share-worthy part of the replication isn't "write it once," but the three evolutions we went through to pursue less code and clearer architecture boundaries—including a very representative pitfall.

Under exactly the same statistical conditions (all src formatted with oxfmt 0.48.0 default rules, counting TS/TSX/Vue/CSS/HTML/JSON, excluding tests, build artifacts, and icon static payload, keeping all static business data), the code volume changes across the four stages are as follows:

Version Stage Production Source Lines Source Bytes Relative to Official Lines Change
DeepSeek official original (React) 18,412 531,178 baseline
Stage 1: TinyRobot independent component composition 14,065 414,462 -23.61%
Stage 2: ChatUI interface suite only 14,396 421,592 -21.81% (increased by 331 lines!)
Stage 3: Kit + Chat Runtime refactor 13,368 395,835 -27.40% (net -5,044 lines)

Stage 1: Building Blocks with Atomic Components (18,412 → 14,065 lines)

The first version used the most intuitive approach: replacing the original hand-written chat UI parts with @opentiny/tiny-robot's TrLayout, TrSender, TrBubble, TrAttachments, TrDragOverlay and other independent components, rewriting React + Zustand to Vue 3 reactive state.

This step cut production source by 4,347 lines. But upon reviewing the source, we found that generic chat logic—session list caching, streaming request cancellation (AbortController), and auto-save debounce queues—was still hand-written in our business store.

Stage 2: Counterintuitive—Adding the ChatUI suite increased code by 331 lines?

TinyRobot actually offers a higher-level @opentiny/tiny-robot-chat conversation application suite. So we integrated <TrChatUI /> in a new directory, using its built-in sidebar, history grouping list, welcome page, auto-scrolling message flow, input box, and right-side panel to replace the previously fragmented page orchestration.

But after running the code statistics script, we saw: the code volume didn't drop; it went up from 14,065 to 14,396 lines!

After dissecting the source, the reason was clear:

  1. We only adopted the UI layer, not the runtime: The UI was rendered by TrChatUI, but the underlying session state, stream merging, and cancellation lifecycle were still maintained by the old business useChatStore, which meant an extra layer of adapter code to convert business state to ChatUIData;
  2. Old and new styles stacked: The old layout CSS wasn't cleaned up, and the suite's overlay styles piled on top.

This was a reminder: a component library rendering the UI doesn't mean the state and lifecycle are also handed over to the framework.

Stage 3: Making Kit + Chat Runtime the True Runtime Backbone (Down to 13,368 lines)

After finding the root cause, we did a thorough "slimming refactor" in the third stage: completely handing the generic chat runtime to @opentiny/tiny-robot-kit and @opentiny/tiny-robot-chat.

The post-refactor responsibility division became very clean:

User input / attachments / voice
   |
   ▼
Chat Runtime Actions (useChatRuntimeFromConversation)
   |
   ▼
Kit session and message engine (useConversation + per-session useMessage Engine)
   ├──► DeepSeek ResponseProvider (focuses only on server search/thinking signatures/file re-upload protocol)
   ├──► IndexedDB storage adapter ◄──► DeepSeek v3 ZIP atomic archive interoperability
   └──► Current branch read-only projection ──► useChatRuntimeAdapter ──► TrChatUI built-in UI

This round of refactoring netted a reduction of 1,028 lines from the previous stage:

Keep in mind that of the remaining 13,368 lines, static extensions, locale data, and multi-language files account for 1,825 lines (of which uploadExts.ts alone, a static extension array, is 986 lines), and v3 ZIP archive compatibility accounts for 1,753 lines. While retaining all static business data and adding MCP/Skill features, we wrote 27.40% less source than the official version. That's the direct benefit of framework layering and reuse.


IV. Source Code Dissection: Why TinyRobot Saves Code Yet Doesn't Limit Deep Customization?

Frontend developers who have worked on complex AI applications often encounter a dilemma: with a highly encapsulated Chat component library, you can't modify the underlying protocol; doing it all by hand means re-creating thousands of lines of bubbles, input boxes, and scroll controls.

During this replication of deepseek-chat-demo-vue, TinyRobot's three-layer progressive architecture resolved the contradiction well:

Below are two real code snippets from the project (details omitted; full implementation is in the public source branch at the end of this article) to show how it works.

1. Using useConversation + Custom ResponseProvider to Carry Complex Protocols Losslessly

In src/services/chat/store.ts, we don't need to flatten DeepSeek's complex message branch tree into plain strings. Instead, we use the Kit message object's extension fields to carry the full deepseek domain message, and when initiating a conversation, we mount a custom createDeepSeekProvider onto the session's engine:

// src/services/chat/store.ts (core structure excerpt)
import { useConversation, type ChatMessage } from '@opentiny/tiny-robot-kit'
import { useChatRuntimeFromConversation } from '@opentiny/tiny-robot-chat'
import { createDeepSeekProvider } from './provider.js'

const wrap = (message: Message): ChatMessage => ({
  id: message.id,
  role: message.role,
  content: '',
  deepseek: message, // preserve thinking process, signatures, search citations, and branch parent-child pointers
  historyEpoch,
})

export const conversation = useConversation({
  autoSaveMessages: true,
  autoSaveThrottle: 250,
  storage: {
    loadConversations: loadList,
    loadMessages: async (id) => { /* load from IndexedDB and wrap as ChatMessage[] */ },
    saveConversation: async (item) => db.renameSession(item.id, item.title || ''),
    saveMessages: async (id, messages) => { /* serialize per session */ },
    deleteConversation: async (id) => db.deleteSession(id),
  },
  useMessageOptions: {
    responseProvider: async () => { throw new Error('No DeepSeek request prepared') },
    onCompletionChunk({ currentMessage, choice }) {
      const message = choice.delta?.deepseek as AssistantMessage
      Object.assign(currentMessage, wrap(message))
    },
  },
})

// On send, inject a DeepSeek-specific ResponseProvider into the session engine; Kit handles streaming consumption and cancellation
function run(id: string, initial: AssistantMessage, request: Request) {
  const engine = engines.get(id)!
  engine.responseProvider.value = createDeepSeekProvider({ /* domain callbacks */ })(id, initial, request)
  void engine.send()
}

export const kitRuntime = useChatRuntimeFromConversation({
  conversation,
  send: ({ conversationId }) => sendMessage(conversationId),
})

In provider.ts, we only need to focus on DeepSeek-specific business logic (e.g., expired attachment re-upload, composing enabled skillContext(), parsing search and thinking SSE events). The cancellation signal signal and engine state transitions are all managed by Kit.

2. useChatRuntimeAdapter + TrChatUI: Preserving Controlled Input Flexibility

Why didn't we use the out-of-the-box default integration component <TrChat /> in App.vue, but instead the suite's public useChatRuntimeAdapter + TrChatUI combination?

Because DeepSeek's original has a very delicate product experience: each session retains its own unsent draft, and voice transcription results, uploaded attachments, and MCP tool return values must all be written into the current draft. The current default <TrChat /> clears the built-in input draft when switching sessions.

By using useChatRuntimeAdapter + TrChatUI with semantic slots, we reuse the entire layout, history list, auto-scroll, and right-side drawer while precisely preserving controlled input and custom message renderers:

<!-- src/App.vue (core structure excerpt) -->
<TrChatUI
  class="deepseek-chat-suite"
  :data="adapter.data.value"
  :ui="ui"
  :is-empty="!chat.activeId"
  v-model:input-value="text"
  :right-aside-open="!!sourcePanel"
  active-right-aside-panel-id="sources"
  @create-conversation="open(null)"
  @switch-conversation="({ conversationId }) => open(conversationId)"
  @rename-conversation="({ conversationId, title }) => renameSession(conversationId, title)"
  @submit="submit"
  @cancel="stop"
>
  <!-- Bottom of left sidebar: inject MCP / Skills and settings entries -->
  <template #layout-left-aside-footer>
    <div class="suite-sidebar-footer">
      <button class="extensions-entry" @click="extensionsOpen = true">✧ MCP / Skills</button>
      <button class="settings-entry" @click="openSettings()">设置</button>
    </div>
  </template>

  <!-- Right sidebar: directly mount the search sources panel -->
  <template #layout-right-aside>
    <Sources v-if="sourcePanel" />
  </template>

  <!-- Input box header and footer slots: mount pending attachments, deep thinking, and smart search toggles -->
  <template v-if="attachments.length" #sender-header>
    <DraftAttachments :items="attachments" />
  </template>
  <template #sender-footer>
    <div class="composer-actions">
      <button :class="['toggle', { selected: settings.thinking }]" @click="setThinking(!settings.thinking)">
        深度思考
      </button>
      <button :class="['toggle', { selected: settings.search }]" @click="setSearch(!settings.search)">
        智能搜索
      </button>
    </div>
  </template>
</TrChatUI>

No need to hack the component library source, nor to stuff the entire page into a giant slot to "pretend" to use the suite. General capabilities leverage the framework's benefits; special interactions stay in a thin adapter layer—this is the most comfortable way to use an enterprise-grade AI component library.


V. More Than "It Runs": Deep-Water Concurrency Races and Layered Validation

Many replication projects just test "send hi, receive reply" and declare success. But in real usage, switching sessions, disconnecting, and importing archives often happen simultaneously. We introduced independent fault-injection reviews and Playwright automated regression, fixing several easily overlooked deep-water issues:

The project passed clear layered validation:


VI. One-Minute Start: Experience TinyRobot in Your Vue Project

If you want to try this replicated app, or you're developing an AI assistant, Copilot sidebar, intelligent customer service, or Agent workbench in Vue 3, you can start right now.

Online Demo of the DeepSeek Vue Replica

Install TinyRobot in Your Own Vue 3 Project

If you only need lightweight components (like TrSender input or TrBubble message bubble), a few lines will get a chat UI running. If you want to build a full multi-session app in one go, install the Chat suite and base component package directly:

pnpm add @opentiny/tiny-robot-chat @opentiny/tiny-robot

If you're integrating a standard OpenAI-compatible interface, you can set up a complete chat page with history management, streaming generation, and cancellation control in under 25 lines using useChatRuntime + TrChat:

<script setup lang="ts">
import { TrChat, useChatRuntime, type ChatProviderConfig } from '@opentiny/tiny-robot-chat'
import '@opentiny/tiny-robot/dist/style.css'
import '@opentiny/tiny-robot-chat/dist/style.css'

const modelProviders: ChatProviderConfig[] = [
  {
    type: 'openai',
    apiUrl: 'https://your-service.example.com/v1/chat/completions', // replace with actual service or backend proxy
    models: [{ id: 'your-model-id', label: 'Your Model Name' }],
  },
]

const runtime = useChatRuntime({ modelProviders })
</script>

<template>
  <TrChat :runtime="runtime" />
</template>

Related Open Source Repos and Docs

From the original 18,000+ lines of full details, to reducing code by nearly 30% with TinyRobot's components, Kit engine, and Chat suite, while easily extending MCP and Skills—good AI frontend infrastructure may not decide your business protocol for you, but it can silently handle the tedious streaming state machine, scroll-to-bottom, attachment drag-and-drop, multi-device layout, and tool forms, letting you focus on valuable AI business innovation.

If you're building an AI app with Vue, feel free to explore the TinyRobot repository and submit an Issue with any ideas or needs!

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

勇宝趣学前端 1 likes

Like