# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

云酒馆 (SillyTavern Cloud) — a full-stack AI role-playing chat platform. Frontend is React + TypeScript + Tailwind + Vite (`web-app/`). Backend is Go + Gin + GORM (`server/`). The two are fully separated and communicate via REST API + SSE streaming.

## Build & Run Commands

### Frontend (`web-app/`)
```bash
npm install
npm run dev        # Dev server at http://localhost:5174
npm run build      # tsc + vite build (type-check then bundle)
npm run preview    # Preview production build
```

### Backend (`server/`)
```bash
go mod tidy
go build -o server .
./server -c config.yaml    # Runs at http://localhost:8888
```

### Type-check only (no emit)
```bash
# Frontend
cd web-app && npx tsc --noEmit

# Backend
cd server && go build ./...
```

## Build Verification

After any code edit, always run the build/compile step before reporting success. For Go files: `go build ./...`. For TypeScript files: `npx tsc --noEmit`. Never assume edits are correct without verification.

## Architecture

### Backend (`server/`)

Layered architecture: **routes → API handlers → services → models/DB**

```
api/v1/app/        # App-facing HTTP handlers (auth, character, conversation, ai_config, etc.)
api/v1/system/     # Admin/system handlers
service/app/       # Business logic layer
model/app/         # GORM data models (AppUser, AiCharacter, Conversation, Preset, Worldbook, RegexScript)
router/app/        # Gin route registration
middleware/        # JWT auth, CORS, logging, recovery
initialize/        # DB, Redis, router, plugin setup (called from main.go)
core/              # Zap logging, Viper config loading, server startup
```

Key models: `AppUser`, `AiCharacter` (SillyTavern V2 card format), `Conversation`, `Preset` (sampling params), `Worldbook` (keyword-triggered context), `RegexScript` (message transforms).

AI providers: OpenAI-compatible + Anthropic. Unified through the AI config service. Conversations use SSE streaming for real-time token delivery.

### Frontend (`web-app/src/`)

MVU (Model-View-Update) pattern via **Zustand** with `persist` middleware (localStorage).

```
store/index.ts     # Single global Zustand store — source of truth for user, currentCharacter,
                   # currentConversation, messages, variables, UI state
api/               # One file per domain: auth, character, conversation, preset, worldbook, regex
                   # All share the axios instance in api/client.ts (injects JWT, handles 401)
pages/             # Route-level components (ChatPage, CharacterManagePage, AdminPage, etc.)
components/        # Reusable UI — ChatArea, CharacterPanel, SettingsPanel, Sidebar, Navbar,
                   # MessageContent (renders markdown + HTML safely via rehype-sanitize)
```

Routes are defined in `App.tsx`. Auth guard redirects to `/login` when `isAuthenticated` is false.

The `variables: Record<string, string>` field in the store implements the MVU variable system used for template substitution in AI prompts (e.g., `{{user}}`, `{{char}}`).

### API Convention

- Base URL: `http://localhost:8888` (configured via `VITE_API_BASE_URL` in `.env.development`)
- Auth: `Authorization: Bearer <jwt>` header, injected automatically by `api/client.ts`
- App routes: `/app/auth/...`, `/app/user/...`, `/app/character/...`, `/app/conversation/...`
- Admin routes: `/system/...` (Casbin RBAC enforced)

## Go Development

When editing Go files, always check all call sites of modified functions. If a function signature changes (parameters or return values), grep for all usages and update them in the same edit batch.

Run `go build ./...` from `server/` to verify after every edit.

## Frontend Development

When editing Vue/TypeScript frontend files, verify all imports are present and no duplicate code remains after edits. Read the file back after editing to confirm structural integrity.

Run `npx tsc --noEmit` from `web-app/` to verify after every edit.

## Third-Party Integrations

When integrating third-party SDKs or APIs (payment providers, AI model APIs), read the actual SDK source or docs first before writing code. Do not guess method names, parameter types, or key sizes.

## Configuration

Backend config file: `server/config.yaml` (not committed; copy from `config.example.yaml` if present). Supports MySQL, PostgreSQL, SQLite, SQL Server, Oracle via GORM. Redis for sessions/caching.

Frontend env files: `web-app/.env.development` and `web-app/.env.production` — set `VITE_API_BASE_URL`.
