Skip to content

Commit 0c7a24e

Browse files
committed
Initial commit
1 parent f58482a commit 0c7a24e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

70 files changed

+10543
-670
lines changed

.dockerignore

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# Dependencies
2+
node_modules
3+
npm-debug.log*
4+
yarn-debug.log*
5+
yarn-error.log*
6+
7+
# Build outputs
8+
.next/
9+
out/
10+
11+
# Runtime data
12+
pids
13+
*.pid
14+
*.seed
15+
*.pid.lock
16+
17+
# Coverage directory used by tools like istanbul
18+
coverage/
19+
20+
# Environment variables
21+
.env*
22+
!.env.example
23+
24+
# IDE files
25+
.vscode/
26+
.idea/
27+
*.swp
28+
*.swo
29+
*~
30+
31+
# OS generated files
32+
.DS_Store
33+
.DS_Store?
34+
._*
35+
.Spotlight-V100
36+
.Trashes
37+
ehthumbs.db
38+
Thumbs.db
39+
40+
# Logs
41+
logs
42+
*.log
43+
44+
# Git
45+
.git
46+
.gitignore
47+
48+
# Docker
49+
Dockerfile
50+
.dockerignore
51+
docker-compose.yml
52+
53+
# Documentation
54+
README.md
55+
*.md
56+
doc/
57+
58+
# Claude files
59+
.claude/
60+
CLAUDE.md
61+
62+
# Temporary files
63+
.tmp/
64+
tmp/
65+
66+
# Test files
67+
__tests__/
68+
*.test.js
69+
*.test.ts
70+
*.test.tsx
71+
*.spec.js
72+
*.spec.ts
73+
*.spec.tsx
74+
75+
# Images (if not needed)
76+
setup.png
77+
img_1.png
78+
79+
# Use JavaScript config in production
80+
next.config.ts

.env.example

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
WECHAT_API_URL=http://127.0.0.1:5030
2+
BACKEND_API_URL=http://127.0.0.1:8080
3+
# OpenRouter API密钥 (获取地址:https://openrouter.ai/keys)
4+
OPENROUTER_API_KEY=

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,5 @@ yarn-error.log*
3939
# typescript
4040
*.tsbuildinfo
4141
next-env.d.ts
42+
/.claude/
43+
/.idea/

CLAUDE.md

Lines changed: 288 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,288 @@
1+
# CLAUDE.md
2+
3+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4+
5+
# 沟通规范
6+
7+
- 所有内容必须使用 **中文** 交流(包括代码注释),但是文案与错误提示要使用英文。
8+
- 遇到不清楚的内容应立即向用户提问。
9+
- 表达清晰、简洁、技术准确。
10+
- 在代码中应添加必要的注释解释关键逻辑。
11+
12+
## Commands
13+
14+
### Development
15+
- `npm run dev` - Start development server with Turbopack
16+
- `npm run build` - Build for production
17+
- `npm run start` - Start production server
18+
- `npm run lint` - Run ESLint
19+
20+
### Docker
21+
- `docker build -t agent-ui .` - Build Docker image
22+
- `docker run -p 3000:3000 agent-ui` - Run container (standalone)
23+
- `docker-compose up` - Start frontend only (requires backend running)
24+
- `docker-compose up --build` - Rebuild and start frontend
25+
- `docker-compose up` - Start frontend container in wechat-rag network
26+
27+
### TypeScript
28+
- Type checking is configured via `tsconfig.json`
29+
- Uses strict TypeScript with Next.js plugin
30+
- Path alias `@/*` maps to root directory for imports
31+
- No test framework currently configured
32+
33+
### Environment Variables
34+
- `WECHAT_API_URL` - WeChat API endpoint (default: http://127.0.0.1:5030)
35+
- `BACKEND_API_URL` - Backend service endpoint (default: http://127.0.0.1:8080)
36+
- `BACKEND_URL` - Alternative backend URL used in API routes (default: http://127.0.0.1:8080)
37+
- `OPENROUTER_API_KEY` - OpenRouter API key for LLM services
38+
39+
**Note**: Runtime environment variables are provided to client-side components via `/api/config` endpoint. This allows containers to read Docker environment variables at runtime rather than build time.
40+
41+
## Architecture
42+
43+
This is a WeChat RAG (Retrieval-Augmented Generation) chatbot frontend built with Next.js 15, React 19, and TypeScript. The application provides a UI for interacting with WeChat chat history through an AI-powered chat interface.
44+
45+
### Core Architecture Patterns
46+
47+
**State Management**: Centralized context-based architecture using `AppProvider` in `contexts/app-context.tsx`. All major application state (settings, UI state, chat, vectorization, WeChat) is managed through this provider.
48+
49+
**Hook-Based Services**: Business logic is encapsulated in custom hooks:
50+
- `use-chat.ts` - Chat functionality with streaming responses via SSE
51+
- `use-vectorization.ts` - Background vectorization progress tracking
52+
- `use-wechat.ts` - WeChat API integration
53+
- `use-settings.ts` - Persistent settings management via localStorage
54+
- `use-mobile.ts` - Mobile device detection
55+
56+
**Component Structure**:
57+
- `components/setup/` - Setup wizard components
58+
- `components/chat/` - Chat interface and message handling
59+
- `components/sync/` - Vectorization/sync progress monitoring
60+
- `components/help/` - FAQ and help components
61+
- `components/ui/` - Reusable UI components (shadcn/ui based)
62+
63+
**API Integration**: RESTful API layer in `lib/api/` with separate modules for:
64+
- `chat.ts` - OpenRouter API for LLM interactions
65+
- `vectorization.ts` - Background processing with SSE progress updates
66+
- `wechat.ts` - WeChat data retrieval and chatroom management
67+
- `base.ts` - Shared HTTP client utilities
68+
69+
### Key Data Flow
70+
71+
1. **Setup Flow**: Users configure API endpoints and credentials through setup wizard
72+
2. **Chat Flow**: Messages are sent to backend, which retrieves relevant WeChat context and forwards to LLM
73+
3. **Vectorization Flow**: Background processing of WeChat data with real-time progress updates via SSE
74+
4. **Persistence**: Settings stored in localStorage, conversations cached locally
75+
76+
### Technology Stack
77+
78+
- **UI Framework**: Next.js 15 with App Router, React 19
79+
- **Styling**: Tailwind CSS v4 with shadcn/ui components and tw-animate-css
80+
- **State**: React Context + custom hooks
81+
- **Forms**: React Hook Form with Zod validation
82+
- **HTTP**: Fetch API with streaming support
83+
- **Icons**: Lucide React
84+
- **Markdown**: react-markdown with remark-gfm for GFM support
85+
- **Notifications**: Sonner for toast notifications
86+
- **Themes**: next-themes for dark/light mode support
87+
88+
### File Organization
89+
90+
- `/app` - Next.js app router pages, layouts, and API routes
91+
- `/components` - React components organized by feature (chat, setup, sync, help, ui)
92+
- `/contexts` - React context providers (centralized app state)
93+
- `/hooks` - Custom React hooks for business logic
94+
- `/lib` - Utilities, types, API clients, and shared constants
95+
- `/doc` - Chinese documentation for the project
96+
97+
The application supports Chinese language and is specifically designed for WeChat chat analysis and interaction.
98+
99+
## Development Patterns
100+
101+
### Code Style
102+
- Use TypeScript with strict mode enabled
103+
- Follow React 19 patterns with hooks and functional components
104+
- Prefer functional programming patterns over class-based components
105+
- Use Zod for runtime type validation in forms
106+
- Event handling with Server-Sent Events (SSE) for real-time updates
107+
108+
### State Management Pattern
109+
- All major state flows through the `AppProvider` context
110+
- Hooks encapsulate business logic and API interactions
111+
- Settings persist to localStorage automatically
112+
- Conversations are cached locally with auto-save functionality
113+
114+
### API Communication
115+
- RESTful endpoints for standard operations
116+
- Server-Sent Events (SSE) for streaming chat responses and progress updates
117+
- Error handling is centralized through context providers
118+
- Connection testing utilities available in `base.ts`
119+
120+
### Component Guidelines
121+
- UI components from shadcn/ui library in `components/ui/`
122+
- Feature components organized by domain (setup, chat, sync, default)
123+
- Form handling with React Hook Form + Zod validation
124+
- Responsive design with mobile detection via `use-mobile.ts` hook
125+
126+
## Critical Architectural Understanding
127+
128+
### Context Provider Architecture
129+
The `AppProvider` (`contexts/app-context.tsx:44`) serves as the single source of truth, managing:
130+
- Settings via `use-settings.ts` hook with localStorage persistence
131+
- Chat state via `use-chat.ts` with EventSource streaming
132+
- UI state including view routing (`default` | `setup` | `chat` | `sync`)
133+
- Conversation history with auto-save to localStorage
134+
135+
### View-Based Routing
136+
Main routing logic in `app/page.tsx:12` switches between views:
137+
- `default` - Welcome/landing page with navigation
138+
- `setup` - Configuration wizard for API endpoints and credentials
139+
- `chat` - Main chat interface with streaming responses
140+
- `sync` - Vectorization progress monitoring and control
141+
142+
### Service Layer Pattern
143+
API services in `lib/api/` follow consistent patterns:
144+
- `ApiClient` base class in `base.ts` provides common HTTP methods
145+
- Service-specific classes extend this pattern
146+
- Connection testing methods standardized across services
147+
- SSE streaming handled specifically in `ChatService`
148+
149+
### Data Persistence Strategy
150+
- Settings: localStorage via `use-settings.ts` with key `wechat-rag-settings`
151+
- Conversations: localStorage via app context with key `wechat-rag-conversations`
152+
- Auto-serialization/deserialization of Date objects for conversation timestamps
153+
154+
### Error Handling Pattern
155+
Centralized error handling through:
156+
- Context provider error state management
157+
- Service-level error propagation to onError callbacks
158+
- Connection status tracking for each external service
159+
160+
### Streaming Implementation
161+
Chat streaming via Server-Sent Events:
162+
- `ChatService.createChatStream()` creates EventSource connections
163+
- Real-time message assembly in `use-chat.ts:133`
164+
- Graceful connection cleanup and error recovery
165+
166+
## Testing
167+
168+
Currently no test framework is configured. If user requests testing:
169+
- Check for existing test setup in `package.json` before suggesting frameworks
170+
- Common patterns would be Jest with React Testing Library for this tech stack
171+
- Consider the existing TypeScript and Next.js 15 configuration when setting up tests
172+
173+
## Backend Integration
174+
175+
The frontend connects to a separate backend service:
176+
- Backend URL defaults to `http://127.0.0.1:8080` (configurable via `BACKEND_API_URL` env var)
177+
- WeChat API URL defaults to `http://127.0.0.1:5030` (configurable via `WECHAT_API_URL` env var)
178+
- Chat endpoint: `GET /api/chat` with query parameters (question, modelName, apiKey)
179+
- Uses Server-Sent Events (SSE) for streaming responses
180+
- Groups and members parameters are logged but not yet supported by backend
181+
182+
## Next.js Configuration
183+
184+
Development configuration in `next.config.ts`:
185+
- Minimal configuration with environment variable injection
186+
- Application version exposed via `NEXT_PUBLIC_APP_VERSION` from package.json
187+
- API proxying handled through dedicated route handlers in `/app/api/` directory
188+
189+
## Proxy API Pattern
190+
191+
API route handlers in `/app/api/` directory provide backend integration:
192+
- `/api/config` - Runtime environment variable configuration
193+
- `/api/proxy/backend/chat/route.ts` - Chat endpoint with SSE streaming support
194+
- `/api/proxy/wechat/[...path]/route.ts` - WeChat API proxy with dynamic path handling
195+
- This pattern eliminates CORS issues and provides unified API interface
196+
- All external service communication is proxied through these endpoints
197+
198+
## Form Validation Strategy
199+
200+
Forms use React Hook Form with Zod validation:
201+
- Schema definitions should be co-located with form components
202+
- Use `@hookform/resolvers/zod` for seamless integration
203+
- Error messages should be in English as per project requirements
204+
- Form state management follows the hook-based pattern
205+
206+
## Event Source (SSE) Implementation Details
207+
208+
Real-time communication via Server-Sent Events:
209+
- `EventSource` connections managed in hooks like `use-chat.ts`
210+
- Connection cleanup handled in `useEffect` cleanup functions
211+
- Graceful error handling and reconnection logic built into hooks
212+
- Message parsing assumes JSON format for structured data
213+
214+
## Mobile Responsiveness
215+
216+
Mobile detection via `use-mobile.ts` hook:
217+
- Uses `window.matchMedia` to detect screen size
218+
- Components conditionally render mobile vs desktop layouts
219+
- Sidebar behavior adapts based on mobile state
220+
- Touch-friendly UI elements on mobile devices
221+
222+
## Development Environment
223+
224+
When running `npm run dev`:
225+
- Uses Next.js 15 with Turbopack for faster development builds
226+
- Hot reload is configured for all file types
227+
- Development server runs on http://localhost:3000 by default
228+
- TypeScript compilation happens in parallel with the dev server
229+
230+
## Docker Deployment
231+
232+
### Deployment Options
233+
234+
#### 2. Frontend Only
235+
如果后端已经在运行,只启动前端:
236+
```bash
237+
# 确保后端服务在 wechat-rag 网络中运行
238+
docker-compose up --build
239+
```
240+
241+
#### 3. Standalone
242+
独立运行前端容器:
243+
```bash
244+
docker build -t agent-ui .
245+
docker run -p 3000:3000 \
246+
-e WECHAT_API_URL=http://host.docker.internal:5030 \
247+
-e BACKEND_API_URL=http://host.docker.internal:8080 \
248+
agent-ui
249+
```
250+
251+
### Environment Configuration
252+
Configure these environment variables in `docker-compose.yml` or pass to `docker run`:
253+
- `WECHAT_API_URL` - WeChat API service endpoint
254+
- `BACKEND_API_URL` - Backend service endpoint
255+
- `BACKEND_URL` - Alternative backend URL for API routes
256+
- `OPENROUTER_API_KEY` - OpenRouter API key (optional, can be configured in UI)
257+
258+
### Network Architecture
259+
- All services run in the `wechat-rag` Docker network
260+
- Frontend communicates with backend using service name: `agent-web:8080`
261+
- WeChat API uses `host.docker.internal:5030` (external to Docker)
262+
- Services can communicate directly without exposing all ports
263+
264+
### Service Dependencies
265+
```
266+
agent-ui (port 3000)
267+
↓ depends on
268+
agent-web (port 8080)
269+
↓ depends on
270+
elasticsearch (port 9200) + redis (port 6379)
271+
```
272+
273+
### File Structure
274+
- `docker-compose.yml` - Frontend only deployment (connects to wechat-rag network)
275+
- `next.config.js` - Production configuration (JavaScript)
276+
- `next.config.ts` - Development configuration (TypeScript)
277+
278+
### Production Optimizations
279+
- Uses Next.js standalone output mode for smaller Docker images
280+
- Separate JavaScript config file eliminates TypeScript runtime dependency
281+
- Multi-stage Docker build with build-time dependency installation
282+
- Runtime environment variable support via API endpoints
283+
284+
# important-instruction-reminders
285+
Do what has been asked; nothing more, nothing less.
286+
NEVER create files unless they're absolutely necessary for achieving your goal.
287+
ALWAYS prefer editing an existing file to creating a new one.
288+
NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.

0 commit comments

Comments
 (0)