## 1. Architecture Design

```mermaid
flowchart TD
    subgraph Frontend
        A[React Components] --> B[React Router]
        B --> C[Zustand State]
        C --> D[UI Layer]
    end
    
    subgraph AI Agent Service Layer
        E[XiaoZhi Server]
        F[LLM API]
        G[ASR Service]
        H[TTS Service]
        I[Voice Cloning]
    end
    
    subgraph Data Layer
        J[Supabase Auth]
        K[Supabase Database]
        L[Supabase Storage]
    end
    
    Frontend --> E
    E --> F
    E --> G
    E --> H
    E --> I
    Frontend --> J
    Frontend --> K
    Frontend --> L
```

## 2. Technology Description
- **Frontend**: React@18 + TypeScript + TailwindCSS@3 + Vite
- **Initialization Tool**: vite-init (react-ts template)
- **State Management**: Zustand
- **Routing**: React Router DOM
- **Icons**: Lucide React
- **AI Agent Service**: XiaoZhi Server (WebSocket/MQTT+UDP streaming)
- **LLM Integration**: Qwen/DeepSeek/GPT (via XiaoZhi)
- **ASR**: SenseVoice/ESP-SR (via XiaoZhi)
- **TTS**: Volcengine/CosyVoice (via XiaoZhi)
- **Voice Cloning**: ElevenLabs/CosyVoice
- **Backend**: Supabase (Auth, Database, Storage)

## 3. Route Definitions
| Route | Purpose | Page Component |
|-------|---------|----------------|
| / | 首页 | HomePage |
| /memorials | 纪念馆列表页 | MemorialListPage |
| /memorials/:id | 纪念馆详情页 | MemorialDetailPage |
| /memorials/:id/chat | 数字人对话页 | ChatPage |
| /memorials/:id/training | 数字人训练页 | TrainingPage |
| /memorials/:id/training/memory | 记忆库管理页 | MemoryLibraryPage |
| /memorials/:id/training/history | 对话历史页 | ChatHistoryPage |
| /memorials/:id/training/personality | 人格调优页 | PersonalityPage |
| /memorials/:id/config | 数字人配置页 | ConfigPage |
| /create | 创建纪念馆页 | CreateMemorialPage |
| /profile | 个人中心页 | ProfilePage |

## 4. XiaoZhi Server Integration

### 4.1 Communication Protocol
- **WebSocket**: 双向流式对话，支持文本和音频数据传输
- **MQTT+UDP**: 低延迟音频传输，优先选择

### 4.2 Message Format
```json
{
  "type": "tts",
  "state": "start|streaming|end",
  "text": "你好，有什么可以帮您？",
  "audio_data": "base64_audio",
  "emotion": "happy|sad|neutral"
}
```

### 4.3 API Endpoints
| Endpoint | Method | Purpose |
|----------|--------|---------|
| /api/chat/session | POST | 创建对话会话 |
| /api/chat/message | POST | 发送消息 |
| /api/chat/audio | POST | 发送音频 |
| /api/agent/create | POST | 创建数字人智能体 |
| /api/agent/train | POST | 训练数字人 |
| /api/agent/config | PUT | 更新数字人配置 |
| /api/voice/clone | POST | 语音克隆 |

## 5. Data Model

### 5.1 ER Diagram
```mermaid
erDiagram
    users ||--o{ memorials : creates
    users ||--o{ chat_sessions : starts
    users ||--o{ chat_messages : sends
    
    memorials ||--o{ chat_sessions : has
    memorials ||--o{ chat_messages : receives
    memorials ||--o{ memory_items : contains
    memorials ||--o{ training_tasks : has
    memorials ||--o{ personality_params : has
    
    chat_sessions ||--o{ chat_messages : contains
    
    users {
        uuid id PK
        text name
        text avatar_url
        text email
        text phone
        timestamp created_at
    }
    
    memorials {
        uuid id PK
        uuid user_id FK
        text name
        text avatar_url
        text bio
        date birth_date
        date death_date
        text location
        text agent_id
        text voice_model_id
        text personality_profile
        int training_progress
        text status
        timestamp created_at
        int visit_count
    }
    
    chat_sessions {
        uuid id PK
        uuid memorial_id FK
        uuid user_id FK
        timestamp start_time
        timestamp end_time
        text status
    }
    
    chat_messages {
        uuid id PK
        uuid session_id FK
        uuid memorial_id FK
        uuid user_id FK
        text content
        text audio_url
        text emotion
        boolean is_agent
        timestamp created_at
    }
    
    memory_items {
        uuid id PK
        uuid memorial_id FK
        text type
        text content
        text file_url
        text tags
        timestamp created_at
    }
    
    training_tasks {
        uuid id PK
        uuid memorial_id FK
        text task_type
        text description
        int progress
        text status
        timestamp created_at
        timestamp completed_at
    }
    
    personality_params {
        uuid id PK
        uuid memorial_id FK
        text trait_name
        decimal value
        timestamp updated_at
    }
```

### 5.2 DDL Statements

```sql
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name TEXT NOT NULL,
    avatar_url TEXT,
    email TEXT UNIQUE,
    phone TEXT UNIQUE,
    created_at TIMESTAMP DEFAULT NOW()
);

CREATE TABLE memorials (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID REFERENCES users(id),
    name TEXT NOT NULL,
    avatar_url TEXT,
    bio TEXT,
    birth_date DATE,
    death_date DATE,
    location TEXT,
    agent_id TEXT,
    voice_model_id TEXT,
    personality_profile TEXT,
    training_progress INT DEFAULT 0,
    status TEXT DEFAULT 'draft',
    created_at TIMESTAMP DEFAULT NOW(),
    visit_count INT DEFAULT 0
);

CREATE TABLE chat_sessions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    memorial_id UUID REFERENCES memorials(id),
    user_id UUID REFERENCES users(id),
    start_time TIMESTAMP DEFAULT NOW(),
    end_time TIMESTAMP,
    status TEXT DEFAULT 'active'
);

CREATE TABLE chat_messages (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id UUID REFERENCES chat_sessions(id),
    memorial_id UUID REFERENCES memorials(id),
    user_id UUID REFERENCES users(id),
    content TEXT NOT NULL,
    audio_url TEXT,
    emotion TEXT DEFAULT 'neutral',
    is_agent BOOLEAN DEFAULT false,
    created_at TIMESTAMP DEFAULT NOW()
);

CREATE TABLE memory_items (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    memorial_id UUID REFERENCES memorials(id),
    type TEXT NOT NULL,
    content TEXT,
    file_url TEXT,
    tags TEXT[],
    created_at TIMESTAMP DEFAULT NOW()
);

CREATE TABLE training_tasks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    memorial_id UUID REFERENCES memorials(id),
    task_type TEXT NOT NULL,
    description TEXT,
    progress INT DEFAULT 0,
    status TEXT DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT NOW(),
    completed_at TIMESTAMP
);

CREATE TABLE personality_params (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    memorial_id UUID REFERENCES memorials(id),
    trait_name TEXT NOT NULL,
    value DECIMAL(5,2) NOT NULL,
    updated_at TIMESTAMP DEFAULT NOW()
);
```

## 6. Project Structure

```
src/
├── components/
│   ├── layout/
│   │   ├── Header.tsx
│   │   ├── Footer.tsx
│   │   └── Navbar.tsx
│   ├── memorial/
│   │   ├── MemorialCard.tsx
│   │   ├── DigitalHuman.tsx
│   │   ├── ChatBubble.tsx
│   │   └── TrainingPanel.tsx
│   ├── chat/
│   │   ├── ChatInterface.tsx
│   │   ├── VoiceWaveform.tsx
│   │   └── EmotionIndicator.tsx
│   ├── training/
│   │   ├── MemoryLibrary.tsx
│   │   ├── ChatHistory.tsx
│   │   ├── PersonalityTuner.tsx
│   │   └── TrainingProgress.tsx
│   ├── common/
│   │   ├── Button.tsx
│   │   ├── Card.tsx
│   │   ├── Input.tsx
│   │   └── ProgressBar.tsx
├── pages/
│   ├── HomePage.tsx
│   ├── MemorialListPage.tsx
│   ├── MemorialDetailPage.tsx
│   ├── ChatPage.tsx
│   ├── TrainingPage.tsx
│   ├── MemoryLibraryPage.tsx
│   ├── ChatHistoryPage.tsx
│   ├── PersonalityPage.tsx
│   ├── ConfigPage.tsx
│   ├── CreateMemorialPage.tsx
│   └── ProfilePage.tsx
├── stores/
│   ├── userStore.ts
│   ├── memorialStore.ts
│   ├── chatStore.ts
│   └── trainingStore.ts
├── services/
│   ├── xiaoZhiApi.ts
│   ├── supabaseClient.ts
│   └── voiceService.ts
├── utils/
│   └── helpers.ts
├── styles/
│   └── globals.css
├── App.tsx
├── main.tsx
└── index.css
```

## 7. Component Breakdown

### Layout Components
- **Header**: Logo、导航菜单、搜索框、用户入口
- **Footer**: 版权信息、联系方式、快速链接
- **Navbar**: 移动端底部导航

### Memorial Components
- **MemorialCard**: 纪念馆卡片展示、在线状态、对话入口
- **DigitalHuman**: 数字人形象组件、表情动画、语音驱动
- **ChatBubble**: 对话气泡、打字机效果
- **TrainingPanel**: 训练面板、进度展示

### Chat Components
- **ChatInterface**: 对话主界面、消息列表、输入区域
- **VoiceWaveform**: 语音波形可视化
- **EmotionIndicator**: 情感指示器

### Training Components
- **MemoryLibrary**: 记忆库管理、资料上传、分类整理
- **ChatHistory**: 对话历史、搜索筛选、标记重要
- **PersonalityTuner**: 人格参数调整、滑块控件
- **TrainingProgress**: 训练进度、任务列表

### Common Components
- **Button**: 按钮组件、渐变效果、发光边框
- **Card**: 卡片容器、玻璃拟态效果
- **Input**: 输入框组件
- **ProgressBar**: 进度条组件、动画效果

## 8. State Management

### userStore
```typescript
{
  user: User | null,
  isLoggedIn: boolean,
  login: (user: User) => void,
  logout: () => void
}
```

### memorialStore
```typescript
{
  memorials: Memorial[],
  currentMemorial: Memorial | null,
  selectedMemorialId: string | null,
  setCurrentMemorial: (memorial: Memorial) => void,
  addMemorial: (memorial: Memorial) => void,
  updateMemorial: (id: string, updates: Partial<Memorial>) => void
}
```

### chatStore
```typescript
{
  messages: ChatMessage[],
  currentSession: ChatSession | null,
  isTyping: boolean,
  isRecording: boolean,
  emotion: string,
  addMessage: (message: ChatMessage) => void,
  setTyping: (typing: boolean) => void,
  setRecording: (recording: boolean) => void,
  setEmotion: (emotion: string) => void
}
```

### trainingStore
```typescript
{
  memoryItems: MemoryItem[],
  trainingTasks: TrainingTask[],
  personalityParams: PersonalityParam[],
  progress: number,
  addMemoryItem: (item: MemoryItem) => void,
  addTrainingTask: (task: TrainingTask) => void,
  updatePersonalityParam: (trait: string, value: number) => void,
  setProgress: (progress: number) => void
}
```

## 9. XiaoZhi API Service

### WebSocket Connection
```typescript
interface XiaoZhiConfig {
  serverUrl: string;
  agentId: string;
  userId: string;
}

interface ChatMessage {
  type: 'text' | 'audio' | 'system';
  content: string;
  audioData?: string;
  emotion?: string;
  timestamp: number;
}
```

### Voice Cloning Service
```typescript
interface VoiceCloneRequest {
  audioFiles: File[];
  agentId: string;
}

interface VoiceCloneResponse {
  voiceModelId: string;
  status: string;
  progress: number;
}
```
