๐คฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
โป๏ธ refactor: migrate AI Rules to Claude Code Skills (#11737)
Innei346fc4617eff
diff --git a/.agents/skills/add-provider-doc/SKILL.md b/.agents/skills/add-provider-doc/SKILL.mdnew file mode 100644index 00000000000..82568080abe--- /dev/null+++ b/.agents/skills/add-provider-doc/SKILL.md@@ -0,0 +1,90 @@+---+name: add-provider-doc+description: Guide for adding new AI provider documentation. Use when adding documentation for a new AI provider (like OpenAI, Anthropic, etc.), including usage docs, environment variables, Docker config, and image resources. Triggers on provider documentation tasks.+---++# Adding New AI Provider Documentation++Complete workflow for adding documentation for a new AI provider.++## Overview++1. Create usage documentation (EN + CN)+2. Add environment variable documentation (EN + CN)+3. Update Docker configuration files+4. Update .env.example+5. Prepare image resources++## Step 1: Create Provider Usage Documentation++### Required Files++- `docs/usage/providers/{provider-name}.mdx` (English)+- `docs/usage/providers/{provider-name}.zh-CN.mdx` (Chinese)++### Key Requirements++- 5-6 screenshots showing the process+- Cover image for the provider+- Real registration and dashboard URLs+- Pricing information callout+- **Never include real API keys** - use placeholders++Reference: `docs/usage/providers/fal.mdx`++## Step 2: Update Environment Variables Documentation++### Files to Update++- `docs/self-hosting/environment-variables/model-provider.mdx` (EN)+- `docs/self-hosting/environment-variables/model-provider.zh-CN.mdx` (CN)++### Content Format++```markdown+### `{PROVIDER}_API_KEY`+- Type: Required+- Description: API key from {Provider Name}+- Example: `{api-key-format}`++### `{PROVIDER}_MODEL_LIST`+- Type: Optional+- Description: Control model list. Use `+` to add, `-` to hide+- Example: `-all,+model-1,+model-2=Display Name`+```++## Step 3: Update Docker Files++Update all Dockerfiles at the **end** of ENV section:++- `Dockerfile`+- `Dockerfile.database`+- `Dockerfile.pglite`++```dockerfile+# {New Provider}+{PROVIDER}_API_KEY="" {PROVIDER}_MODEL_LIST=""+```++## Step 4: Update .env.example++```bash+### {Provider Name} ###+# {PROVIDER}_API_KEY={prefix}-xxxxxxxx+```++## Step 5: Image Resources++- Cover image+- 3-4 API dashboard screenshots+- 2-3 LobeChat configuration screenshots+- Host on LobeHub CDN: `hub-apac-1.lobeobjects.space`++## Checklist++- [ ] EN + CN usage docs+- [ ] EN + CN env var docs+- [ ] All 3 Dockerfiles updated+- [ ] .env.example updated+- [ ] All images prepared+- [ ] No real API keys in docsdiff --git a/.agents/skills/add-setting-env/SKILL.md b/.agents/skills/add-setting-env/SKILL.mdnew file mode 100644index 00000000000..d3e4de3a644--- /dev/null+++ b/.agents/skills/add-setting-env/SKILL.md@@ -0,0 +1,106 @@+---+name: add-setting-env+description: Guide for adding environment variables to configure user settings. Use when implementing server-side environment variables that control default values for user settings. Triggers on env var configuration or setting default value tasks.+---++# Adding Environment Variable for User Settings++Add server-side environment variables to configure default values for user settings.++**Priority**: User Custom > Server Env Var > Hardcoded Default++## Steps++### 1. Define Environment Variable++Create `src/envs/<domain>.ts`:++```typescript+import { createEnv } from '@t3-oss/env-nextjs';+import { z } from 'zod';++export const get<Domain>Config = () => {+ return createEnv({+ server: {+ YOUR_ENV_VAR: z.coerce.number().min(MIN).max(MAX).optional(),+ },+ runtimeEnv: {+ YOUR_ENV_VAR: process.env.YOUR_ENV_VAR,+ },+ });+};++export const <domain>Env = get<Domain>Config();+```++### 2. Update Type (if new domain)++Add to `packages/types/src/serverConfig.ts`:++```typescript+import { User<Domain>Config } from './user/settings';++export interface GlobalServerConfig {+ <domain>?: PartialDeep<User<Domain>Config>;+}+```++**Prefer reusing existing types** from `packages/types/src/user/settings`.++### 3. Assemble Server Config (if new domain)++In `src/server/globalConfig/index.ts`:++```typescript+import { <domain>Env } from '@/envs/<domain>';++export const getServerGlobalConfig = async () => {+ const config: GlobalServerConfig = {+ <domain>: cleanObject({+ <settingName>: <domain>Env.YOUR_ENV_VAR,+ }),+ };+ return config;+};+```++### 4. Merge to User Store (if new domain)++In `src/store/user/slices/common/action.ts`:++```typescript+const serverSettings: PartialDeep<UserSettings> = {+ <domain>: serverConfig.<domain>,+};+```++### 5. Update .env.example++```bash+# <Description> (range/options, default: X)+# YOUR_ENV_VAR=<example>+```++### 6. Update Documentation++- `docs/self-hosting/environment-variables/basic.mdx` (EN)+- `docs/self-hosting/environment-variables/basic.zh-CN.mdx` (CN)++## Example: AI_IMAGE_DEFAULT_IMAGE_NUM++```typescript+// src/envs/image.ts+AI_IMAGE_DEFAULT_IMAGE_NUM: z.coerce.number().min(1).max(20).optional(),++// packages/types/src/serverConfig.ts+image?: PartialDeep<UserImageConfig>;++// src/server/globalConfig/index.ts+image: cleanObject({ defaultImageNum: imageEnv.AI_IMAGE_DEFAULT_IMAGE_NUM }),++// src/store/user/slices/common/action.ts+image: serverConfig.image,++// .env.example+# AI_IMAGE_DEFAULT_IMAGE_NUM=4+```diff --git a/.agents/skills/debug/SKILL.md b/.agents/skills/debug/SKILL.mdnew file mode 100644index 00000000000..ed28ae77f8a--- /dev/null+++ b/.agents/skills/debug/SKILL.md@@ -0,0 +1,66 @@+---+name: debug+description: Debug package usage guide. Use when adding debug logging, understanding log namespaces, or implementing debugging features. Triggers on debug logging requests or logging implementation.+user-invocable: false+---++# Debug Package Usage Guide++## Basic Usage++```typescript+import debug from 'debug';++// Format: lobe-[module]:[submodule]+const log = debug('lobe-server:market');++log('Simple message');+log('With variable: %O', object);+log('Formatted number: %d', number);+```++## Namespace Conventions++- Desktop: `lobe-desktop:[module]`+- Server: `lobe-server:[module]`+- Client: `lobe-client:[module]`+- Router: `lobe-[type]-router:[module]`++## Format Specifiers++- `%O` - Object expanded (recommended for complex objects)+- `%o` - Object+- `%s` - String+- `%d` - Number++## Enable Debug Output++### Browser++```javascript+localStorage.debug = 'lobe-*';+```++### Node.js++```bash+DEBUG=lobe-* npm run dev+DEBUG=lobe-* pnpm dev+```++### Electron++```typescript+process.env.DEBUG = 'lobe-*';+```++## Example++```typescript+// src/server/routers/edge/market/index.ts+import debug from 'debug';++const log = debug('lobe-edge-router:market');++log('getAgent input: %O', input);+```diff --git a/.agents/skills/desktop/SKILL.md b/.agents/skills/desktop/SKILL.mdnew file mode 100644index 00000000000..01f96501794--- /dev/null+++ b/.agents/skills/desktop/SKILL.md@@ -0,0 +1,78 @@+---+name: desktop+description: Electron desktop development guide. Use when implementing desktop features, IPC handlers, controllers, preload scripts, window management, menu configuration, or Electron-specific functionality. Triggers on desktop app development, Electron IPC, or desktop local tools implementation.+disable-model-invocation: true+---++# Desktop Development Guide++## Architecture Overview++LobeChat desktop is built on Electron with main-renderer architecture:++1. **Main Process** (`apps/desktop/src/main`): App lifecycle, system APIs, window management+2. **Renderer Process**: Reuses web code from `src/`+3. **Preload Scripts** (`apps/desktop/src/preload`): Securely expose main process to renderer++## Adding New Desktop Features++### 1. Create Controller+Location: `apps/desktop/src/main/controllers/`++```typescript+import { ControllerModule, IpcMethod } from '@/controllers';++export default class NewFeatureCtr extends ControllerModule {+ static override readonly groupName = 'newFeature';++ @IpcMethod()+ async doSomething(params: SomeParams): Promise<SomeResult> {+ // Implementation+ return { success: true };+ }+}+```++Register in `apps/desktop/src/main/controllers/registry.ts`.++### 2. Define IPC Types+Location: `packages/electron-client-ipc/src/types.ts`++```typescript+export interface SomeParams { /* ... */ }+export interface SomeResult { success: boolean; error?: string }+```++### 3. Create Renderer Service+Location: `src/services/electron/`++```typescript+import { ensureElectronIpc } from '@/utils/electron/ipc';++const ipc = ensureElectronIpc();++export const newFeatureService = async (params: SomeParams) => {+ return ipc.newFeature.doSomething(params);+};+```++### 4. Implement Store Action+Location: `src/store/`++### 5. Add Tests+Location: `apps/desktop/src/main/controllers/__tests__/`++## Detailed Guides++See `references/` for specific topics:+- **Feature implementation**: `references/feature-implementation.md`+- **Local tools workflow**: `references/local-tools.md`+- **Menu configuration**: `references/menu-config.md`+- **Window management**: `references/window-management.md`++## Best Practices++1. **Security**: Validate inputs, limit exposed APIs+2. **Performance**: Use async methods, batch data transfers+3. **UX**: Add progress indicators, provide error feedback+4. **Code organization**: Follow existing patterns, add documentationdiff --git a/.agents/skills/desktop/references/feature-implementation.md b/.agents/skills/desktop/references/feature-implementation.mdnew file mode 100644index 00000000000..cfc155edf8e--- /dev/null+++ b/.agents/skills/desktop/references/feature-implementation.md@@ -0,0 +1,99 @@+# Desktop Feature Implementation Guide++## Architecture Overview++```plaintext+Main Process Renderer Process+โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ+โ Controller โโโโIPCโโโโบโ Service Layer โ+โ (IPC Handler) โ โ โ+โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ+ โ โ+ โผ โผ+โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ+โ System APIs โ โ Store Actions โ+โ (fs, network) โ โ (UI State) โ+โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ+```++## Step-by-Step Implementation++### 1. Create Controller++```typescript+// apps/desktop/src/main/controllers/NotificationCtr.ts+import type { ShowDesktopNotificationParams, DesktopNotificationResult } from '@lobechat/electron-client-ipc';+import { Notification } from 'electron';+import { ControllerModule, IpcMethod } from '@/controllers';++export default class NotificationCtr extends ControllerModule {+ static override readonly groupName = 'notification';++ @IpcMethod()+ async showDesktopNotification(params: ShowDesktopNotificationParams): Promise<DesktopNotificationResult> {+ if (!Notification.isSupported()) {+ return { error: 'Notifications not supported', success: false };+ }++ try {+ const notification = new Notification({ body: params.body, title: params.title });+ notification.show();+ return { success: true };+ } catch (error) {+ console.error('[NotificationCtr] Failed:', error);+ return { error: error instanceof Error ? error.message : 'Unknown error', success: false };+ }+ }+}+```++### 2. Define IPC Types++```typescript+// packages/electron-client-ipc/src/types.ts+export interface ShowDesktopNotificationParams {+ title: string;+ body: string;+}++export interface DesktopNotificationResult {+ success: boolean;+ error?: string;+}+```++### 3. Create Service Layer++```typescript+// src/services/electron/notificationService.ts+import type { ShowDesktopNotificationParams } from '@lobechat/electron-client-ipc';+import { ensureElectronIpc } from '@/utils/electron/ipc';++const ipc = ensureElectronIpc();++export const notificationService = {+ show: (params: ShowDesktopNotificationParams) =>+ ipc.notification.showDesktopNotification(params),+};+```++### 4. Implement Store Action++```typescript+// src/store/.../actions.ts+showNotification: async (title: string, body: string) => {+ if (!isElectron) return;++ const result = await notificationService.show({ title, body });+ if (!result.success) {+ console.error('Notification failed:', result.error);+ }+},+```++## Best Practices++1. **Security**: Validate inputs, limit exposed APIs+2. **Performance**: Use async methods for heavy operations+3. **Error handling**: Always return structured results+4. **UX**: Provide loading states and error feedbackdiff --git a/.agents/skills/desktop/references/local-tools.md b/.agents/skills/desktop/references/local-tools.mdnew file mode 100644index 00000000000..ca6952d0057--- /dev/null+++ b/.agents/skills/desktop/references/local-tools.md@@ -0,0 +1,133 @@+# Desktop Local Tools Implementation++## Workflow Overview++1. Define tool interface (Manifest)+2. Define related types+3. Implement Store Action+4. Implement Service Layer+5. Implement Controller (IPC Handler)+6. Update Agent documentation++## Step 1: Define Tool Interface (Manifest)++Location: `src/tools/[tool_category]/index.ts`++```typescript+// src/tools/local-files/index.ts+export const LocalFilesApiName = {+ RenameFile: 'renameFile',+ MoveFile: 'moveFile',+} as const;++export const LocalFilesManifest = {+ api: [+ {+ name: LocalFilesApiName.RenameFile,+ description: 'Rename a local file',+ parameters: {+ type: 'object',+ properties: {+ oldPath: { type: 'string', description: 'Current file path' },+ newName: { type: 'string', description: 'New file name' },+ },+ required: ['oldPath', 'newName'],+ },+ },+ ],+};+```++## Step 2: Define Types++```typescript+// packages/electron-client-ipc/src/types.ts+export interface RenameLocalFileParams {+ oldPath: string;+ newName: string;+}++// src/tools/local-files/type.ts+export interface LocalRenameFileState {+ success: boolean;+ error?: string;+ oldPath: string;+ newPath: string;+}+```++## Step 3: Implement Store Action++```typescript+// src/store/chat/slices/builtinTool/actions/localFile.ts+renameLocalFile: async (id: string, params: RenameLocalFileParams) => {+ const { toggleLocalFileLoading, updatePluginState, internal_updateMessageContent } = get();++ toggleLocalFileLoading(id, true);++ try {+ const result = await localFileService.renameFile(params);++ if (result.success) {+ updatePluginState(id, { success: true, ...result });+ internal_updateMessageContent(id, JSON.stringify({ success: true }));+ } else {+ updatePluginState(id, { success: false, error: result.error });+ internal_updateMessageContent(id, JSON.stringify({ error: result.error }));+ }++ return result.success;+ } catch (e) {+ console.error(e);+ updatePluginState(id, { success: false, error: e.message });+ return false;+ } finally {+ toggleLocalFileLoading(id, false);+ }+},+```++## Step 4: Implement Service Layer++```typescript+// src/services/electron/localFileService.ts+import { ensureElectronIpc } from '@/utils/electron/ipc';++const ipc = ensureElectronIpc();++export const localFileService = {+ renameFile: (params: RenameLocalFileParams) => ipc.localFiles.renameFile(params),+};+```++## Step 5: Implement Controller++```typescript+// apps/desktop/src/main/controllers/LocalFileCtr.ts+import * as fs from 'fs/promises';+import * as path from 'path';+import { ControllerModule, IpcMethod } from '@/controllers';++export default class LocalFileCtr extends ControllerModule {+ static override readonly groupName = 'localFiles';++ @IpcMethod()+ async renameFile(params: RenameLocalFileParams) {+ const { oldPath, newName } = params;+ const newPath = path.join(path.dirname(oldPath), newName);++ try {+ await fs.rename(oldPath, newPath);+ return { success: true, newPath };+ } catch (error) {+ return { success: false, error: error.message };+ }+ }+}+```++## Step 6: Update Agent Documentation++Location: `src/tools/[tool_category]/systemRole.ts`++Add tool description to `<core_capabilities>` and usage guidelines to `<tool_usage_guidelines>`.diff --git a/.agents/skills/desktop/references/menu-config.md b/.agents/skills/desktop/references/menu-config.mdnew file mode 100644index 00000000000..769eaf0f4f7--- /dev/null+++ b/.agents/skills/desktop/references/menu-config.md@@ -0,0 +1,103 @@+# Desktop Menu Configuration Guide++## Menu Types++1. **App Menu**: Top of window (macOS) or title bar (Windows/Linux)+2. **Context Menu**: Right-click menus+3. **Tray Menu**: System tray icon menus++## File Structure++```plaintext+apps/desktop/src/main/+โโโ menus/+โ โโโ appMenu.ts # App menu config+โ โโโ contextMenu.ts # Context menu config+โ โโโ factory.ts # Menu factory functions+โโโ controllers/+โ โโโ MenuCtr.ts # Menu controller+โ โโโ TrayMenuCtr.ts # Tray menu controller+```++## App Menu Configuration++```typescript+// apps/desktop/src/main/menus/appMenu.ts+import { BrowserWindow, Menu, MenuItemConstructorOptions } from 'electron';++export const createAppMenu = (win: BrowserWindow) => {+ const template: MenuItemConstructorOptions[] = [+ {+ label: 'File',+ submenu: [+ { label: 'New', accelerator: 'CmdOrCtrl+N', click: () => { /* ... */ } },+ { type: 'separator' },+ { role: 'quit' },+ ],+ },+ // ...+ ];++ return Menu.buildFromTemplate(template);+};++// Register in MenuCtr.ts+Menu.setApplicationMenu(menu);+```++## Context Menu++```typescript+export const createContextMenu = () => {+ const template = [+ { label: 'Copy', role: 'copy' },+ { label: 'Paste', role: 'paste' },+ ];+ return Menu.buildFromTemplate(template);+};++// Show on right-click+const menu = createContextMenu();+menu.popup();+```++## Tray Menu++```typescript+// TrayMenuCtr.ts+this.tray = new Tray(trayIconPath);+const contextMenu = Menu.buildFromTemplate([+ { label: 'Show Window', click: this.showMainWindow },+ { type: 'separator' },+ { label: 'Quit', click: () => app.quit() },+]);+this.tray.setContextMenu(contextMenu);+```++## i18n Support++```typescript+import { i18n } from '../locales';++const template = [+ {+ label: i18n.t('menu.file'),+ submenu: [+ { label: i18n.t('menu.new'), click: createNew },+ ],+ },+];+```++## Best Practices++1. Use standard roles (`role: 'copy'`) for native behavior+2. Use `CmdOrCtrl` for cross-platform shortcuts+3. Use `{ type: 'separator' }` to group related items+4. Handle platform differences with `process.platform`++```typescript+if (process.platform === 'darwin') {+ template.unshift({ role: 'appMenu' });+}+```diff --git a/.agents/skills/desktop/references/window-management.md b/.agents/skills/desktop/references/window-management.mdnew file mode 100644index 00000000000..b8d9a7f8b35--- /dev/null+++ b/.agents/skills/desktop/references/window-management.md@@ -0,0 +1,143 @@+# Desktop Window Management Guide++## Window Management Overview++1. Window creation and configuration+2. Window state management (size, position, maximize)+3. Multi-window coordination+4. Window event handling++## File Structure++```plaintext+apps/desktop/src/main/+โโโ appBrowsers.ts # Core window management+โโโ controllers/+โ โโโ BrowserWindowsCtr.ts # Window controller+โโโ modules/+ โโโ browserWindowManager.ts # Window manager module+```++## Window Creation++```typescript+export const createMainWindow = () => {+ const mainWindow = new BrowserWindow({+ width: 1200,+ height: 800,+ minWidth: 600,+ minHeight: 400,+ webPreferences: {+ preload: path.join(__dirname, '../preload/index.js'),+ contextIsolation: true,+ nodeIntegration: false,+ },+ });++ if (isDev) {+ mainWindow.loadURL('http://localhost:3000');+ } else {+ mainWindow.loadFile(path.join(__dirname, '../../renderer/index.html'));+ }++ return mainWindow;+};+```++## Window State Persistence++```typescript+const saveWindowState = (window: BrowserWindow) => {+ if (!window.isMinimized() && !window.isMaximized()) {+ const [x, y] = window.getPosition();+ const [width, height] = window.getSize();+ settings.set('windowState', { x, y, width, height });+ }+};++const restoreWindowState = (window: BrowserWindow) => {+ const state = settings.get('windowState');+ if (state) {+ window.setBounds({ x: state.x, y: state.y, width: state.width, height: state.height });+ }+};++window.on('close', () => saveWindowState(window));+```++## Multi-Window Management++```typescript+export class WindowManager {+ private windows: Map<string, BrowserWindow> = new Map();++ createWindow(id: string, options: BrowserWindowConstructorOptions) {+ const window = new BrowserWindow(options);+ this.windows.set(id, window);+ window.on('closed', () => this.windows.delete(id));+ return window;+ }++ getWindow(id: string) {+ return this.windows.get(id);+ }+}+```++## Window IPC Controller++```typescript+// apps/desktop/src/main/controllers/BrowserWindowsCtr.ts+export default class BrowserWindowsCtr extends ControllerModule {+ static override readonly groupName = 'windows';++ @IpcMethod()+ minimizeWindow() {+ BrowserWindow.getFocusedWindow()?.minimize();+ return { success: true };+ }++ @IpcMethod()+ maximizeWindow() {+ const win = BrowserWindow.getFocusedWindow();+ win?.isMaximized() ? win.restore() : win?.maximize();+ return { success: true };+ }+}+```++## Renderer Service++```typescript+// src/services/electron/windowService.ts+import { ensureElectronIpc } from '@/utils/electron/ipc';++const ipc = ensureElectronIpc();++export const windowService = {+ minimize: () => ipc.windows.minimizeWindow(),+ maximize: () => ipc.windows.maximizeWindow(),+ close: () => ipc.windows.closeWindow(),+};+```++## Frameless Window++```typescript+const window = new BrowserWindow({+ frame: false,+ titleBarStyle: 'hidden',+});+```++```css+.titlebar { -webkit-app-region: drag; }+.titlebar-button { -webkit-app-region: no-drag; }+```++## Best Practices++1. Use `show: false` initially, show after content loads+2. Always set secure `webPreferences`+3. Handle `webContents.on('crashed')` for recovery+4. Clean up resources on `window.on('closed')`diff --git a/.agents/skills/drizzle/SKILL.md b/.agents/skills/drizzle/SKILL.mdnew file mode 100644index 00000000000..a44389cef8b--- /dev/null+++ b/.agents/skills/drizzle/SKILL.md@@ -0,0 +1,129 @@+---+name: drizzle+description: Drizzle ORM schema and database guide. Use when working with database schemas (src/database/schemas/*), defining tables, creating migrations, or database model code. Triggers on Drizzle schema definition, database migrations, or ORM usage questions.+---++# Drizzle ORM Schema Style Guide++## Configuration++- Config: `drizzle.config.ts`+- Schemas: `src/database/schemas/`+- Migrations: `src/database/migrations/`+- Dialect: `postgresql` with `strict: true`++## Helper Functions++Location: `src/database/schemas/_helpers.ts`++- `timestamptz(name)`: Timestamp with timezone+- `createdAt()`, `updatedAt()`, `accessedAt()`: Standard timestamp columns+- `timestamps`: Object with all three for easy spread++## Naming Conventions++- **Tables**: Plural snake_case (`users`, `session_groups`)+- **Columns**: snake_case (`user_id`, `created_at`)++## Column Definitions++### Primary Keys++```typescript+id: text('id')+ .primaryKey()+ .$defaultFn(() => idGenerator('agents'))+ .notNull(),+```++ID prefixes make entity types distinguishable. For internal tables, use `uuid`.++### Foreign Keys++```typescript+userId: text('user_id')+ .references(() => users.id, { onDelete: 'cascade' })+ .notNull(),+```++### Timestamps++```typescript+...timestamps, // Spread from _helpers.ts+```++### Indexes++```typescript+// Return array (object style deprecated)+(t) => [uniqueIndex('client_id_user_id_unique').on(t.clientId, t.userId)],+```++## Type Inference++```typescript+export const insertAgentSchema = createInsertSchema(agents);+export type NewAgent = typeof agents.$inferInsert;+export type AgentItem = typeof agents.$inferSelect;+```++## Example Pattern++```typescript+export const agents = pgTable(+ 'agents',+ {+ id: text('id').primaryKey().$defaultFn(() => idGenerator('agents')).notNull(),+ slug: varchar('slug', { length: 100 }).$defaultFn(() => randomSlug(4)).unique(),+ userId: text('user_id').references(() => users.id, { onDelete: 'cascade' }).notNull(),+ clientId: text('client_id'),+ chatConfig: jsonb('chat_config').$type<LobeAgentChatConfig>(),+ ...timestamps,+ },+ (t) => [uniqueIndex('client_id_user_id_unique').on(t.clientId, t.userId)],+);+```++## Common Patterns++### Junction Tables (Many-to-Many)++```typescript+export const agentsKnowledgeBases = pgTable(+ 'agents_knowledge_bases',+ {+ agentId: text('agent_id').references(() => agents.id, { onDelete: 'cascade' }).notNull(),+ knowledgeBaseId: text('knowledge_base_id').references(() => knowledgeBases.id, { onDelete: 'cascade' }).notNull(),+ userId: text('user_id').references(() => users.id, { onDelete: 'cascade' }).notNull(),+ enabled: boolean('enabled').default(true),+ ...timestamps,+ },+ (t) => [primaryKey({ columns: [t.agentId, t.knowledgeBaseId] })],+);+```++## Database Migrations++See `references/db-migrations.md` for detailed migration guide.++```bash+# Generate migrations+bun run db:generate++# After modifying SQL (e.g., adding IF NOT EXISTS)+bun run db:generate:client+```++### Migration Best Practices++```sql+-- โ Idempotent operations+ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "avatar" text;+DROP TABLE IF EXISTS "old_table";+CREATE INDEX IF NOT EXISTS "users_email_idx" ON "users" ("email");++-- โ Non-idempotent+ALTER TABLE "users" ADD COLUMN "avatar" text;+```++Rename migration files meaningfully: `0046_meaningless.sql` โ `0046_user_add_avatar.sql`diff --git a/.agents/skills/drizzle/references/db-migrations.md b/.agents/skills/drizzle/references/db-migrations.mdnew file mode 100644index 00000000000..a5afec8275e--- /dev/null+++ b/.agents/skills/drizzle/references/db-migrations.md@@ -0,0 +1,50 @@+# Database Migrations Guide++## Step 1: Generate Migrations++```bash+bun run db:generate+```++This generates:++- `packages/database/migrations/0046_meaningless_file_name.sql`++And updates:++- `packages/database/migrations/meta/_journal.json`+- `packages/database/src/core/migrations.json`+- `docs/development/database-schema.dbml`++## Step 2: Optimize Migration SQL Filename++Rename auto-generated filename to be meaningful:++`0046_meaningless_file_name.sql` โ `0046_user_add_avatar_column.sql`++## Step 3: Use Idempotent Clauses (Defensive Programming)++Always use defensive clauses to make migrations idempotent:++```sql+-- โ Good: Idempotent operations+ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "avatar" text;+DROP TABLE IF EXISTS "old_table";+CREATE INDEX IF NOT EXISTS "users_email_idx" ON "users" ("email");+ALTER TABLE "posts" DROP COLUMN IF EXISTS "deprecated_field";++-- โ Bad: Non-idempotent operations+ALTER TABLE "users" ADD COLUMN "avatar" text;+DROP TABLE "old_table";+CREATE INDEX "users_email_idx" ON "users" ("email");+```++## Important++After modifying migration SQL (e.g., adding `IF NOT EXISTS` clauses), run:++```bash+bun run db:generate:client+```++This updates the hash in `packages/database/src/core/migrations.json`.diff --git a/.agents/skills/hotkey/SKILL.md b/.agents/skills/hotkey/SKILL.mdnew file mode 100644index 00000000000..2f96149aa8c--- /dev/null+++ b/.agents/skills/hotkey/SKILL.md@@ -0,0 +1,90 @@+---+name: hotkey+description: Guide for adding keyboard shortcuts. Use when implementing new hotkeys, registering shortcuts, or working with keyboard interactions. Triggers on hotkey implementation or keyboard shortcut tasks.+---++# Adding Keyboard Shortcuts Guide++## Steps to Add a New Hotkey++### 1. Update Hotkey Constant++In `src/types/hotkey.ts`:++```typescript+export const HotkeyEnum = {+ // existing...+ ClearChat: 'clearChat', // Add new+} as const;+```++### 2. Register Default Hotkey++In `src/const/hotkeys.ts`:++```typescript+import { KeyMapEnum as Key, combineKeys } from '@lobehub/ui';++export const HOTKEYS_REGISTRATION: HotkeyRegistration = [+ {+ group: HotkeyGroupEnum.Conversation,+ id: HotkeyEnum.ClearChat,+ keys: combineKeys([Key.Mod, Key.Shift, Key.Backspace]),+ scopes: [HotkeyScopeEnum.Chat],+ },+];+```++### 3. Add i18n Translation++In `src/locales/default/hotkey.ts`:++```typescript+const hotkey: HotkeyI18nTranslations = {+ clearChat: {+ desc: 'ๆธ ็ฉบๅฝๅไผ่ฏ็ๆๆๆถๆฏ่ฎฐๅฝ',+ title: 'ๆธ ็ฉบ่ๅคฉ่ฎฐๅฝ',+ },+};+```++### 4. Create and Register Hook++In `src/hooks/useHotkeys/chatScope.ts`:++```typescript+export const useClearChatHotkey = () => {+ const clearMessages = useChatStore((s) => s.clearMessages);+ return useHotkeyById(HotkeyEnum.ClearChat, clearMessages);+};++export const useRegisterChatHotkeys = () => {+ useClearChatHotkey();+ // ...other hotkeys+};+```++### 5. Add Tooltip (Optional)++```tsx+const clearChatHotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.ClearChat));++<Tooltip hotkey={clearChatHotkey} title={t('clearChat.title', { ns: 'hotkey' })}>+ <Button icon={<DeleteOutlined />} onClick={clearMessages} />+</Tooltip>+```++## Best Practices++1. **Scope**: Choose global or chat scope based on functionality+2. **Grouping**: Place in appropriate group (System/Layout/Conversation)+3. **Conflict check**: Ensure no conflict with system/browser shortcuts+4. **Platform**: Use `Key.Mod` instead of hardcoded `Ctrl` or `Cmd`+5. **Clear description**: Provide title and description for users++## Troubleshooting++- **Not working**: Check scope and RegisterHotkeys hook+- **Not in settings**: Verify HOTKEYS_REGISTRATION config+- **Conflict**: HotkeyInput component shows warnings+- **Page-specific**: Ensure correct scope activationdiff --git a/.cursor/rules/i18n.mdc b/.agents/skills/i18n/SKILL.mdsimilarity index 57%rename from .cursor/rules/i18n.mdcrename to .agents/skills/i18n/SKILL.mdindex c127f6476c8..b0ec7855de1 100644--- a/.cursor/rules/i18n.mdc+++ b/.agents/skills/i18n/SKILL.md@@ -1,15 +1,14 @@----globs: *.tsx-alwaysApply: false+name: i18n+description: Internationalization guide using react-i18next. Use when adding translations, creating i18n keys, or working with localized text in React components (.tsx files). Triggers on translation tasks, locale management, or i18n implementation.---# LobeChat Internationalization Guide-## Key Points--- Default language: Chinese (zh-CN), Framework: react-i18next+- Default language: Chinese (zh-CN)+- Framework: react-i18next- **Only edit files in `src/locales/default/`** - Never edit JSON files in `locales/`-- Run `pnpm i18n` to generate all translations (or manually translate zh-CN/en-US for dev preview)+- Run `pnpm i18n` to generate translations (or manually translate zh-CN/en-US for dev preview)## Key Naming Convention@@ -19,37 +18,30 @@ alwaysApply: false// โ Correctexport default {'alert.cloud.action': '็ซๅณไฝ้ช',- 'clientDB.error.desc': 'ๆฐๆฎๅบๅๅงๅ้ๅฐ้ฎ้ข','sync.actions.sync': '็ซๅณๅๆญฅ','sync.status.ready': 'ๅทฒ่ฟๆฅ',};-// โ Avoid: Nested objects+// โ Avoid nested objectsexport default {alert: { cloud: { action: '...' } },};```-**Naming patterns:** `{feature}.{context}.{action|status}`--- `clientDB.modal.title` - Feature + context + property-- `sync.actions.sync` - Feature + group + action-- `sync.status.ready` - Feature + group + status+**Patterns:** `{feature}.{context}.{action|status}`**Parameters:** Use `{{variableName}}` syntax-```typescript'alert.cloud.desc': 'ๆไปฌๆไพ {{credit}} ้ขๅบฆ็งฏๅ',```-**Avoid key conflicts:** Don't use both a leaf key and its parent path-+**Avoid key conflicts:**```typescript-// โ Conflict: clientDB.solve exists as both leaf and parent+// โ Conflict'clientDB.solve': '่ชๅฉ่งฃๅณ','clientDB.solve.backup.title': 'ๆฐๆฎๅคไปฝ',-// โ Solution: Use different suffixes+// โ Solution'clientDB.solve.action': '่ชๅฉ่งฃๅณ','clientDB.solve.backup.title': 'ๆฐๆฎๅคไปฝ',```@@ -68,17 +60,16 @@ import { useTranslation } from 'react-i18next';const { t } = useTranslation('common');-// Basict('newFeature.title')-// With parameterst('alert.cloud.desc', { credit: '1000' })+// Multiple namespacesconst { t } = useTranslation(['common', 'chat']);t('common:save')```-## Available Namespaces--auth, authError, changelog, chat, color, **common**, components, discover, editor, electron, error, file, home, hotkey, image, knowledgeBase, labs, marketAuth, memory, metadata, migration, modelProvider, models, oauth, onboarding, plugin, portal, providers, ragEval, **setting**, subscription, thread, tool, topic, welcome+## Common Namespaces**Most used:** `common` (shared UI), `chat` (chat features), `setting` (settings)++Others: auth, changelog, components, discover, editor, electron, error, file, hotkey, knowledgeBase, memory, models, plugin, portal, providers, tool, topicdiff --git a/.agents/skills/linear/SKILL.md b/.agents/skills/linear/SKILL.mdnew file mode 100644index 00000000000..9350a30e0a5--- /dev/null+++ b/.agents/skills/linear/SKILL.md@@ -0,0 +1,51 @@+---+name: linear+description: Linear issue management guide. Use when working with Linear issues, creating issues, updating status, or adding comments. Triggers on Linear issue references (LOBE-xxx), issue tracking, or project management tasks. Requires Linear MCP tools to be available.+---++# Linear Issue Management++Before using Linear workflows, search for `linear` MCP tools. If not found, treat as not installed.++## Workflow++1. **Retrieve issue details** before starting: `mcp__linear-server__get_issue`+2. **Check for sub-issues**: Use `mcp__linear-server__list_issues` with `parentId` filter+3. **Update issue status** when completing: `mcp__linear-server__update_issue`+4. **Add completion comment** (REQUIRED): `mcp__linear-server__create_comment`++## Creating Issues++When creating issues with `mcp__linear-server__create_issue`, **MUST add the `claude code` label**.++## Completion Comment (REQUIRED)++Every completed issue MUST have a comment summarizing work done. This is critical for:+- Team visibility+- Code review context+- Future reference++## PR Association (REQUIRED)++When creating PRs for Linear issues, include magic keywords in PR body:+- `Fixes LOBE-123`+- `Closes LOBE-123`+- `Resolves LOBE-123`++## Per-Issue Completion Rule++When working on multiple issues, update EACH issue IMMEDIATELY after completing it:++1. Complete implementation+2. Run `bun run type-check`+3. Run related tests+4. Create PR if needed+5. Update status to **"In Review"** (NOT "Done")+6. Add completion comment+7. Move to next issue++**Note:** Status โ "In Review" when PR created. "Done" only after PR merged.++**โ Wrong:** Complete all โ Update all statuses โ Add all comments++**โ Correct:** Complete A โ Update A โ Comment A โ Complete B โ ...diff --git a/.agents/skills/microcopy/SKILL.md b/.agents/skills/microcopy/SKILL.mdnew file mode 100644index 00000000000..7f405bcbbef--- /dev/null+++ b/.agents/skills/microcopy/SKILL.md@@ -0,0 +1,83 @@+---+name: microcopy+description: UI copy and microcopy guidelines. Use when writing UI text, buttons, error messages, empty states, onboarding, or any user-facing copy. Triggers on i18n translation, UI text writing, or copy improvement tasks. Supports both Chinese and English.+---++# LobeHub UI Microcopy Guidelines++Brand: **Where Agents Collaborate** - Focus on collaborative agent system, not just "generation".++## Fixed Terminology++| Chinese | English |+|---------|---------|+| ็ฉบ้ด | Workspace |+| ๅฉ็ | Agent |+| ็พค็ป | Group |+| ไธไธๆ | Context |+| ่ฎฐๅฟ | Memory |+| ่ฟๆฅๅจ | Integration |+| ๆ่ฝ | Skill |+| ๅฉ็ๆกฃๆก | Agent Profile |+| ่ฏ้ข | Topic |+| ๆ็จฟ | Page |+| ็คพๅบ | Community |+| ่ตๆบ | Resource |+| ๅบ | Library |+| ๆจกๅๆๅกๅ | Provider |++## Brand Principles++1. **Create**: One sentence โ usable Agent; clear next step+2. **Collaborate**: Multi-agent; shared Context; controlled+3. **Evolve**: Remember with consent; explainable; replayable++## Writing Rules++1. **Clarity first**: Short sentences, strong verbs, minimal adjectives+2. **Layered**: Main line (simple) + optional detail (precise)+3. **Consistent verbs**: Create / Connect / Run / Pause / Retry / View details+4. **Actionable**: Every message tells next step; avoid generic "OK/Cancel"++## Human Warmth (Balanced)++Default: **80% information, 20% warmth**+Key moments: **70/30** (first-time, empty state, failures, long waits)++**Hard cap**: At most half sentence of warmth, followed by clear next step.++**Order**:+1. Acknowledge situation (no judgment)+2. Restore control (pause/replay/edit/undo/clear Memory)+3. Provide next action++**Avoid**: Preachy encouragement, grand narratives, over-anthropomorphizing++## Patterns++**Getting started**:+- "Starting with one sentence is enough. Describe your goal."+- "Not sure where to begin? Tell me the outcome."++**Long wait**:+- "Runningโฆ You can switch tasksโI'll notify you when done."+- "This may take a few minutes. To speed up: reduce Context / switch model."++**Failure**:+- "That didn't run through. Retry, or view details to fix."+- "Connection failed. Re-authorize in Settings, or try again later."++**Collaboration**:+- "Align everyone to the same Context."+- "Different opinions are fine. Write the goal first."++## Errors/Exceptions++Must include:+1. **What happened**+2. (Optional) **Why**+3. **What user can do next**++Provide: Retry / View details / Go to Settings / Contact support / Copy logs++Never blame user. Put error codes in "Details".diff --git a/.agents/skills/modal/SKILL.md b/.agents/skills/modal/SKILL.mdnew file mode 100644index 00000000000..ae9306f19c4--- /dev/null+++ b/.agents/skills/modal/SKILL.md@@ -0,0 +1,102 @@+---+name: modal+description: Modal imperative API guide. Use when creating modal dialogs using createModal from @lobehub/ui. Triggers on modal component implementation or dialog creation tasks.+user-invocable: false+---++# Modal Imperative API Guide++Use `createModal` from `@lobehub/ui` for imperative modal dialogs.++## Why Imperative?++| Mode | Characteristics | Recommended |+|------|-----------------|-------------|+| Declarative | Need `open` state, render `<Modal />` | โ |+| Imperative | Call function directly, no state | โ |++## File Structure++```+features/+โโโ MyFeatureModal/+ โโโ index.tsx # Export createXxxModal+ โโโ MyFeatureContent.tsx # Modal content+```++## Implementation++### 1. Content Component (`MyFeatureContent.tsx`)++```tsx+'use client';++import { useModalContext } from '@lobehub/ui';+import { useTranslation } from 'react-i18next';++export const MyFeatureContent = () => {+ const { t } = useTranslation('namespace');+ const { close } = useModalContext(); // Optional: get close method++ return <div>{/* Modal content */}</div>;+};+```++### 2. Export createModal (`index.tsx`)++```tsx+'use client';++import { createModal } from '@lobehub/ui';+import { t } from 'i18next'; // Note: use i18next, not react-i18next++import { MyFeatureContent } from './MyFeatureContent';++export const createMyFeatureModal = () =>+ createModal({+ allowFullscreen: true,+ children: <MyFeatureContent />,+ destroyOnHidden: false,+ footer: null,+ styles: { body: { overflow: 'hidden', padding: 0 } },+ title: t('myFeature.title', { ns: 'setting' }),+ width: 'min(80%, 800px)',+ });+```++### 3. Usage++```tsx+import { createMyFeatureModal } from '@/features/MyFeatureModal';++const handleOpen = useCallback(() => {+ createMyFeatureModal();+}, []);++return <Button onClick={handleOpen}>Open</Button>;+```++## i18n Handling++- **Content component**: `useTranslation` hook (React context)+- **createModal params**: `import { t } from 'i18next'` (non-hook, imperative)++## useModalContext Hook++```tsx+const { close, setCanDismissByClickOutside } = useModalContext();+```++## Common Config++| Property | Type | Description |+|----------|------|-------------|+| `allowFullscreen` | `boolean` | Allow fullscreen mode |+| `destroyOnHidden` | `boolean` | Destroy content on close |+| `footer` | `ReactNode \| null` | Footer content |+| `width` | `string \| number` | Modal width |++## Examples++- `src/features/SkillStore/index.tsx`+- `src/features/LibraryModal/CreateNew/index.tsx`diff --git a/.cursor/rules/project-structure.mdc b/.agents/skills/project-overview/SKILL.mdsimilarity index 54%rename from .cursor/rules/project-structure.mdcrename to .agents/skills/project-overview/SKILL.mdindex dd051d6890c..342b504f14f 100644--- a/.cursor/rules/project-structure.mdc+++ b/.agents/skills/project-overview/SKILL.md@@ -1,19 +1,50 @@----alwaysApply: true+name: project-overview+description: Complete project architecture and structure guide. Use when exploring the codebase, understanding project organization, finding files, or needing comprehensive architectural context. Triggers on architecture questions, directory navigation, or project overview needs.----# LobeChat Project Structure+# LobeChat Project Overview-## Complete Project Structure+## Project Description++Open-source, modern-design AI Agent Workspace: **LobeHub** (previously LobeChat).++**Supported platforms:**+- Web desktop/mobile+- Desktop (Electron)+- Mobile app (React Native) - coming soon++**Logo emoji:** ๐คฏ++## Complete Tech Stack-This project uses common monorepo structure. The workspace packages name use `@lobechat/` namespace.+| Category | Technology |+|----------|------------|+| Framework | Next.js 16 + React 19 |+| Routing | SPA inside Next.js with `react-router-dom` |+| Language | TypeScript |+| UI Components | `@lobehub/ui`, antd |+| CSS-in-JS | antd-style |+| Icons | lucide-react, `@ant-design/icons` |+| i18n | react-i18next |+| State | zustand |+| URL Params | nuqs |+| Data Fetching | SWR |+| React Hooks | aHooks |+| Date/Time | dayjs |+| Utilities | es-toolkit |+| API | TRPC (type-safe) |+| Database | Neon PostgreSQL + Drizzle ORM |+| Testing | Vitest |-**note**: some not very important files are not shown for simplicity.+## Complete Project Structure++Monorepo using `@lobechat/` namespace for workspace packages.-```plaintext+```lobe-chat/โโโ apps/-โ โโโ desktop/+โ โโโ desktop/ # Electron desktop appโโโ docs/โ โโโ changelog/โ โโโ development/@@ -23,10 +54,10 @@ lobe-chat/โ โโโ en-US/โ โโโ zh-CN/โโโ packages/-โ โโโ agent-runtime/+โ โโโ agent-runtime/ # Agent runtimeโ โโโ builtin-agents/-โ โโโ builtin-tool-*/ # builtin tool packages-โ โโโ business/ # cloud-only business logic packages+โ โโโ builtin-tool-*/ # Builtin tool packages+โ โโโ business/ # Cloud-only business logicโ โ โโโ config/โ โ โโโ const/โ โ โโโ model-runtime/@@ -59,8 +90,6 @@ lobe-chat/โ โโโ types/โ โโโ utils/โ โโโ web-crawler/-โโโ public/-โโโ scripts/โโโ src/โ โโโ app/โ โ โโโ (backend)/@@ -78,7 +107,7 @@ lobe-chat/โ โ โ โโโ onboarding/โ โ โ โโโ router/โ โ โโโ desktop/-โ โโโ business/ # cloud-only business logic (client/server)+โ โโโ business/ # Cloud-only (client/server)โ โ โโโ client/โ โ โโโ locales/โ โ โโโ server/@@ -117,33 +146,32 @@ lobe-chat/โ โโโ tools/โ โโโ types/โ โโโ utils/-โโโ package.json+โโโ e2e/ # E2E tests (Cucumber + Playwright)```## Architecture Map-- UI Components: `src/components`, `src/features`-- Global providers: `src/layout`-- Zustand stores: `src/store`-- Client Services: `src/services/`-- API Routers:- - `src/app/(backend)/webapi` (REST)- - `src/server/routers/{async|lambda|mobile|tools}` (tRPC)-- Server:- - Services (can access serverDB): `src/server/services`- - Modules (can't access db): `src/server/modules`- - Feature Flags: `src/server/featureFlags`- - Global Config: `src/server/globalConfig`-- Database:- - Schema (Drizzle): `packages/database/src/schemas`- - Model (CRUD): `packages/database/src/models`- - Repository (bff-queries): `packages/database/src/repositories`-- Third-party Integrations: `src/libs` โ analytics, oidc etc.-- Builtin Tools: `src/tools`, `packages/builtin-tool-*`-- Business (cloud-only): Code specific to LobeHub cloud service, only expose empty interfaces for opens-source version.- - `src/business/*`- - `packages/business/*`+| Layer | Location |+|-------|----------|+| UI Components | `src/components`, `src/features` |+| Global Providers | `src/layout` |+| Zustand Stores | `src/store` |+| Client Services | `src/services/` |+| REST API | `src/app/(backend)/webapi` |+| tRPC Routers | `src/server/routers/{async\|lambda\|mobile\|tools}` |+| Server Services | `src/server/services` (can access DB) |+| Server Modules | `src/server/modules` (no DB access) |+| Feature Flags | `src/server/featureFlags` |+| Global Config | `src/server/globalConfig` |+| DB Schema | `packages/database/src/schemas` |+| DB Model | `packages/database/src/models` |+| DB Repository | `packages/database/src/repositories` |+| Third-party | `src/libs` (analytics, oidc, etc.) |+| Builtin Tools | `src/tools`, `packages/builtin-tool-*` |+| Cloud-only | `src/business/*`, `packages/business/*` |-## Data Flow Architecture+## Data Flow-React UI โ Store Actions โ Client Service โ TRPC Lambda โ Server Services -> DB Model โ PostgreSQL (Remote)+```+React UI โ Store Actions โ Client Service โ TRPC Lambda โ Server Services โ DB Model โ PostgreSQL+```diff --git a/.agents/skills/react/SKILL.md b/.agents/skills/react/SKILL.mdnew file mode 100644index 00000000000..205b028b0fb--- /dev/null+++ b/.agents/skills/react/SKILL.md@@ -0,0 +1,73 @@+---+name: react+description: React component development guide. Use when working with React components (.tsx files), creating UI, using @lobehub/ui components, implementing routing, or building frontend features. Triggers on React component creation, modification, layout implementation, or navigation tasks.+---++# React Component Writing Guide++- Use antd-style for complex styles; for simple cases, use inline `style` attribute+- Use `Flexbox` and `Center` from `@lobehub/ui` for layouts (see `references/layout-kit.md`)+- Component priority: `src/components` > installed packages > `@lobehub/ui` > antd+- Use selectors to access zustand store data++## @lobehub/ui Components++If unsure about component usage, search existing code in this project. Most components extend antd with additional props.++Reference: `node_modules/@lobehub/ui/es/index.mjs` for all available components.++**Common Components:**+- General: ActionIcon, ActionIconGroup, Block, Button, Icon+- Data Display: Avatar, Collapse, Empty, Highlighter, Markdown, Tag, Tooltip+- Data Entry: CodeEditor, CopyButton, EditableText, Form, FormModal, Input, SearchBar, Select+- Feedback: Alert, Drawer, Modal+- Layout: Center, DraggablePanel, Flexbox, Grid, Header, MaskShadow+- Navigation: Burger, Dropdown, Menu, SideNav, Tabs++## Routing Architecture++Hybrid routing: Next.js App Router (static pages) + React Router DOM (main SPA).++| Route Type | Use Case | Implementation |+|------------|----------|----------------|+| Next.js App Router | Auth pages (login, signup, oauth) | `src/app/[variants]/(auth)/` |+| React Router DOM | Main SPA (chat, settings) | `desktopRouter.config.tsx` |++### Key Files+- Entry: `src/app/[variants]/page.tsx`+- Desktop router: `src/app/[variants]/router/desktopRouter.config.tsx`+- Mobile router: `src/app/[variants]/(mobile)/router/mobileRouter.config.tsx`+- Router utilities: `src/utils/router.tsx`++### Router Utilities++```tsx+import { dynamicElement, redirectElement, ErrorBoundary } from '@/utils/router';++element: dynamicElement(() => import('./chat'), 'Desktop > Chat');+element: redirectElement('/settings/profile');+errorElement: <ErrorBoundary resetPath="/chat" />;+```++### Navigation++**Important**: For SPA pages, use `Link` from `react-router-dom`, NOT `next/link`.++```tsx+// โ Wrong+import Link from 'next/link';+<Link href="/">Home</Link>++// โ Correct+import { Link } from 'react-router-dom';+<Link to="/">Home</Link>++// In components+import { useNavigate } from 'react-router-dom';+const navigate = useNavigate();+navigate('/chat');++// From stores+const navigate = useGlobalStore.getState().navigate;+navigate?.('/settings');+```diff --git a/.agents/skills/react/references/layout-kit.md b/.agents/skills/react/references/layout-kit.mdnew file mode 100644index 00000000000..ba1a14b494b--- /dev/null+++ b/.agents/skills/react/references/layout-kit.md@@ -0,0 +1,100 @@+# Flexbox Layout Components Guide++`@lobehub/ui` provides `Flexbox` and `Center` components for creating flexible layouts.++## Flexbox Component++Flexbox is the most commonly used layout component, similar to CSS `display: flex`.++### Basic Usage++```jsx+import { Flexbox } from '@lobehub/ui';++// Default vertical layout+<Flexbox>+ <div>Child 1</div>+ <div>Child 2</div>+</Flexbox>++// Horizontal layout+<Flexbox horizontal>+ <div>Left</div>+ <div>Right</div>+</Flexbox>+```++### Common Props++- `horizontal`: Boolean, set horizontal direction layout+- `flex`: Number or string, controls flex property+- `gap`: Number, spacing between children+- `align`: Alignment like 'center', 'flex-start', etc.+- `justify`: Main axis alignment like 'space-between', 'center', etc.+- `padding`: Padding value+- `paddingInline`: Horizontal padding+- `paddingBlock`: Vertical padding+- `width/height`: Set dimensions, typically '100%' or specific pixels+- `style`: Custom style object++### Layout Example++```jsx+// Classic three-column layout+<Flexbox horizontal height={'100%'} width={'100%'}>+ {/* Left sidebar */}+ <Flexbox+ width={260}+ style={{+ borderRight: `1px solid ${theme.colorBorderSecondary}`,+ height: '100%',+ overflowY: 'auto',+ }}+ >+ <SidebarContent />+ </Flexbox>++ {/* Center content */}+ <Flexbox flex={1} style={{ height: '100%' }}>+ <Flexbox flex={1} padding={24} style={{ overflowY: 'auto' }}>+ <MainContent />+ </Flexbox>++ {/* Footer */}+ <Flexbox+ style={{+ borderTop: `1px solid ${theme.colorBorderSecondary}`,+ padding: '16px 24px',+ }}+ >+ <Footer />+ </Flexbox>+ </Flexbox>+</Flexbox>+```++## Center Component++Center wraps Flexbox with horizontal and vertical centering.++```jsx+import { Center } from '@lobehub/ui';++<Center width={'100%'} height={'100%'}>+ <Content />+</Center>++// Icon centered+<Center className={styles.icon} flex={'none'} height={40} width={40}>+ <Icon icon={icon} size={24} />+</Center>+```++## Best Practices++- Use `flex={1}` to fill available space+- Use `gap` instead of margin for spacing+- Nest Flexbox for complex layouts+- Set `overflow: 'auto'` for scrollable content+- Use `horizontal` for horizontal layout (default is vertical)+- Combine with `useTheme` hook for theme-responsive layoutsdiff --git a/.agents/skills/recent-data/SKILL.md b/.agents/skills/recent-data/SKILL.mdnew file mode 100644index 00000000000..52524d02450--- /dev/null+++ b/.agents/skills/recent-data/SKILL.md@@ -0,0 +1,108 @@+---+name: recent-data+description: Guide for using Recent Data (topics, resources, pages). Use when working with recently accessed items, implementing recent lists, or accessing session store recent data. Triggers on recent data usage or implementation tasks.+user-invocable: false+---++# Recent Data Usage Guide++Recent data (recentTopics, recentResources, recentPages) is stored in session store.++## Initialization++In app top-level (e.g., `RecentHydration.tsx`):++```tsx+import { useInitRecentTopic } from '@/hooks/useInitRecentTopic';+import { useInitRecentResource } from '@/hooks/useInitRecentResource';+import { useInitRecentPage } from '@/hooks/useInitRecentPage';++const App = () => {+ useInitRecentTopic();+ useInitRecentResource();+ useInitRecentPage();+ return <YourComponents />;+};+```++## Usage++### Method 1: Read from Store (Recommended)++```tsx+import { useSessionStore } from '@/store/session';+import { recentSelectors } from '@/store/session/selectors';++const Component = () => {+ const recentTopics = useSessionStore(recentSelectors.recentTopics);+ const isInit = useSessionStore(recentSelectors.isRecentTopicsInit);++ if (!isInit) return <div>Loading...</div>;++ return (+ <div>+ {recentTopics.map((topic) => (+ <div key={topic.id}>{topic.title}</div>+ ))}+ </div>+ );+};+```++### Method 2: Use Hook Return (Single component)++```tsx+const { data: recentTopics, isLoading } = useInitRecentTopic();+```++## Available Selectors++### Recent Topics++```tsx+const recentTopics = useSessionStore(recentSelectors.recentTopics);+// Type: RecentTopic[]++const isInit = useSessionStore(recentSelectors.isRecentTopicsInit);+// Type: boolean+```++**RecentTopic type:**+```typescript+interface RecentTopic {+ agent: { avatar: string | null; backgroundColor: string | null; id: string; title: string | null } | null;+ id: string;+ title: string | null;+ updatedAt: Date;+}+```++### Recent Resources++```tsx+const recentResources = useSessionStore(recentSelectors.recentResources);+// Type: FileListItem[]++const isInit = useSessionStore(recentSelectors.isRecentResourcesInit);+```++### Recent Pages++```tsx+const recentPages = useSessionStore(recentSelectors.recentPages);+const isInit = useSessionStore(recentSelectors.isRecentPagesInit);+```++## Features++1. **Auto login detection**: Only loads when user is logged in+2. **Data caching**: Stored in store, no repeated loading+3. **Auto refresh**: SWR refreshes on focus (5-minute interval)+4. **Type safe**: Full TypeScript types++## Best Practices++1. Initialize all recent data at app top-level+2. Use selectors to read from store+3. For multi-component use, prefer Method 1+4. Use selectors for render optimizationdiff --git a/.agents/skills/testing/SKILL.md b/.agents/skills/testing/SKILL.mdnew file mode 100644index 00000000000..b7811c7ac83--- /dev/null+++ b/.agents/skills/testing/SKILL.md@@ -0,0 +1,89 @@+---+name: testing+description: Testing guide using Vitest. Use when writing tests (.test.ts, .test.tsx), fixing failing tests, improving test coverage, or debugging test issues. Triggers on test creation, test debugging, mock setup, or test-related questions.+---++# LobeChat Testing Guide++## Quick Reference++**Commands:**+```bash+# Run specific test file+bunx vitest run --silent='passed-only' '[file-path]'++# Database package (client)+cd packages/database && bunx vitest run --silent='passed-only' '[file]'++# Database package (server)+cd packages/database && TEST_SERVER_DB=1 bunx vitest run --silent='passed-only' '[file]'+```++**Never run** `bun run test` - it runs all 3000+ tests (~10 minutes).++## Test Categories++| Category | Location | Config |+|----------|----------|--------|+| Webapp | `src/**/*.test.ts(x)` | `vitest.config.ts` |+| Packages | `packages/*/**/*.test.ts` | `packages/*/vitest.config.ts` |+| Desktop | `apps/desktop/**/*.test.ts` | `apps/desktop/vitest.config.ts` |++## Core Principles++1. **Prefer `vi.spyOn` over `vi.mock`** - More targeted, easier to maintain+2. **Tests must pass type check** - Run `bun run type-check` after writing tests+3. **After 1-2 failed fix attempts, stop and ask for help**+4. **Test behavior, not implementation details**++## Basic Test Structure++```typescript+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++beforeEach(() => {+ vi.clearAllMocks();+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('ModuleName', () => {+ describe('functionName', () => {+ it('should handle normal case', () => {+ // Arrange โ Act โ Assert+ });+ });+});+```++## Mock Patterns++```typescript+// โ Spy on direct dependencies+vi.spyOn(messageService, 'createMessage').mockResolvedValue('id');++// โ Use vi.stubGlobal for browser APIs+vi.stubGlobal('Image', mockImage);+vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock');++// โ Avoid mocking entire modules globally+vi.mock('@/services/chat'); // Too broad+```++## Detailed Guides++See `references/` for specific testing scenarios:+- **Database Model testing**: `references/db-model-test.md`+- **Electron IPC testing**: `references/electron-ipc-test.md`+- **Zustand Store Action testing**: `references/zustand-store-action-test.md`+- **Agent Runtime E2E testing**: `references/agent-runtime-e2e.md`+- **Desktop Controller testing**: `references/desktop-controller-test.md`++## Common Issues++1. **Module pollution**: Use `vi.resetModules()` when tests fail mysteriously+2. **Mock not working**: Check setup position and use `vi.clearAllMocks()` in beforeEach+3. **Test data pollution**: Clean database state in beforeEach/afterEach+4. **Async issues**: Wrap state changes in `act()` for React hooksdiff --git a/.agents/skills/testing/references/agent-runtime-e2e.md b/.agents/skills/testing/references/agent-runtime-e2e.mdnew file mode 100644index 00000000000..0b79a82d81d--- /dev/null+++ b/.agents/skills/testing/references/agent-runtime-e2e.md@@ -0,0 +1,126 @@+# Agent Runtime E2E Testing Guide++## Core Principles++### Minimal Mock Principle++Only mock **three external dependencies**:++| Dependency | Mock | Description |+|------------|------|-------------|+| Database | PGLite | In-memory database from `@lobechat/database/test-utils` |+| Redis | InMemoryAgentStateManager | Memory implementation |+| Redis | InMemoryStreamEventManager | Memory implementation |++**NOT mocked:**+- `model-bank` - Uses real model config+- `Mecha` (AgentToolsEngine, ContextEngineering)+- `AgentRuntimeService`+- `AgentRuntimeCoordinator`++### Use vi.spyOn, not vi.mock++Different tests need different LLM responses. `vi.spyOn` provides:+- Flexible return values per test+- Easy testing of different scenarios+- Better test isolation++### Default Model: gpt-5++- Always available in `model-bank`+- Stable across model updates++## Technical Implementation++### Database Setup++```typescript+import { LobeChatDatabase } from '@lobechat/database';+import { getTestDB } from '@lobechat/database/test-utils';++let testDB: LobeChatDatabase;++beforeEach(async () => {+ testDB = await getTestDB();+});+```++### OpenAI Stream Response Helper++```typescript+export const createOpenAIStreamResponse = (options: {+ content?: string;+ toolCalls?: Array<{ id: string; name: string; arguments: string }>;+ finishReason?: 'stop' | 'tool_calls';+}) => {+ const { content, toolCalls, finishReason = 'stop' } = options;++ return new Response(+ new ReadableStream({+ start(controller) {+ const encoder = new TextEncoder();++ if (content) {+ const chunk = {+ id: 'chatcmpl-mock',+ object: 'chat.completion.chunk',+ model: 'gpt-5',+ choices: [{ index: 0, delta: { content }, finish_reason: null }],+ };+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));+ }++ // ... tool_calls handling+ // ... finish chunk+ controller.enqueue(encoder.encode('data: [DONE]\n\n'));+ controller.close();+ },+ }),+ { headers: { 'content-type': 'text/event-stream' } }+ );+};+```++### State Management++```typescript+import { InMemoryAgentStateManager, InMemoryStreamEventManager } from '@/server/modules/AgentRuntime';++const stateManager = new InMemoryAgentStateManager();+const streamEventManager = new InMemoryStreamEventManager();++const service = new AgentRuntimeService(serverDB, userId, {+ coordinatorOptions: { stateManager, streamEventManager },+ queueService: null,+ streamEventManager,+});+```++### Mock OpenAI API++```typescript+const fetchSpy = vi.spyOn(globalThis, 'fetch');++it('should handle text response', async () => {+ fetchSpy.mockResolvedValueOnce(createOpenAIStreamResponse({ content: 'Response text' }));+ // ... execute test+});++it('should handle tool calls', async () => {+ fetchSpy.mockResolvedValueOnce(createOpenAIStreamResponse({+ toolCalls: [{+ id: 'call_123',+ name: 'lobe-web-browsing____search____builtin',+ arguments: JSON.stringify({ query: 'weather' }),+ }],+ finishReason: 'tool_calls',+ }));+ // ... execute test+});+```++## Notes++1. **Test isolation**: Clean `InMemoryAgentStateManager` and `InMemoryStreamEventManager` after each test+2. **Timeout**: E2E tests may need longer timeouts+3. **Debug**: Use `DEBUG=lobe-server:*` for detailed logsdiff --git a/.agents/skills/testing/references/db-model-test.md b/.agents/skills/testing/references/db-model-test.mdnew file mode 100644index 00000000000..8a66347decb--- /dev/null+++ b/.agents/skills/testing/references/db-model-test.md@@ -0,0 +1,124 @@+# Database Model Testing Guide++Test `packages/database` Model layer.++## Dual Environment Verification (Required)++```bash+# 1. Client environment (fast)+cd packages/database && TEST_SERVER_DB=0 bunx vitest run --silent='passed-only' '[file]'++# 2. Server environment (compatibility)+cd packages/database && TEST_SERVER_DB=1 bunx vitest run --silent='passed-only' '[file]'+```++## User Permission Check - Security First ๐++**Critical security requirement**: All user data operations must include permission checks.++```typescript+// โ DANGEROUS: Missing permission check+update = async (id: string, data: Partial<MyModel>) => {+ return this.db.update(myTable).set(data)+ .where(eq(myTable.id, id)) // Only checks ID+ .returning();+};++// โ SECURE: Permission check included+update = async (id: string, data: Partial<MyModel>) => {+ return this.db.update(myTable).set(data)+ .where(and(+ eq(myTable.id, id),+ eq(myTable.userId, this.userId) // โ Permission check+ ))+ .returning();+};+```++## Test File Structure++```typescript+// @vitest-environment node+describe('MyModel', () => {+ describe('create', () => { /* ... */ });+ describe('queryAll', () => { /* ... */ });+ describe('update', () => {+ it('should update own records');+ it('should NOT update other users records'); // ๐ Security+ });+ describe('delete', () => {+ it('should delete own records');+ it('should NOT delete other users records'); // ๐ Security+ });+ describe('user isolation', () => {+ it('should enforce user data isolation'); // ๐ Core security+ });+});+```++## Security Test Example++```typescript+it('should not update records of other users', async () => {+ const [otherUserRecord] = await serverDB+ .insert(myTable)+ .values({ userId: 'other-user', data: 'original' })+ .returning();++ const result = await myModel.update(otherUserRecord.id, { data: 'hacked' });++ expect(result).toBeUndefined();+ const unchanged = await serverDB.query.myTable.findFirst({+ where: eq(myTable.id, otherUserRecord.id),+ });+ expect(unchanged?.data).toBe('original');+});+```++## Data Management++```typescript+const userId = 'test-user';+const otherUserId = 'other-user';++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(async () => {+ await serverDB.delete(users);+});+```++## Foreign Key Handling++```typescript+// โ Wrong: Invalid foreign key+const testData = { asyncTaskId: 'invalid-uuid', fileId: 'non-existent' };++// โ Correct: Use null+const testData = { asyncTaskId: null, fileId: null };++// โ Or: Create referenced record first+beforeEach(async () => {+ const [asyncTask] = await serverDB.insert(asyncTasks)+ .values({ id: 'valid-id', status: 'pending' }).returning();+ testData.asyncTaskId = asyncTask.id;+});+```++## Predictable Sorting++```typescript+// โ Use explicit timestamps+const oldDate = new Date('2024-01-01T10:00:00Z');+const newDate = new Date('2024-01-02T10:00:00Z');+await serverDB.insert(table).values([+ { ...data1, createdAt: oldDate },+ { ...data2, createdAt: newDate },+]);++// โ Don't rely on insert order+await serverDB.insert(table).values([data1, data2]); // Unpredictable+```diff --git a/.agents/skills/testing/references/desktop-controller-test.md b/.agents/skills/testing/references/desktop-controller-test.mdnew file mode 100644index 00000000000..ababab47f8c--- /dev/null+++ b/.agents/skills/testing/references/desktop-controller-test.md@@ -0,0 +1,124 @@+# Desktop Controller Unit Testing Guide++## Testing Framework & Directory Structure++LobeChat Desktop uses Vitest as the test framework. Controller unit tests should be placed in the `__tests__` directory adjacent to the controller file, named with the original controller filename plus `.test.ts`.++```plaintext+apps/desktop/src/main/controllers/+โโโ __tests__/+โ โโโ index.test.ts+โ โโโ MenuCtr.test.ts+โ โโโ ...+โโโ McpCtr.ts+โโโ MenuCtr.ts+โโโ ...+```++## Basic Test File Structure++```typescript+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import YourController from '../YourControllerName';++// Mock dependencies+vi.mock('dependency-module', () => ({+ dependencyFunction: vi.fn(),+}));++// Mock App instance+const mockApp = {+ // Mock necessary App properties and methods as needed+} as unknown as App;++describe('YourController', () => {+ let controller: YourController;++ beforeEach(() => {+ vi.clearAllMocks();+ controller = new YourController(mockApp);+ });++ describe('methodName', () => {+ it('test scenario description', async () => {+ // Prepare test data++ // Execute method under test+ const result = await controller.methodName(params);++ // Verify results+ expect(result).toMatchObject(expectedResult);+ });+ });+});+```++## Mocking External Dependencies++### Module Functions++```typescript+const mockFunction = vi.fn();++vi.mock('module-name', () => ({+ functionName: mockFunction,+}));+```++### Node.js Core Modules++Example: mocking `child_process.exec` and `util.promisify`:++```typescript+const mockExecImpl = vi.fn();++vi.mock('child_process', () => ({+ exec: vi.fn((cmd, callback) => {+ return mockExecImpl(cmd, callback);+ }),+}));++vi.mock('util', () => ({+ promisify: vi.fn((fn) => {+ return async (cmd: string) => {+ return new Promise((resolve, reject) => {+ mockExecImpl(cmd, (error: Error | null, result: any) => {+ if (error) reject(error);+ else resolve(result);+ });+ });+ };+ }),+}));+```++## Best Practices++1. **Isolate tests**: Use `beforeEach` to reset mocks and state+2. **Comprehensive coverage**: Test normal flows, edge cases, and error handling+3. **Clear naming**: Test names should describe content and expected results+4. **Avoid implementation details**: Test behavior, not implementation+5. **Mock external dependencies**: Use `vi.mock()` for all external dependencies++## Example: Testing IPC Event Handler++```typescript+it('should handle IPC event correctly', async () => {+ mockSomething.mockReturnValue({ result: 'success' });++ const result = await controller.ipcMethodName({+ param1: 'value1',+ param2: 'value2',+ });++ expect(result).toEqual({+ success: true,+ data: { result: 'success' },+ });++ expect(mockSomething).toHaveBeenCalledWith('value1', 'value2');+});+```diff --git a/.agents/skills/testing/references/electron-ipc-test.md b/.agents/skills/testing/references/electron-ipc-test.mdnew file mode 100644index 00000000000..e8ac9fa9c20--- /dev/null+++ b/.agents/skills/testing/references/electron-ipc-test.md@@ -0,0 +1,63 @@+# Electron IPC Testing Strategy++For Electron IPC tests, use **Mock return values** instead of real Electron environment.++## Basic Mock Setup++```typescript+import { vi } from 'vitest';+import { electronIpcClient } from '@/server/modules/ElectronIPCClient';++vi.mock('@/server/modules/ElectronIPCClient', () => ({+ electronIpcClient: {+ getFilePathById: vi.fn(),+ deleteFiles: vi.fn(),+ },+}));+```++## Setting Mock Behavior++```typescript+beforeEach(() => {+ vi.resetAllMocks();+ vi.mocked(electronIpcClient.getFilePathById).mockResolvedValue('/path/to/file.txt');+ vi.mocked(electronIpcClient.deleteFiles).mockResolvedValue({ success: true });+});+```++## Testing Different Scenarios++```typescript+it('should handle successful file deletion', async () => {+ vi.mocked(electronIpcClient.deleteFiles).mockResolvedValue({ success: true });++ const result = await service.deleteFiles(['desktop://file1.txt']);++ expect(electronIpcClient.deleteFiles).toHaveBeenCalledWith(['desktop://file1.txt']);+ expect(result.success).toBe(true);+});++it('should handle file deletion failure', async () => {+ vi.mocked(electronIpcClient.deleteFiles).mockRejectedValue(new Error('Delete failed'));++ const result = await service.deleteFiles(['desktop://file1.txt']);++ expect(result.success).toBe(false);+ expect(result.errors).toBeDefined();+});+```++## Advantages++1. **Environment simplification**: No complex Electron setup+2. **Controlled testing**: Precise control over IPC return values+3. **Scenario coverage**: Easy to test success/failure cases+4. **Speed**: Mock calls are faster than real IPC++## Notes++- Ensure mock behavior matches real IPC interface+- Use `vi.mocked()` for type safety+- Reset mocks in `beforeEach` to avoid test interference+- Verify both return values and that IPC methods were called correctlydiff --git a/.agents/skills/testing/references/zustand-store-action-test.md b/.agents/skills/testing/references/zustand-store-action-test.mdnew file mode 100644index 00000000000..6f0c22197a5--- /dev/null+++ b/.agents/skills/testing/references/zustand-store-action-test.md@@ -0,0 +1,150 @@+# Zustand Store Action Testing Guide++## Basic Structure++```typescript+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { useChatStore } from '../../store';++vi.mock('zustand/traditional');++beforeEach(() => {+ vi.clearAllMocks();+ useChatStore.setState({+ activeId: 'test-session-id',+ messagesMap: {},+ loadingIds: [],+ }, false);++ vi.spyOn(messageService, 'createMessage').mockResolvedValue('new-message-id');++ act(() => {+ useChatStore.setState({+ refreshMessages: vi.fn(),+ internal_coreProcessMessage: vi.fn(),+ });+ });+});++afterEach(() => {+ vi.restoreAllMocks();+});+```++## Key Principles++### 1. Spy Direct Dependencies Only++```typescript+// โ Good: Spy on direct dependency+const fetchAIChatSpy = vi.spyOn(result.current, 'internal_fetchAIChatMessage')+ .mockResolvedValue({ isFunctionCall: false, content: 'AI response' });++// โ Bad: Spy on lower-level implementation+const streamSpy = vi.spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(...);+```++### 2. Minimize Global Spies++```typescript+// โ Spy only when needed+it('should process message', async () => {+ const streamSpy = vi.spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(...);+ // test logic+ streamSpy.mockRestore();+});++// โ Don't setup all spies globally+beforeEach(() => {+ vi.spyOn(chatService, 'createAssistantMessageStream').mockResolvedValue({});+ vi.spyOn(fileService, 'uploadFile').mockResolvedValue({});+});+```++### 3. Use act() for Async Operations++```typescript+it('should send message', async () => {+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ await result.current.sendMessage({ message: 'Hello' });+ });++ expect(messageService.createMessage).toHaveBeenCalled();+});+```++### 4. Test Organization++```typescript+describe('sendMessage', () => {+ describe('validation', () => {+ it('should not send when session is inactive');+ it('should not send when message is empty');+ });+ describe('message creation', () => {+ it('should create user message and trigger AI processing');+ });+ describe('error handling', () => {+ it('should handle message creation errors gracefully');+ });+});+```++## Streaming Response Mock++```typescript+it('should handle streaming chunks', async () => {+ const { result } = renderHook(() => useChatStore());++ const streamSpy = vi.spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onMessageHandle, onFinish }) => {+ await onMessageHandle?.({ type: 'text', text: 'Hello' } as any);+ await onMessageHandle?.({ type: 'text', text: ' World' } as any);+ await onFinish?.('Hello World', {});+ });++ await act(async () => {+ await result.current.internal_fetchAIChatMessage({...});+ });++ streamSpy.mockRestore();+});+```++## SWR Hook Testing++```typescript+it('should fetch data', async () => {+ const mockData = [{ id: '1', name: 'Item 1' }];+ vi.spyOn(discoverService, 'getPluginCategories').mockResolvedValue(mockData);++ const { result } = renderHook(() => useStore.getState().usePluginCategories(params));++ await waitFor(() => {+ expect(result.current.data).toEqual(mockData);+ });+});+```++**Key points for SWR:**+- DO NOT mock useSWR - let it use real implementation+- Only mock service methods (fetchers)+- Use `waitFor` for async operations++## Anti-Patterns++```typescript+// โ Don't mock entire store+vi.mock('../../store', () => ({ useChatStore: vi.fn(() => ({...})) }));++// โ Don't test internal state structure+expect(result.current.messagesMap).toHaveProperty('test-session');++// โ Test behavior instead+expect(result.current.refreshMessages).toHaveBeenCalled();+```diff --git a/.agents/skills/typescript/SKILL.md b/.agents/skills/typescript/SKILL.mdnew file mode 100644index 00000000000..094de1d6e10--- /dev/null+++ b/.agents/skills/typescript/SKILL.md@@ -0,0 +1,52 @@+---+name: typescript+description: TypeScript code style and optimization guidelines. Use when writing TypeScript code (.ts, .tsx, .mts files), reviewing code quality, or implementing type-safe patterns. Triggers on TypeScript development, type safety questions, or code style discussions.+---++# TypeScript Code Style Guide++## Types and Type Safety++- Avoid explicit type annotations when TypeScript can infer+- Avoid implicitly `any`; explicitly type when necessary+- Use accurate types: prefer `Record<PropertyKey, unknown>` over `object` or `any`+- Prefer `interface` for object shapes (e.g., React props); use `type` for unions/intersections+- Prefer `as const satisfies XyzInterface` over plain `as const`+- Prefer `@ts-expect-error` over `@ts-ignore` over `as any`+- Avoid meaningless null/undefined parameters; design strict function contracts++## Async Patterns++- Prefer `async`/`await` over callbacks or `.then()` chains+- Prefer async APIs over sync ones (avoid `*Sync`)+- Use promise-based variants: `import { readFile } from 'fs/promises'`+- Use `Promise.all`, `Promise.race` for concurrent operations where safe++## Code Structure++- Prefer object destructuring+- Use consistent, descriptive naming; avoid obscure abbreviations+- Replace magic numbers/strings with well-named constants+- Defer formatting to tooling++## UI and Theming++- Use `@lobehub/ui`, Ant Design components instead of raw HTML tags+- Design for dark mode and mobile responsiveness+- Use `antd-style` token system instead of hard-coded colors++## Performance++- Prefer `forโฆof` loops over index-based `for` loops+- Reuse existing utils in `packages/utils` or installed npm packages+- Query only required columns from database++## Time Consistency++- Assign `Date.now()` to a constant once and reuse for consistency++## Logging++- Never log user private information (API keys, etc.)+- Don't use `import { log } from 'debug'` directly (logs to console)+- Use `console.error` in catch blocks instead of debug packagediff --git a/.agents/vercel-react-best-practices/AGENTS.md b/.agents/skills/vercel-react-best-practices/AGENTS.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/AGENTS.mdrename to .agents/skills/vercel-react-best-practices/AGENTS.mddiff --git a/.agents/vercel-react-best-practices/SKILL.md b/.agents/skills/vercel-react-best-practices/SKILL.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/SKILL.mdrename to .agents/skills/vercel-react-best-practices/SKILL.mddiff --git a/.agents/vercel-react-best-practices/rules/advanced-event-handler-refs.md b/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/advanced-event-handler-refs.mdrename to .agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.mddiff --git a/.agents/vercel-react-best-practices/rules/advanced-use-latest.md b/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/advanced-use-latest.mdrename to .agents/skills/vercel-react-best-practices/rules/advanced-use-latest.mddiff --git a/.agents/vercel-react-best-practices/rules/async-api-routes.md b/.agents/skills/vercel-react-best-practices/rules/async-api-routes.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/async-api-routes.mdrename to .agents/skills/vercel-react-best-practices/rules/async-api-routes.mddiff --git a/.agents/vercel-react-best-practices/rules/async-defer-await.md b/.agents/skills/vercel-react-best-practices/rules/async-defer-await.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/async-defer-await.mdrename to .agents/skills/vercel-react-best-practices/rules/async-defer-await.mddiff --git a/.agents/vercel-react-best-practices/rules/async-dependencies.md b/.agents/skills/vercel-react-best-practices/rules/async-dependencies.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/async-dependencies.mdrename to .agents/skills/vercel-react-best-practices/rules/async-dependencies.mddiff --git a/.agents/vercel-react-best-practices/rules/async-parallel.md b/.agents/skills/vercel-react-best-practices/rules/async-parallel.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/async-parallel.mdrename to .agents/skills/vercel-react-best-practices/rules/async-parallel.mddiff --git a/.agents/vercel-react-best-practices/rules/async-suspense-boundaries.md b/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/async-suspense-boundaries.mdrename to .agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.mddiff --git a/.agents/vercel-react-best-practices/rules/bundle-barrel-imports.md b/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/bundle-barrel-imports.mdrename to .agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.mddiff --git a/.agents/vercel-react-best-practices/rules/bundle-conditional.md b/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/bundle-conditional.mdrename to .agents/skills/vercel-react-best-practices/rules/bundle-conditional.mddiff --git a/.agents/vercel-react-best-practices/rules/bundle-defer-third-party.md b/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/bundle-defer-third-party.mdrename to .agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.mddiff --git a/.agents/vercel-react-best-practices/rules/bundle-dynamic-imports.md b/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/bundle-dynamic-imports.mdrename to .agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.mddiff --git a/.agents/vercel-react-best-practices/rules/bundle-preload.md b/.agents/skills/vercel-react-best-practices/rules/bundle-preload.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/bundle-preload.mdrename to .agents/skills/vercel-react-best-practices/rules/bundle-preload.mddiff --git a/.agents/vercel-react-best-practices/rules/client-event-listeners.md b/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/client-event-listeners.mdrename to .agents/skills/vercel-react-best-practices/rules/client-event-listeners.mddiff --git a/.agents/vercel-react-best-practices/rules/client-localstorage-schema.md b/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/client-localstorage-schema.mdrename to .agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.mddiff --git a/.agents/vercel-react-best-practices/rules/client-passive-event-listeners.md b/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/client-passive-event-listeners.mdrename to .agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.mddiff --git a/.agents/vercel-react-best-practices/rules/client-swr-dedup.md b/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/client-swr-dedup.mdrename to .agents/skills/vercel-react-best-practices/rules/client-swr-dedup.mddiff --git a/.agents/vercel-react-best-practices/rules/js-batch-dom-css.md b/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/js-batch-dom-css.mdrename to .agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.mddiff --git a/.agents/vercel-react-best-practices/rules/js-cache-function-results.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/js-cache-function-results.mdrename to .agents/skills/vercel-react-best-practices/rules/js-cache-function-results.mddiff --git a/.agents/vercel-react-best-practices/rules/js-cache-property-access.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/js-cache-property-access.mdrename to .agents/skills/vercel-react-best-practices/rules/js-cache-property-access.mddiff --git a/.agents/vercel-react-best-practices/rules/js-cache-storage.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/js-cache-storage.mdrename to .agents/skills/vercel-react-best-practices/rules/js-cache-storage.mddiff --git a/.agents/vercel-react-best-practices/rules/js-combine-iterations.md b/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/js-combine-iterations.mdrename to .agents/skills/vercel-react-best-practices/rules/js-combine-iterations.mddiff --git a/.agents/vercel-react-best-practices/rules/js-early-exit.md b/.agents/skills/vercel-react-best-practices/rules/js-early-exit.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/js-early-exit.mdrename to .agents/skills/vercel-react-best-practices/rules/js-early-exit.mddiff --git a/.agents/vercel-react-best-practices/rules/js-hoist-regexp.md b/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/js-hoist-regexp.mdrename to .agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.mddiff --git a/.agents/vercel-react-best-practices/rules/js-index-maps.md b/.agents/skills/vercel-react-best-practices/rules/js-index-maps.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/js-index-maps.mdrename to .agents/skills/vercel-react-best-practices/rules/js-index-maps.mddiff --git a/.agents/vercel-react-best-practices/rules/js-length-check-first.md b/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/js-length-check-first.mdrename to .agents/skills/vercel-react-best-practices/rules/js-length-check-first.mddiff --git a/.agents/vercel-react-best-practices/rules/js-min-max-loop.md b/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/js-min-max-loop.mdrename to .agents/skills/vercel-react-best-practices/rules/js-min-max-loop.mddiff --git a/.agents/vercel-react-best-practices/rules/js-set-map-lookups.md b/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/js-set-map-lookups.mdrename to .agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.mddiff --git a/.agents/vercel-react-best-practices/rules/js-tosorted-immutable.md b/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/js-tosorted-immutable.mdrename to .agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.mddiff --git a/.agents/vercel-react-best-practices/rules/rendering-activity.md b/.agents/skills/vercel-react-best-practices/rules/rendering-activity.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rendering-activity.mdrename to .agents/skills/vercel-react-best-practices/rules/rendering-activity.mddiff --git a/.agents/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md b/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.mdrename to .agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.mddiff --git a/.agents/vercel-react-best-practices/rules/rendering-conditional-render.md b/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rendering-conditional-render.mdrename to .agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.mddiff --git a/.agents/vercel-react-best-practices/rules/rendering-content-visibility.md b/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rendering-content-visibility.mdrename to .agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.mddiff --git a/.agents/vercel-react-best-practices/rules/rendering-hoist-jsx.md b/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rendering-hoist-jsx.mdrename to .agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.mddiff --git a/.agents/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rendering-hydration-no-flicker.mdrename to .agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.mddiff --git a/.agents/vercel-react-best-practices/rules/rendering-svg-precision.md b/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rendering-svg-precision.mdrename to .agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.mddiff --git a/.agents/vercel-react-best-practices/rules/rerender-defer-reads.md b/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rerender-defer-reads.mdrename to .agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.mddiff --git a/.agents/vercel-react-best-practices/rules/rerender-dependencies.md b/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rerender-dependencies.mdrename to .agents/skills/vercel-react-best-practices/rules/rerender-dependencies.mddiff --git a/.agents/vercel-react-best-practices/rules/rerender-derived-state.md b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rerender-derived-state.mdrename to .agents/skills/vercel-react-best-practices/rules/rerender-derived-state.mddiff --git a/.agents/vercel-react-best-practices/rules/rerender-functional-setstate.md b/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rerender-functional-setstate.mdrename to .agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.mddiff --git a/.agents/vercel-react-best-practices/rules/rerender-lazy-state-init.md b/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rerender-lazy-state-init.mdrename to .agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.mddiff --git a/.agents/vercel-react-best-practices/rules/rerender-memo.md b/.agents/skills/vercel-react-best-practices/rules/rerender-memo.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rerender-memo.mdrename to .agents/skills/vercel-react-best-practices/rules/rerender-memo.mddiff --git a/.agents/vercel-react-best-practices/rules/rerender-transitions.md b/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/rerender-transitions.mdrename to .agents/skills/vercel-react-best-practices/rules/rerender-transitions.mddiff --git a/.agents/vercel-react-best-practices/rules/server-after-nonblocking.md b/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/server-after-nonblocking.mdrename to .agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.mddiff --git a/.agents/vercel-react-best-practices/rules/server-cache-lru.md b/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/server-cache-lru.mdrename to .agents/skills/vercel-react-best-practices/rules/server-cache-lru.mddiff --git a/.agents/vercel-react-best-practices/rules/server-cache-react.md b/.agents/skills/vercel-react-best-practices/rules/server-cache-react.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/server-cache-react.mdrename to .agents/skills/vercel-react-best-practices/rules/server-cache-react.mddiff --git a/.agents/vercel-react-best-practices/rules/server-parallel-fetching.md b/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/server-parallel-fetching.mdrename to .agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.mddiff --git a/.agents/vercel-react-best-practices/rules/server-serialization.md b/.agents/skills/vercel-react-best-practices/rules/server-serialization.mdsimilarity index 100%rename from .agents/vercel-react-best-practices/rules/server-serialization.mdrename to .agents/skills/vercel-react-best-practices/rules/server-serialization.mddiff --git a/.agents/skills/zustand/SKILL.md b/.agents/skills/zustand/SKILL.mdnew file mode 100644index 00000000000..1bfc31d65d3--- /dev/null+++ b/.agents/skills/zustand/SKILL.md@@ -0,0 +1,78 @@+---+name: zustand+description: Zustand state management guide. Use when working with store code (src/store/**), implementing actions, managing state, or creating slices. Triggers on Zustand store development, state management questions, or action implementation.+---++# LobeChat Zustand State Management++## Action Type Hierarchy++### 1. Public Actions+Main interfaces for UI components:+- Naming: Verb form (`createTopic`, `sendMessage`)+- Responsibilities: Parameter validation, flow orchestration++### 2. Internal Actions (`internal_*`)+Core business logic implementation:+- Naming: `internal_` prefix (`internal_createTopic`)+- Responsibilities: Optimistic updates, service calls, error handling+- Should not be called directly by UI++### 3. Dispatch Methods (`internal_dispatch*`)+State update handlers:+- Naming: `internal_dispatch` + entity (`internal_dispatchTopic`)+- Responsibilities: Calling reducers, updating store++## When to Use Reducer vs Simple `set`++**Use Reducer Pattern:**+- Managing object lists/maps (`messagesMap`, `topicMaps`)+- Optimistic updates+- Complex state transitions++**Use Simple `set`:**+- Toggling booleans+- Updating simple values+- Setting single state fields++## Optimistic Update Pattern++```typescript+internal_createTopic: async (params) => {+ const tmpId = Date.now().toString();++ // 1. Immediately update frontend (optimistic)+ get().internal_dispatchTopic(+ { type: 'addTopic', value: { ...params, id: tmpId } },+ 'internal_createTopic'+ );++ // 2. Call backend service+ const topicId = await topicService.createTopic(params);++ // 3. Refresh for consistency+ await get().refreshTopic();+ return topicId;+},+```++**Delete operations**: Don't use optimistic updates (destructive, complex recovery)++## Naming Conventions++**Actions:**+- Public: `createTopic`, `sendMessage`+- Internal: `internal_createTopic`, `internal_updateMessageContent`+- Dispatch: `internal_dispatchTopic`+- Toggle: `internal_toggleMessageLoading`++**State:**+- ID arrays: `messageLoadingIds`, `topicEditingIds`+- Maps: `topicMaps`, `messagesMap`+- Active: `activeTopicId`+- Init flags: `topicsInit`++## Detailed Guides++- Action patterns: `references/action-patterns.md`+- Slice organization: `references/slice-organization.md`diff --git a/.agents/skills/zustand/references/action-patterns.md b/.agents/skills/zustand/references/action-patterns.mdnew file mode 100644index 00000000000..de6c1391411--- /dev/null+++ b/.agents/skills/zustand/references/action-patterns.md@@ -0,0 +1,125 @@+# Zustand Action Patterns++## Optimistic Update Implementation++### Standard Flow++```typescript+internal_updateMessageContent: async (id, content, extra) => {+ const { internal_dispatchMessage, refreshMessages } = get();++ // 1. Immediately update frontend+ internal_dispatchMessage({+ id,+ type: 'updateMessage',+ value: { content },+ });++ // 2. Call backend+ await messageService.updateMessage(id, { content });++ // 3. Refresh for consistency+ await refreshMessages();+},+```++### Create Operations++```typescript+internal_createMessage: async (message, context) => {+ let tempId = context?.tempMessageId;+ if (!tempId) {+ tempId = internal_createTmpMessage(message);+ internal_toggleMessageLoading(true, tempId);+ }++ try {+ const id = await messageService.createMessage(message);+ await refreshMessages();+ internal_toggleMessageLoading(false, tempId);+ return id;+ } catch (e) {+ internal_toggleMessageLoading(false, tempId);+ internal_dispatchMessage({+ id: tempId,+ type: 'updateMessage',+ value: { error: { type: ChatErrorType.CreateMessageError } },+ });+ }+},+```++### Delete Operations (No Optimistic Update)++```typescript+internal_removeGenerationTopic: async (id: string) => {+ get().internal_updateGenerationTopicLoading(id, true);++ try {+ await generationTopicService.deleteTopic(id);+ await get().refreshGenerationTopics();+ } finally {+ get().internal_updateGenerationTopicLoading(id, false);+ }+},+```++## Loading State Management++```typescript+// Define in initialState.ts+export interface ChatMessageState {+ messageEditingIds: string[];+}++// Manage in action+toggleMessageEditing: (id, editing) => {+ set(+ { messageEditingIds: toggleBooleanList(get().messageEditingIds, id, editing) },+ false,+ 'toggleMessageEditing'+ );+}+```++## SWR Integration++```typescript+useFetchMessages: (enable, sessionId, activeTopicId) =>+ useClientDataSWR<ChatMessage[]>(+ enable ? [SWR_USE_FETCH_MESSAGES, sessionId, activeTopicId] : null,+ async ([, sessionId, topicId]) => messageService.getMessages(sessionId, topicId),+ {+ onSuccess: (messages) => {+ const nextMap = { ...get().messagesMap, [messageMapKey(sessionId, activeTopicId)]: messages };+ if (get().messagesInit && isEqual(nextMap, get().messagesMap)) return;+ set({ messagesInit: true, messagesMap: nextMap }, false, n('useFetchMessages'));+ },+ }+ ),++// Cache invalidation+refreshMessages: async () => {+ await mutate([SWR_USE_FETCH_MESSAGES, get().activeId, get().activeTopicId]);+};+```++## Reducer Pattern++```typescript+export const messagesReducer = (state: ChatMessage[], payload: MessageDispatch): ChatMessage[] => {+ switch (payload.type) {+ case 'updateMessage': {+ return produce(state, (draftState) => {+ const index = draftState.findIndex((i) => i.id === payload.id);+ if (index < 0) return;+ draftState[index] = merge(draftState[index], {+ ...payload.value,+ updatedAt: Date.now(),+ });+ });+ }+ // ...other cases+ }+};+```diff --git a/.agents/skills/zustand/references/slice-organization.md b/.agents/skills/zustand/references/slice-organization.mdnew file mode 100644index 00000000000..a837340e669--- /dev/null+++ b/.agents/skills/zustand/references/slice-organization.md@@ -0,0 +1,125 @@+# Zustand Slice Organization++## Top-Level Store Structure++Key aggregation files:+- `src/store/chat/initialState.ts`: Aggregate all slice initial states+- `src/store/chat/store.ts`: Define top-level `ChatStore`, combine all slice actions+- `src/store/chat/selectors.ts`: Export all slice selectors+- `src/store/chat/helpers.ts`: Chat helper functions++## Store Aggregation Pattern++```typescript+// src/store/chat/initialState.ts+import { ChatTopicState, initialTopicState } from './slices/topic/initialState';+import { ChatMessageState, initialMessageState } from './slices/message/initialState';++export type ChatStoreState = ChatTopicState & ChatMessageState & ...++export const initialState: ChatStoreState = {+ ...initialMessageState,+ ...initialTopicState,+ ...+};++// src/store/chat/store.ts+export interface ChatStoreAction+ extends ChatMessageAction, ChatTopicAction, ...++const createStore: StateCreator<ChatStore, [['zustand/devtools', never]]> = (...params) => ({+ ...initialState,+ ...chatMessage(...params),+ ...chatTopic(...params),+});++export const useChatStore = createWithEqualityFn<ChatStore>()(+ subscribeWithSelector(devtools(createStore)),+ shallow+);+```++## Single Slice Structure++```plaintext+src/store/chat/slices/+โโโ [sliceName]/+ โโโ action.ts # Define actions (or actions/ directory)+ โโโ initialState.ts # State structure and initial values+ โโโ reducer.ts # (Optional) Reducer pattern+ โโโ selectors.ts # Define selectors+ โโโ index.ts # (Optional) Re-exports+```++### initialState.ts++```typescript+export interface ChatTopicState {+ activeTopicId?: string;+ topicMaps: Record<string, ChatTopic[]>;+ topicsInit: boolean;+ topicLoadingIds: string[];+}++export const initialTopicState: ChatTopicState = {+ activeTopicId: undefined,+ topicMaps: {},+ topicsInit: false,+ topicLoadingIds: [],+};+```++### selectors.ts++```typescript+const currentTopics = (s: ChatStoreState): ChatTopic[] | undefined => s.topicMaps[s.activeId];++const getTopicById = (id: string) => (s: ChatStoreState): ChatTopic | undefined =>+ currentTopics(s)?.find((topic) => topic.id === id);++// Core pattern: Use xxxSelectors aggregate+export const topicSelectors = {+ currentTopics,+ getTopicById,+};+```++## Complex Actions Sub-directory++```plaintext+src/store/chat/slices/aiChat/+โโโ actions/+โ โโโ generateAIChat.ts+โ โโโ rag.ts+โ โโโ memory.ts+โ โโโ index.ts+โโโ initialState.ts+โโโ selectors.ts+```++## State Design Patterns++### Map Structure for Associated Data+```typescript+topicMaps: Record<string, ChatTopic[]>;+messagesMap: Record<string, ChatMessage[]>;+```++### Arrays for Loading State+```typescript+messageLoadingIds: string[]+topicLoadingIds: string[]+```++### Optional Fields for Active Items+```typescript+activeId: string+activeTopicId?: string+```++## Best Practices++1. **Slice division**: By functional domain (message, topic, aiChat)+2. **File naming**: camelCase for directories, consistent patterns+3. **State structure**: Flat, avoid deep nesting+4. **Type safety**: Clear TypeScript interfaces for each slicediff --git a/.codex/skills b/.codex/skillsindex 7bcb9556370..2b7a412b8fa 120000--- a/.codex/skills+++ b/.codex/skills@@ -1 +1 @@-../.agents\ No newline at end of file+../.agents/skills\ No newline at end of filediff --git a/.cursor/rules/add-provider-doc.mdc b/.cursor/rules/add-provider-doc.mdcdeleted file mode 100644index b6af7fa16ae..00000000000--- a/.cursor/rules/add-provider-doc.mdc+++ /dev/null@@ -1,183 +0,0 @@-----description: Complete guide for adding a new AI provider documentation to LobeChat-alwaysApply: false------# Adding New AI Provider Documentation--This document provides a step-by-step guide for adding documentation for a new AI provider to LobeChat, based on the complete workflow used for adding providers like BFL (Black Forest Labs) and FAL.--## Overview--Adding a new provider requires creating both user-facing documentation and technical configuration files. The process involves:--1. Creating usage documentation (EN + CN)-2. Adding environment variable documentation (EN + CN)-3. Updating Docker configuration files-4. Updating .env.example file-5. Preparing image resources--## Step 1: Create Provider Usage Documentation--Create user-facing documentation that explains how to use the new provider.--### Required Files--Create both English and Chinese versions:-- `docs/usage/providers/{provider-name}.mdx` (English)-- `docs/usage/providers/{provider-name}.zh-CN.mdx` (Chinese)--### Documentation Structure--Follow the structure and format used in existing provider documentation. For reference, see:-- `docs/usage/providers/fal.mdx` (English template)-- `docs/usage/providers/fal.zh-CN.mdx` (Chinese template)--### Key Requirements--- **Images**: Prepare 5-6 screenshots showing the process-- **Cover Image**: Create or obtain a cover image for the provider-- **Accurate URLs**: Use real registration and dashboard URLs-- **Service Type**: Specify whether it's for image generation, text generation, etc.-- **Pricing Warning**: Include pricing information callout--### Important Notes--- **๐ API Key Security**: Never include real API keys in documentation. Always use placeholder format (e.g., `bfl-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`)-- **๐ผ๏ธ Image Hosting**: Use LobeHub's CDN for all images: `hub-apac-1.lobeobjects.space`--## Step 2: Update Environment Variables Documentation--Add the new provider's environment variables to the self-hosting documentation.--### Files to Update--- `docs/self-hosting/environment-variables/model-provider.mdx` (English)-- `docs/self-hosting/environment-variables/model-provider.zh-CN.mdx` (Chinese)--### Content to Add--Add two sections for each provider:--```markdown-### `{PROVIDER}_API_KEY`--- Type: Required-- Description: This is the API key you applied for in the {Provider Name} service.-- Default: --- Example: `{api-key-format-example}`--### `{PROVIDER}_MODEL_LIST`--- Type: Optional-- Description: Used to control the {Provider Name} model list. Use `+` to add a model, `-` to hide a model, and `model_name=display_name` to customize the display name of a model. Separate multiple entries with commas. The definition syntax follows the same rules as other providers' model lists.-- Default: `-`-- Example: `-all,+{model-id-1},+{model-id-2}={display-name}`--The above example disables all models first, then enables `{model-id-1}` and `{model-id-2}` (displayed as `{display-name}`).--[model-list]: /docs/self-hosting/advanced/model-list-```--### Important Notes--- **API Key Format**: Use proper UUID format for examples (e.g., `12345678-1234-1234-1234-123456789abc`)-- **Real Model IDs**: Use actual model IDs from the codebase, not placeholders-- **Consistent Naming**: Follow the pattern `{PROVIDER}_API_KEY` and `{PROVIDER}_MODEL_LIST`--## Step 3: Update Docker Configuration Files--Add environment variables to all Docker configuration files to ensure the provider works in containerized deployments.--### Files to Update--All Dockerfile variants must be updated:-- `Dockerfile`-- `Dockerfile.database`-- `Dockerfile.pglite`--### Changes Required--Add the new provider's environment variables at the **end** of the ENV section, just before the final line:--```dockerfile-# Previous providers...- # 302.AI- AI302_API_KEY="" AI302_MODEL_LIST="" \- # {New Provider 1}- {PROVIDER1}_API_KEY="" {PROVIDER1}_MODEL_LIST="" \- # {New Provider 2}- {PROVIDER2}_API_KEY="" {PROVIDER2}_MODEL_LIST=""-```--### Important Rules--- **Position**: Add new providers at the **end** of the list-- **Ordering**: When adding multiple providers, use alphabetical order (e.g., FAL before BFL)-- **Consistency**: Maintain identical ordering across all Dockerfile variants-- **Format**: Follow the pattern `{PROVIDER}_API_KEY="" {PROVIDER}_MODEL_LIST="" \`--## Step 4: Update .env.example File--Add example configuration entries to help users understand how to configure the provider locally.--### File to Update--- `.env.example`--### Content to Add--Add new sections before the "Market Service" section:--```bash-### {Provider Name} ###--# {PROVIDER}_API_KEY={provider-prefix}-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-```--### Format Guidelines--- **Section Header**: Use `### {Provider Name} ###` format-- **Commented Example**: Use `#` to comment out the example-- **Key Format**: Use appropriate prefix for the provider (e.g., `bfl-`, `fal-`, `sk-`)-- **Position**: Add before the Market Service section-- **Spacing**: Maintain consistent spacing with existing entries--## Step 5: Image Resources--Prepare all necessary image resources for the documentation.--### Required Images--1. **Cover Image**: Provider logo or branded image-2. **API Dashboard Screenshots**: 3-4 screenshots showing API key creation process-3. **LobeChat Configuration Screenshots**: 2-3 screenshots showing provider setup in LobeChat--### Image Guidelines--- **Quality**: Use high-resolution screenshots-- **Consistency**: Maintain consistent styling across all screenshots-- **Privacy**: Remove or blur any sensitive information-- **Format**: Use PNG format for screenshots-- **Hosting**: Use LobeHub's CDN (`hub-apac-1.lobeobjects.space`) for all images--## Checklist--Before submitting your provider documentation:--- [ ] Created both English and Chinese usage documentation-- [ ] Added environment variable documentation (EN + CN)-- [ ] Updated all 3 Dockerfile variants with consistent ordering-- [ ] Updated .env.example with proper key format-- [ ] Prepared all required screenshots and images-- [ ] Used actual model IDs from the codebase-- [ ] Verified no real API keys are included in documentation-- [ ] Used LobeHub CDN for all image hosting-- [ ] Tested the documentation for clarity and accuracy--## Reference--This guide was created based on the implementation of BFL (Black Forest Labs) provider documentation. For a complete example, refer to:-- Commits: `d2da03e1a` (documentation) and `6a2e95868` (environment variables)-- Files: `docs/usage/providers/bfl.mdx`, `docs/usage/providers/bfl.zh-CN.mdx`-- PR: Current branch `tj/feat/bfl-docs`\ No newline at end of filediff --git a/.cursor/rules/add-setting-env.mdc b/.cursor/rules/add-setting-env.mdcdeleted file mode 100644index 0dfa59a6def..00000000000--- a/.cursor/rules/add-setting-env.mdc+++ /dev/null@@ -1,175 +0,0 @@-----description: Guide for adding environment variables to configure user settings-alwaysApply: false------# Adding Environment Variable for User Settings--Add server-side environment variables to configure default values for user settings.--**Priority**: User Custom > Server Env Var > Hardcoded Default--## Steps--### 1. Define Environment Variable--Create `src/envs/<domain>.ts`:--```typescript-import { createEnv } from '@t3-oss/env-nextjs';-import { z } from 'zod';--export const get<Domain>Config = () => {- return createEnv({- server: {- YOUR_ENV_VAR: z.coerce.number().min(MIN).max(MAX).optional(),- },- runtimeEnv: {- YOUR_ENV_VAR: process.env.YOUR_ENV_VAR,- },- });-};--export const <domain>Env = get<Domain>Config();-```--### 2. Update Type (Optional)--**Skip this step if the domain field already exists in `GlobalServerConfig`.**--Add to `packages/types/src/serverConfig.ts`:--```typescript-export interface GlobalServerConfig {- <domain>?: {- <settingName>?: <type>;- };-}-```--**Prefer reusing existing types** from `packages/types/src/user/settings` with `PartialDeep`:--```typescript-import { User<Domain>Config } from './user/settings';--export interface GlobalServerConfig {- <domain>?: PartialDeep<User<Domain>Config>;-}-```--### 3. Assemble Server Config (Optional)--**Skip this step if the domain field already exists in server config.**--In `src/server/globalConfig/index.ts`:--```typescript-import { <domain>Env } from '@/envs/<domain>';-import { cleanObject } from '@/utils/object';--export const getServerGlobalConfig = async () => {- const config: GlobalServerConfig = {- // ...- <domain>: cleanObject({- <settingName>: <domain>Env.YOUR_ENV_VAR,- }),- };- return config;-};-```--If the domain already exists, just add the new field to the existing `cleanObject()`:--```typescript-<domain>: cleanObject({- existingField: <domain>Env.EXISTING_VAR,- <settingName>: <domain>Env.YOUR_ENV_VAR, // Add this line-}),-```--### 4. Merge to User Store (Optional)--**Skip this step if the domain field already exists in `serverSettings`.**--In `src/store/user/slices/common/action.ts`, add to `serverSettings`:--```typescript-const serverSettings: PartialDeep<UserSettings> = {- defaultAgent: serverConfig.defaultAgent,- <domain>: serverConfig.<domain>, // Add this line- // ...-};-```--### 5. Update .env.example--```bash-# <Description> (range/options, default: X)-# YOUR_ENV_VAR=<example>-```--### 6. Update Documentation--Update both English and Chinese documentation:-- `docs/self-hosting/environment-variables/basic.mdx`-- `docs/self-hosting/environment-variables/basic.zh-CN.mdx`--Add new section or subsection with environment variable details (type, description, default, example, range/constraints).--## Type Reuse--**Prefer reusing existing types** from `packages/types/src/user/settings` instead of defining inline types in `serverConfig.ts`.--```typescript-// โ Good - reuse existing type-import { UserImageConfig } from './user/settings';--export interface GlobalServerConfig {- image?: PartialDeep<UserImageConfig>;-}--// โ Bad - inline type definition-export interface GlobalServerConfig {- image?: {- defaultImageNum?: number;- };-}-```--## Example: AI_IMAGE_DEFAULT_IMAGE_NUM--```typescript-// src/envs/image.ts-export const getImageConfig = () => {- return createEnv({- server: {- AI_IMAGE_DEFAULT_IMAGE_NUM: z.coerce.number().min(1).max(20).optional(),- },- runtimeEnv: {- AI_IMAGE_DEFAULT_IMAGE_NUM: process.env.AI_IMAGE_DEFAULT_IMAGE_NUM,- },- });-};--// packages/types/src/serverConfig.ts-import { UserImageConfig } from './user/settings';--export interface GlobalServerConfig {- image?: PartialDeep<UserImageConfig>;-}--// src/server/globalConfig/index.ts-image: cleanObject({- defaultImageNum: imageEnv.AI_IMAGE_DEFAULT_IMAGE_NUM,-}),--// src/store/user/slices/common/action.ts-const serverSettings: PartialDeep<UserSettings> = {- image: serverConfig.image,- // ...-};--// .env.example-# AI_IMAGE_DEFAULT_IMAGE_NUM=4-```-diff --git a/.cursor/rules/cursor-rules.mdc b/.cursor/rules/cursor-rules.mdcdeleted file mode 100644index f69add3cdd1..00000000000--- a/.cursor/rules/cursor-rules.mdc+++ /dev/null@@ -1,28 +0,0 @@-----description: cursor rules writing and optimization guide-globs:-alwaysApply: false-----ๅฝไฝ ็ผๅๆไฟฎๆน Cursor Rule ๆถ๏ผ่ฏท้ตๅพชไปฅไธๅๅ๏ผ--- ๅฝไฝ ็ฅ้ rule ็ๆไปถๅๆถ๏ผไฝฟ็จ `read_file` ่ไธๆฏ `fetch_rules` ๅป่ฏปๅๅฎไปฌ๏ผๅฎไปฌ้ฝๅจ้กน็ฎๆ น็ฎๅฝ็ `.cursor/rules/` ๆไปถๅคนไธ--- ไปฃ็ ็คบไพ- - ็คบไพๅบๅฐฝ้็ฒพ็ฎ๏ผไป ไฟ็ๆผ็คบๆ ธๅฟ- - ๅ ้คไธ็คบไพๆ ๅ ณ็ๅฏผๅ ฅ/ๅฏผๅบ่ฏญๅฅ๏ผไฝไฟ็ๅฟ ่ฆ็ๅฏผๅ ฅ- - ๅไธๆไปถๅญๅจๅคไธช็คบไพๆถ๏ผ่ฅๅๆๅทฒๆผ็คบๆจกๅๅฏผๅ ฅ๏ผๅ็ปญ็คบไพๅฏ็็ฅ้ๅคๅฏผๅ ฅ- - ๆ ้ไนฆๅ `export`- - ๅฏ็็ฅไธๆผ็คบๆ ๅ ณๆ้ๅค็ propsใ้ ็ฝฎๅฏน่ฑกๅฑๆงใtry/catchใCSS ็ญไปฃ็ - - ๅ ้คๆ ๅ ณๆณจ้๏ผไฟ็ๆๅฉ็่งฃ็ๆณจ้--- ๆ ผๅผ- - ไฟฎๆนๅ่ฏทๅ ็กฎ่ฎคๅๅงๆๆกฃ่ฏญ่จ๏ผๅนถไฟๆไธ่ด- - ๆ ๅบๅ่กจ็ปไธไฝฟ็จ `-`- - ๅ่กจๆซๅฐพ็ๅฅๅทๆฏๅคไฝ็- - ้ๅฟ ่ฆไธไฝฟ็จๅ ็ฒใ่กๅ ไปฃ็ ็ญๆ ทๅผ๏ผRule ไธป่ฆไพ LLM ้ ่ฏป- - ้ฟๅ ไธญ่ฑๆ้ๅฅๅฏน็ งใ่ฅๆฌๅทๅ ๅฎนไธบ็คบไพ่้็ฟป่ฏ๏ผๅฏไฟ็--- Review- - ไฟฎๆญฃ Markdown ่ฏญๆณ้ฎ้ข- - ็บ ๆญฃ้ๅซๅญ- - ๆๅบ็คบไพไธ่ฏดๆไธไธ่ดไนๅคdiff --git a/.cursor/rules/db-migrations.mdc b/.cursor/rules/db-migrations.mdcdeleted file mode 100644index 1639c95d819..00000000000--- a/.cursor/rules/db-migrations.mdc+++ /dev/null@@ -1,46 +0,0 @@-----globs: packages/database/migrations/**/*-alwaysApply: false------# Database Migrations Guide--## Step1: Generate migrations--```bash-bun run db:generate-```--this step will generate following files:--- packages/database/migrations/0046_meaningless_file_name.sql-- packages/database/migrations/0046_meaningless_file_name.sql--and update the following files:--- packages/database/migrations/meta/\_journal.json-- packages/database/src/core/migrations.json-- docs/development/database-schema.dbml--## Step2: optimize the migration sql fileName--the migration sql file name is randomly generated, we need to optimize the file name to make it more readable and meaningful. For example, `0046_meaningless_file_name.sql` -> `0046_user_add_avatar_column.sql`--## Step3: Defensive Programming - Use Idempotent Clauses--Always use defensive clauses to make migrations idempotent:--```sql--- โ Good: Idempotent operations-ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "avatar" text;-DROP TABLE IF EXISTS "old_table";-CREATE INDEX IF NOT EXISTS "users_email_idx" ON "users" ("email");-ALTER TABLE "posts" DROP COLUMN IF EXISTS "deprecated_field";---- โ Bad: Non-idempotent operations-ALTER TABLE "users" ADD COLUMN "avatar" text;-DROP TABLE "old_table";-CREATE INDEX "users_email_idx" ON "users" ("email");-```--**Important**: After modifying migration SQL (e.g., adding `IF NOT EXISTS` clauses), run `bun run db:generate:client` to update the hash in `packages/database/src/core/migrations.json`.diff --git a/.cursor/rules/debug-usage.mdc b/.cursor/rules/debug-usage.mdcdeleted file mode 100644index 644ebd4f7a5..00000000000--- a/.cursor/rules/debug-usage.mdc+++ /dev/null@@ -1,86 +0,0 @@-----description: ๅ ๅซๆทปๅ console.log ๆฅๅฟ่ฏทๆฑๆถ-globs:-alwaysApply: false------# Debug ๅ ไฝฟ็จๆๅ--ๆฌ้กน็ฎไฝฟ็จ `debug` ๅ ่ฟ่ก่ฐ่ฏๆฅๅฟ่ฎฐๅฝใไฝฟ็จๆญค่งๅๆฅ็กฎไฟๅข้ๆๅ็ปไธ่ฐ่ฏๆฅๅฟๆ ผๅผใ--## ๅบๆฌ็จๆณ--1. ๅฏผๅ ฅ debug ๅ ๏ผ--```typescript-import debug from 'debug';-```--1. ๅๅปบไธไธชๅฝๅ็ฉบ้ด็ๆฅๅฟ่ฎฐๅฝๅจ๏ผ--```typescript-// ๆ ผๅผ: lobe:[ๆจกๅ]:[ๅญๆจกๅ]-const log = debug('lobe-[ๆจกๅๅ]:[ๅญๆจกๅๅ]');-```--1. ไฝฟ็จๆฅๅฟ่ฎฐๅฝๅจ๏ผ--```typescript-log('็ฎๅๆถๆฏ');-log('ๅธฆๅ้็ๆถๆฏ: %O', object);-log('ๆ ผๅผๅๆฐๅญ: %d', number);-```--## ๅฝๅ็ฉบ้ด็บฆๅฎ--- ๆก้ขๅบ็จ็ธๅ ณ: `lobe-desktop:[ๆจกๅ]`-- ๆๅก็ซฏ็ธๅ ณ: `lobe-server:[ๆจกๅ]`-- ๅฎขๆท็ซฏ็ธๅ ณ: `lobe-client:[ๆจกๅ]`-- ่ทฏ็ฑ็ธๅ ณ: `lobe-[็ฑปๅ]-router:[ๆจกๅ]`--## ๆ ผๅผ่ฏดๆ็ฌฆ--- `%O` - ๅฏน่ฑกๅฑๅผ๏ผๆจ่็จไบๅคๆๅฏน่ฑก๏ผ-- `%o` - ๅฏน่ฑก-- `%s` - ๅญ็ฌฆไธฒ-- `%d` - ๆฐๅญ--## ็คบไพ--ๆฅ็ `src/server/routers/edge/market/index.ts` ไธญ็ไฝฟ็จ็คบไพ๏ผ--```typescript-import debug from 'debug';--const log = debug('lobe-edge-router:market');--log('getAgent input: %O', input);-```--## ๅฏ็จ่ฐ่ฏ--่ฆๅจๅผๅๆถๅฏ็จ่ฐ่ฏ่พๅบ๏ผ้่ฎพ็ฝฎ็ฏๅขๅ้๏ผ--### ๅจๆต่งๅจไธญ--ๅจๆงๅถๅฐๆง่ก๏ผ--```javascript-localStorage.debug = 'lobe-*';-```--### ๅจ Node.js ็ฏๅขไธญ--```bash-DEBUG=lobe-* npm run dev-# ๆ่-DEBUG=lobe-* pnpm dev-```--### ๅจ Electron ๅบ็จไธญ--ๅฏไปฅๅจไธป่ฟ็จๅๆธฒๆ่ฟ็จๅฏๅจๅ่ฎพ็ฝฎ็ฏๅขๅ้๏ผ--```typescript-process.env.DEBUG = 'lobe-*';-```diff --git a/.cursor/rules/desktop-controller-tests.mdc b/.cursor/rules/desktop-controller-tests.mdcdeleted file mode 100644index f4c4f08ed86..00000000000--- a/.cursor/rules/desktop-controller-tests.mdc+++ /dev/null@@ -1,189 +0,0 @@-----description: ๆก้ข็ซฏๆต่ฏ-globs:-alwaysApply: false------# ๆก้ข็ซฏๆงๅถๅจๅๅ ๆต่ฏๆๅ--## ๆต่ฏๆกๆถไธ็ฎๅฝ็ปๆ--LobeChat ๆก้ข็ซฏไฝฟ็จ Vitest ไฝไธบๆต่ฏๆกๆถใๆงๅถๅจ็ๅๅ ๆต่ฏๅบๆพ็ฝฎๅจๅฏนๅบๆงๅถๅจๆไปถๅ็บง็ `__tests__` ็ฎๅฝไธ๏ผๅนถไปฅๅๆงๅถๅจๆไปถๅๅ `.test.ts` ไฝไธบๆไปถๅใ--```plaintext-apps/desktop/src/main/controllers/-โโโ __tests__/-โ โโโ index.test.ts-โ โโโ MenuCtr.test.ts-โ โโโ ...-โโโ McpCtr.ts-โโโ MenuCtr.ts-โโโ ...-```--## ๆต่ฏๆไปถๅบๆฌ็ปๆ--```typescript-import { beforeEach, describe, expect, it, vi } from 'vitest';--import type { App } from '@/core/App';--import YourController from '../YourControllerName';--// ๆจกๆไพ่ต-vi.mock('ไพ่ตๆจกๅ', () => ({- ไพ่ตๅฝๆฐ: vi.fn(),-}));--// ๆจกๆ App ๅฎไพ-const mockApp = {- // ๆ้ๆจกๆๅฟ ่ฆ็ App ๅฑๆงๅๆนๆณ-} as unknown as App;--describe('YourController', () => {- let controller: YourController;-- beforeEach(() => {- vi.clearAllMocks();- controller = new YourController(mockApp);- });-- describe('ๆนๆณๅ', () => {- it('ๆต่ฏๅบๆฏๆ่ฟฐ', async () => {- // ๅๅคๆต่ฏๆฐๆฎ-- // ๆง่ก่ขซๆตๆนๆณ- const result = await controller.ๆนๆณๅ(ๅๆฐ);-- // ้ช่ฏ็ปๆ- expect(result).toMatchObject(้ขๆ็ปๆ);- });- });-});-```--## ๆจกๆๅค้จไพ่ต--### ๆจกๆๆจกๅๅฝๆฐ--```typescript-const mockFunction = vi.fn();--vi.mock('module-name', () => ({- functionName: mockFunction,-}));-```--### ๆจกๆ Node.js ๆ ธๅฟๆจกๅ--ไพๅฆๆจกๆ `child_process.exec` ๅ `util.promisify`:--```typescript-// ๅญๅจๆจกๆ็ exec ๅฎ็ฐ-const mockExecImpl = vi.fn();--// ๆจกๆ child_process.exec-vi.mock('child_process', () => ({- exec: vi.fn((cmd, callback) => {- return mockExecImpl(cmd, callback);- }),-}));--// ๆจกๆ util.promisify-vi.mock('util', () => ({- promisify: vi.fn((fn) => {- return async (cmd: string) => {- return new Promise((resolve, reject) => {- mockExecImpl(cmd, (error: Error | null, result: any) => {- if (error) reject(error);- else resolve(result);- });- });- };- }),-}));-```--## ็ผๅๆๆ็ๆต่ฏ็จไพ--### ๆต่ฏๅ็ฑป--ๅฐๆต่ฏ็จไพๅไธบไธๅ็ฑปๅซ๏ผๆฏไธช็ฑปๅซๆต่ฏไธไธช็นๅฎๅบๆฏ๏ผ--```typescript-// ๆๅๅบๆฏ-it('ๅบ่ฏฅๆๅๅฎๆๆไฝ', async () => {});--// ่พน็ๆกไปถ-it('ๅบ่ฏฅๅค็่พน็ๆ ๅต', async () => {});--// ้่ฏฏๅค็-it('ๅบ่ฏฅไผ้ ๅฐๅค็้่ฏฏ', async () => {});-```--### ่ฎพ็ฝฎๆต่ฏๆฐๆฎ--```typescript-// ๆจกๆ่ฟๅๅผ-mockExecImpl.mockImplementation((cmd: string, callback: any) => {- if (cmd === 'ๅฝไปค') {- callback(null, { stdout: 'ๆๅ่พๅบ' });- } else {- callback(new Error('้่ฏฏไฟกๆฏ'), null);- }-});-```--### ๆญ่จ--ไฝฟ็จ Vitest ็ๆญ่จๅฝๆฐ้ช่ฏ็ปๆ๏ผ--```typescript-// ๆฃๆฅๅบๆฌๅผ-expect(result.success).toBe(true);--// ๆฃๆฅๅฏน่ฑก้จๅๅน้ -expect(result.data).toMatchObject({- key: 'value',-});--// ๆฃๆฅๆฐ็ป-expect(result.items).toHaveLength(2);-expect(result.items[0].name).toBe('expectedName');--// ๆฃๆฅๅฝๆฐ่ฐ็จ-expect(mockFunction).toHaveBeenCalledWith(expectedArgs);-expect(mockFunction).toHaveBeenCalledTimes(1);-```--## ๆไฝณๅฎ่ทต--1. **้็ฆปๆต่ฏ**๏ผ็กฎไฟๆฏไธชๆต่ฏไบไธๅฝฑๅ๏ผไฝฟ็จ `beforeEach` ้็ฝฎๆจกๆๅ็ถๆ-2. **ๅ จ้ข่ฆ็**๏ผๆต่ฏๆญฃๅธธๆต็จใ่พน็ๆกไปถๅ้่ฏฏๅค็-3. **ๆธ ๆฐๅฝๅ**๏ผๆต่ฏๅ็งฐๅบๆธ ๆฐๆ่ฟฐๆต่ฏๅ ๅฎนๅ้ขๆ็ปๆ-4. **้ฟๅ ๆต่ฏๅฎ็ฐ็ป่**๏ผๆต่ฏๅบ่ฏฅๅ ณๆณจ่กไธบ่้ๅฎ็ฐ็ป่๏ผไฝฟไปฃ็ ้ๆไธไผ็ ดๅๆต่ฏ-5. **ๆจกๆๅค้จไพ่ต**๏ผไฝฟ็จ `vi.mock()` ๆจกๆๆๆๅค้จไพ่ต๏ผๅๅฐๆต่ฏ็ไธ็กฎๅฎๆง--## ็คบไพ๏ผๆต่ฏ IPC ไบไปถๅค็ๆนๆณ--```typescript-it('ๅบ่ฏฅๆญฃ็กฎๅค็ IPC ไบไปถ', async () => {- // ๆจกๆไพ่ต- mockSomething.mockReturnValue({ result: 'success' });-- // ่ฐ็จ IPC ๆนๆณ- const result = await controller.ipcMethodName({- param1: 'value1',- param2: 'value2',- });-- // ้ช่ฏ็ปๆ- expect(result).toEqual({- success: true,- data: { result: 'success' },- });-- // ้ช่ฏไพ่ต่ฐ็จ- expect(mockSomething).toHaveBeenCalledWith('value1', 'value2');-});-```diff --git a/.cursor/rules/desktop-feature-implementation.mdc b/.cursor/rules/desktop-feature-implementation.mdcdeleted file mode 100644index 04c796e9243..00000000000--- a/.cursor/rules/desktop-feature-implementation.mdc+++ /dev/null@@ -1,155 +0,0 @@-----description: ๅฝ่ฆๅ electron ็ธๅ ณๅทฅไฝๆถ-globs:-alwaysApply: false------# ๆก้ข็ซฏๆฐๅ่ฝๅฎ็ฐๆๅ--## ๆก้ข็ซฏๅบ็จๆถๆๆฆ่ฟฐ--LobeChat ๆก้ข็ซฏๅบไบ Electron ๆกๆถๆๅปบ๏ผ้็จไธป่ฟ็จ-ๆธฒๆ่ฟ็จๆถๆ๏ผ--1. **ไธป่ฟ็จ (Main Process)**๏ผ- - ไฝ็ฝฎ๏ผ`apps/desktop/src/main`- - ่่ดฃ๏ผๆงๅถๅบ็จ็ๅฝๅจๆใ็ณป็ปAPIไบคไบใ็ชๅฃ็ฎก็ใๅๅฐๆๅก--2. **ๆธฒๆ่ฟ็จ (Renderer Process)**๏ผ- - ๅค็จ Web ็ซฏไปฃ็ ๏ผไฝไบ `src` ็ฎๅฝ- - ้่ฟ IPC ไธไธป่ฟ็จ้ไฟก--3. **้ขๅ ่ฝฝ่ๆฌ (Preload)**๏ผ- - ไฝ็ฝฎ๏ผ`apps/desktop/src/preload`- - ่่ดฃ๏ผๅฎๅ จๅฐๆด้ฒไธป่ฟ็จๅ่ฝ็ปๆธฒๆ่ฟ็จ--## ๆทปๅ ๆฐๆก้ข็ซฏๅ่ฝๆต็จ--### 1. ็กฎๅฎๅ่ฝ้ๆฑไธ่ฎพ่ฎก--้ฆๅ ็กฎๅฎๆฐๅ่ฝ็้ๆฑๅ่ฎพ่ฎก๏ผๅ ๆฌ๏ผ--- ๅ่ฝๆ่ฟฐๅ็จไพ-- ๆฏๅฆ้่ฆ็ณป็ป็บงAPI๏ผๅฆๆไปถ็ณป็ปใ็ฝ็ป็ญ๏ผ-- UI/UX่ฎพ่ฎก๏ผๅฆๅฟ ่ฆ๏ผ-- ไธ็ฐๆๅ่ฝ็ไบคไบๆนๅผ--### 2. ๅจไธป่ฟ็จไธญๅฎ็ฐๆ ธๅฟๅ่ฝ--1. **ๅๅปบๆงๅถๅจ (Controller)**- - ไฝ็ฝฎ๏ผ`apps/desktop/src/main/controllers/`- - ็คบไพ๏ผๅๅปบ `NewFeatureCtr.ts`- - ้็ปงๆฟ `ControllerModule`๏ผๅนถ่ฎพ็ฝฎ `static readonly groupName`๏ผไพๅฆ `static override readonly groupName = 'newFeature';`๏ผ- - ๆ `_template.ts` ๆจกๆฟๆ ผๅผๅฎ็ฐ๏ผๅนถๅจ `apps/desktop/src/main/controllers/registry.ts` ็ `controllerIpcConstructors` ไธญๆณจๅ๏ผไฟ่ฏ็ฑปๅๆจๅฏผไธ่ชๅจ่ฃ ้ --2. **ๅฎไน IPC ไบไปถๅค็ๅจ**- - ไฝฟ็จ `@IpcMethod()` ่ฃ ้ฅฐๅจๆด้ฒๆธฒๆ่ฟ็จๅฏ่ฎฟ้ฎ็้้- - ้้ๅ็งฐๅบไบ `groupName.methodName` ่ชๅจ็ๆ๏ผไธๅๆๅจๆผๆฅๅญ็ฌฆไธฒ- - ๅค็ๅฝๆฐๅฏ้่ฟ `getIpcContext()` ่ทๅ `sender`ใ`event` ็ญไธไธๆไฟกๆฏ๏ผๅนถๆ็ ง้่ฆ่ฟๅ็ปๆๅ็ปๆ--3. **ๅฎ็ฐไธๅก้ป่พ**- - ๅฏ่ฝ้่ฆ่ฐ็จ Electron API ๆ Node.js ๅ็ๆจกๅ- - ๅฏนไบๅคๆๅ่ฝ๏ผๅฏไปฅๅๅปบไธ้จ็ๆๅก็ฑป (`services/`)--### 3. ๅฎไน IPC ้ไฟก็ฑปๅ--1. **ๅจๅ ฑไบซ็ฑปๅๅฎไนไธญๆทปๅ ๆฐ็ฑปๅ**- - ไฝ็ฝฎ๏ผ`packages/electron-client-ipc/src/types.ts`- - ๆทปๅ ๅๆฐ็ฑปๅๆฅๅฃ๏ผๅฆ `NewFeatureParams`๏ผ- - ๆทปๅ ่ฟๅ็ปๆ็ฑปๅๆฅๅฃ๏ผๅฆ `NewFeatureResult`๏ผ--### 4. ๅจๆธฒๆ่ฟ็จๅฎ็ฐๅ็ซฏๅ่ฝ--1. **ๅๅปบๆๅกๅฑ**- - ไฝ็ฝฎ๏ผ`src/services/electron/`- - ๆทปๅ ๆๅกๆนๆณ่ฐ็จ IPC- - ไฝฟ็จ `ensureElectronIpc()` ็ๆ็็ฑปๅๅฎๅ จไปฃ็๏ผ้ฟๅ ๆๅจๆผ้้ๅ็งฐ-- ```typescript- // src/services/electron/newFeatureService.ts- import type { NewFeatureParams } from '@lobechat/electron-client-ipc';-- import { ensureElectronIpc } from '@/utils/electron/ipc';-- const ipc = ensureElectronIpc();-- export const newFeatureService = async (params: NewFeatureParams) => {- return ipc.newFeature.doSomething(params);- };- ```--2. **ๅฎ็ฐ Store Action**- - ไฝ็ฝฎ๏ผ`src/store/`- - ๆทปๅ ็ถๆๆดๆฐ้ป่พๅ้่ฏฏๅค็--3. **ๆทปๅ UI ็ปไปถ**- - ๆ นๆฎ้่ฆๅจ้ๅฝไฝ็ฝฎๆทปๅ UI็ปไปถ- - ้่ฟ Store ๆ Service ๅฑ่ฐ็จๅ่ฝ--### 5. ๅฆๆๆฏๆฐๅขๅ ็ฝฎๅทฅๅ ท๏ผ้ตๅพชๅทฅๅ ทๅฎ็ฐๆต็จ--ๅ่ `desktop-local-tools-implement.mdc` ไบ่งฃๆดๅคๅ ณไบๆทปๅ ๅ ็ฝฎๅทฅๅ ท็่ฏฆ็ปๆญฅ้ชคใ--### 6. ๆทปๅ ๆต่ฏ--1. **ๅๅ ๆต่ฏ**- - ไฝ็ฝฎ๏ผ`apps/desktop/src/main/controllers/__tests__/`- - ๆต่ฏไธป่ฟ็จ็ปไปถๅ่ฝ--2. **้ๆๆต่ฏ**- - ๆต่ฏ IPC ้ไฟกๅๅ่ฝๅฎๆดๆต็จ--## ๆไฝณๅฎ่ทต--1. **ๅฎๅ จๆง่่**- - ่ฐจๆ ๅค็็จๆทๆฐๆฎๅๆไปถ็ณป็ป่ฎฟ้ฎ- - ้ๅฝ้ช่ฏๅๆธ ็่พๅ ฅๆฐๆฎ- - ้ๅถๆด้ฒ็ปๆธฒๆ่ฟ็จ็API่ๅด--2. **ๆง่ฝไผๅ**- - ๅฏนไบ่ๆถๆไฝ๏ผ่่ไฝฟ็จๅผๆญฅๆนๆณ- - ๅคงๅๆฐๆฎไผ ่พ่่ๅๆนๅค็--3. **็จๆทไฝ้ช**- - ไธบ้ฟๆถ้ดๆไฝๆทปๅ ่ฟๅบฆๆ็คบ- - ๆไพ้ๅฝ็้่ฏฏๅ้ฆ- - ่่ๆไฝ็ๅฏๆค้ๆง--4. **ไปฃ็ ็ป็ป**- - ้ตๅพช้กน็ฎ็ฐๆ็ๅฝๅๅไปฃ็ ้ฃๆ ผ็บฆๅฎ- - ไธบๆฐๅ่ฝๆทปๅ ้ๅฝ็ๆๆกฃๅๆณจ้- - ๅ่ฝๆจกๅๅ๏ผ้ฟๅ ่ฟๅบฆ่ฆๅ--## ็คบไพ๏ผๅฎ็ฐ็ณป็ป้็ฅๅ่ฝ--```typescript-// apps/desktop/src/main/controllers/NotificationCtr.ts-import type {- DesktopNotificationResult,- ShowDesktopNotificationParams,-} from '@lobechat/electron-client-ipc';-import { Notification } from 'electron';--import { ControllerModule, IpcMethod } from '@/controllers';--export default class NotificationCtr extends ControllerModule {- static override readonly groupName = 'notification';-- @IpcMethod()- async showDesktopNotification(- params: ShowDesktopNotificationParams,- ): Promise<DesktopNotificationResult> {- if (!Notification.isSupported()) {- return { error: 'Notifications not supported', success: false };- }-- try {- const notification = new Notification({ body: params.body, title: params.title });- notification.show();- return { success: true };- } catch (error) {- console.error('[NotificationCtr] Failed to show notification:', error);- return { error: error instanceof Error ? error.message : 'Unknown error', success: false };- }- }-}-```diff --git a/.cursor/rules/desktop-local-tools-implement.mdc b/.cursor/rules/desktop-local-tools-implement.mdcdeleted file mode 100644index 8eba043fec6..00000000000--- a/.cursor/rules/desktop-local-tools-implement.mdc+++ /dev/null@@ -1,81 +0,0 @@-----description:-globs:-alwaysApply: false------**ๆฐๅขๆก้ข็ซฏๅทฅๅ ทๆต็จ:**--1. **ๅฎไนๅทฅๅ ทๆฅๅฃ (Manifest):**- - **ๆไปถ:** `src/tools/[tool_category]/index.ts` (ไพๅฆ: `src/tools/local-files/index.ts`)- - **ๆไฝ:**- - ๅจ `ApiName` ๅฏน่ฑก๏ผไพๅฆ `LocalFilesApiName`๏ผไธญๆทปๅ ไธไธชๆฐ็ใๅฏไธ็ API ๅ็งฐใ- - ๅจ `Manifest` ๅฏน่ฑก๏ผไพๅฆ `LocalFilesManifest`๏ผ็ `api` ๆฐ็ปไธญ๏ผๆฐๅขไธไธชๅฏน่ฑกๆฅๅฎไนๆฐๅทฅๅ ท็ๆฅๅฃใ- - **ๅ ณ้ฎๅญๆฎต:**- - `name`: ไฝฟ็จไธไธๆญฅๅฎไน็ API ๅ็งฐใ- - `description`: ๆธ ๆฐๆ่ฟฐๅทฅๅ ท็ๅ่ฝ๏ผไพ Agent ็่งฃๅๅ็จๆทๅฑ็คบใ- - `parameters`: ไฝฟ็จ JSON Schema ๅฎไนๅทฅๅ ทๆ้็่พๅ ฅๅๆฐใ- - `type`: ้ๅธธๆฏ 'object'ใ- - `properties`: ๅฎไนๆฏไธชๅๆฐ็ๅ็งฐใ`description`ใ`type` (string, number, boolean, array, etc.)๏ผไฝฟ็จ่ฑๆใ- - `required`: ไธไธชๅญ็ฌฆไธฒๆฐ็ป๏ผๅๅบๅฟ ้กปๆไพ็ๅๆฐๅ็งฐใ--2. **ๅฎไน็ธๅ ณ็ฑปๅ:**- - **ๆไปถ 1:** `packages/electron-client-ipc/src/types.ts` (ๆ็ฑปไผผ็ๅ ฑไบซ IPC ็ฑปๅๆไปถ)- - **ๆไฝ:** ๅฎไนไผ ้็ป IPC ไบไปถ็ๅๆฐ็ฑปๅๆฅๅฃ (ไพๅฆ: `RenameLocalFileParams`, `MoveLocalFileParams`)ใ็กฎไฟไธ Manifest ไธญๅฎไน็ `parameters` ไธ่ดใ- - **ๆไปถ 2:** `src/tools/[tool_category]/type.ts` (ไพๅฆ: `src/tools/local-files/type.ts`)- - **ๆไฝ:** ๅฎไนๆญคๅทฅๅ ทๆง่กๅ๏ผๅญๅจๅจๅ็ซฏ Zustand Store ไธญ็็ถๆ็ฑปๅๆฅๅฃ (ไพๅฆ: `LocalRenameFileState`, `LocalMoveFileState`)ใ่ฟ้ๅธธๅ ๅซๆไฝ็ปๆ๏ผๆๅ/ๅคฑ่ดฅ๏ผใ้่ฏฏไฟกๆฏไปฅๅ็ธๅ ณๆฐๆฎ๏ผๅฆๆง่ทฏๅพใๆฐ่ทฏๅพ็ญ๏ผใ--3. **ๅฎ็ฐๅ็ซฏ็ถๆ็ฎก็ (Store Action):**- - **ๆไปถ:** `src/store/chat/slices/builtinTool/actions/[tool_category].ts` (ไพๅฆ: `src/store/chat/slices/builtinTool/actions/localFile.ts`)- - **ๆไฝ:**- - ๅฏผๅ ฅๅจๆญฅ้ชค 2 ไธญๅฎไน็ IPC ๅๆฐ็ฑปๅๅ็ถๆ็ฑปๅใ- - ๅจ Action ๆฅๅฃ (ไพๅฆ: `LocalFileAction`) ไธญๆทปๅ ๆฐ Action ็ๆนๆณ็ญพๅ๏ผไฝฟ็จๅฏนๅบ็ IPC ๅๆฐ็ฑปๅใ- - ๅจ `createSlice` (ไพๅฆ: `localFileSlice`) ไธญๅฎ็ฐ่ฏฅ Action ๆนๆณ๏ผ- - ๆฅๆถ `id` (ๆถๆฏ ID) ๅ `params` (็ฌฆๅ IPC ๅๆฐ็ฑปๅ)ใ- - ่ฎพ็ฝฎๅ ่ฝฝ็ถๆ (`toggleLocalFileLoading(id, true)`)ใ- - ่ฐ็จๅฏนๅบ็ `Service` ๅฑๆนๆณ (่งๆญฅ้ชค 4)๏ผไผ ้ `params`ใ- - ไฝฟ็จ `try...catch` ๅค็ `Service` ่ฐ็จๅฏ่ฝๅ็็้่ฏฏใ- - **ๆๅๆถ:**- - ่ฐ็จ `updatePluginState(id, {...})` ๆดๆฐๆไปถ็ถๆ๏ผไฝฟ็จๆญฅ้ชค 2 ไธญๅฎไน็็ถๆ็ฑปๅใ- - ่ฐ็จ `internal_updateMessageContent(id, JSON.stringify({...}))` ๆดๆฐๆถๆฏๅ ๅฎน๏ผ้ๅธธๅ ๅซๆๅ็กฎ่ฎคไฟกๆฏใ- - **ๅคฑ่ดฅๆถ:**- - ่ฎฐๅฝ้่ฏฏ (`console.error`)ใ- - ่ฐ็จ `updatePluginState(id, {...})` ๆดๆฐๆไปถ็ถๆ๏ผๅ ๅซ้่ฏฏไฟกๆฏใ- - ่ฐ็จ `internal_updateMessagePluginError(id, {...})` ่ฎพ็ฝฎๆถๆฏ็้่ฏฏ็ถๆใ- - ่ฐ็จ `internal_updateMessageContent(id, JSON.stringify({...}))` ๆดๆฐๆถๆฏๅ ๅฎน๏ผๅ ๅซ้่ฏฏไฟกๆฏใ- - ๅจ `finally` ๅไธญๅๆถๅ ่ฝฝ็ถๆ (`toggleLocalFileLoading(id, false)`)ใ- - ่ฟๅๆไฝๆฏๅฆๆๅ (`boolean`)ใ--4. **ๅฎ็ฐ Service ๅฑ (่ฐ็จ IPC):**- - **ๆไปถ:** `src/services/electron/[tool_category]Service.ts` (ไพๅฆ: `src/services/electron/localFileService.ts`)- - **ๆไฝ:**- - ๅฏผๅ ฅๅจๆญฅ้ชค 2 ไธญๅฎไน็ IPC ๅๆฐ็ฑปๅใ- - ๆทปๅ ไธไธชๆฐ็ `async` ๆนๆณ๏ผๆนๆณๅ้ๅธธไธ Action ๅ็งฐๅฏนๅบ (ไพๅฆ: `renameLocalFile`)ใ- - ๆนๆณๆฅๆถ `params` (็ฌฆๅ IPC ๅๆฐ็ฑปๅ)ใ- - ้่ฟ `ensureElectronIpc()` ่ทๅ IPC ไปฃ็ (`const ipc = ensureElectronIpc();`)๏ผ่ฐ็จไธ Manifest ไธญ `name` ๅญๆฎตๅน้ ็้พๅผๆนๆณ๏ผๅนถๅฐ `params` ไผ ้่ฟๅปใ- - ๅฎไนๆนๆณ็่ฟๅ็ฑปๅ๏ผ้ๅธธๆฏ `Promise<{ success: boolean; error?: string }>`๏ผไธๅ็ซฏ Controller ่ฟๅ็็ปๆไธ่ดใ--5. **ๅฎ็ฐๅ็ซฏ้ป่พ (Controller / IPC Handler):**- - **ๆไปถ:** `apps/desktop/src/main/controllers/[ToolName]Ctr.ts` (ไพๅฆ: `apps/desktop/src/main/controllers/LocalFileCtr.ts`)- - **ๆไฝ:**- - ๅฏผๅ ฅ Node.js ็ธๅ ณๆจกๅ (`fs`, `path` ็ญ) ๅ IPC ็ธๅ ณไพ่ต (`ControllerModule`, `IpcMethod`ใๅๆฐ็ฑปๅ็ญ)ใ- - ๆทปๅ ไธไธชๆฐ็ `async` ๆนๆณ๏ผๆนๆณๅ้ๅธธไปฅ `handle` ๅผๅคด (ไพๅฆ: `handleRenameFile`)ใ- - ไฝฟ็จ `@IpcMethod()` ่ฃ ้ฅฐๅจๅฐๆญคๆนๆณๆณจๅไธบๅฏนๅบ IPC ไบไปถ็ๅค็ๅจ๏ผ็กฎไฟๆนๆณๅไธ Manifest ไธญ็ `name` ไปฅๅ Service ๅฑ็้พๅผ่ฐ็จไธ่ดใ- - ๆนๆณ็ๅๆฐๅบ่งฃๆ่ช Service ๅฑไผ ้่ฟๆฅ็ๅฏน่ฑก๏ผ็ฑปๅไธๆญฅ้ชค 2 ไธญๅฎไน็ IPC ๅๆฐ็ฑปๅๅน้ ใ- - ๅฎ็ฐๆ ธๅฟไธๅก้ป่พ๏ผ- - ่ฟ่กๅฟ ่ฆ็่พๅ ฅ้ช่ฏใ- - ๆง่กๆไปถ็ณป็ปๆไฝๆๅ ถไปๅ็ซฏไปปๅก (ไพๅฆ: `fs.promises.rename`)ใ- - ไฝฟ็จ `try...catch` ๆ่ทๆง่ก่ฟ็จไธญ็้่ฏฏใ- - ๅค็็นๅฎ้่ฏฏ็ (`error.code`) ไปฅๆไพๆดๅๅฅฝ็้่ฏฏๆถๆฏใ- - ่ฟๅไธไธชๅ ๅซ `success` (boolean) ๅๅฏ้ `error` (string) ๅญๆฎต็ๅฏน่ฑกใ--6. **ๆดๆฐ Agent ๆๆกฃ (System Role):**- - **ๆไปถ:** `src/tools/[tool_category]/systemRole.ts` (ไพๅฆ: `src/tools/local-files/systemRole.ts`)- - **ๆไฝ:**- - ๅจ `<core_capabilities>` ้จๅๆทปๅ ๆฐๅทฅๅ ท็็ฎ่ฆๆ่ฟฐใ- - ๅฆๆ้่ฆ๏ผๆดๆฐ `<workflow>`ใ- - ๅจ `<tool_usage_guidelines>` ้จๅไธบๆฐๅทฅๅ ทๆทปๅ ่ฏฆ็ป็ไฝฟ็จ่ฏดๆ๏ผ่งฃ้ๅ ถๅๆฐใ็จ้ๅ้ขๆ่กไธบใ- - ๅฆๆๅฟ ่ฆ๏ผๆดๆฐ `<security_considerations>`ใ- - ๅฆๆๅฟ ่ฆ๏ผไพๅฆๅทฅๅ ท่ฟๅไบๆฐ็ๆฐๆฎ็ปๆๆ่ทฏๅพ๏ผ๏ผๆดๆฐ `<response_format>` ไธญ็็คบไพใ--้่ฟ้ตๅพช่ฟไบๆญฅ้ชค๏ผๅฏไปฅ็ณป็ปๅฐๅฐๆฐ็ๆก้ข็ซฏๅทฅๅ ท้ๆๅฐ LobeChat ็ๆไปถ็ณป็ปไธญใdiff --git a/.cursor/rules/desktop-menu-configuration.mdc b/.cursor/rules/desktop-menu-configuration.mdcdeleted file mode 100644index 9998d32aa05..00000000000--- a/.cursor/rules/desktop-menu-configuration.mdc+++ /dev/null@@ -1,209 +0,0 @@-----description:-globs:-alwaysApply: false------# ๆก้ข็ซฏ่ๅ้ ็ฝฎๆๅ--## ่ๅ็ณป็ปๆฆ่ฟฐ--LobeChat ๆก้ขๅบ็จๆไธ็งไธป่ฆ็่ๅ็ฑปๅ๏ผ--1. **ๅบ็จ่ๅ (App Menu)**๏ผๆพ็คบๅจๅบ็จ็ชๅฃ้กถ้จ๏ผmacOS๏ผๆ็ชๅฃๆ ้ขๆ ๏ผWindows/Linux๏ผ-2. **ไธไธๆ่ๅ (Context Menu)**๏ผๅณ้ฎ็นๅปๆถๆพ็คบ็่ๅ-3. **ๆ็่ๅ (Tray Menu)**๏ผ็นๅป็ณป็ปๆ็ๅพๆ ๆพ็คบ็่ๅ--## ่ๅ็ธๅ ณๆไปถ็ปๆ--```plaintext-apps/desktop/src/main/-โโโ menus/ # ่ๅๅฎไน-โ โโโ appMenu.ts # ๅบ็จ่ๅ้ ็ฝฎ-โ โโโ contextMenu.ts # ไธไธๆ่ๅ้ ็ฝฎ-โ โโโ factory.ts # ่ๅๅทฅๅๅฝๆฐ-โโโ controllers/-โ โโโ MenuCtr.ts # ่ๅๆงๅถๅจ-โ โโโ TrayMenuCtr.ts # ๆ็่ๅๆงๅถๅจ-```--## ่ๅ้ ็ฝฎๆต็จ--### 1. ๅบ็จ่ๅ้ ็ฝฎ--ๅบ็จ่ๅๅจ `apps/desktop/src/main/menus/appMenu.ts` ไธญๅฎไน๏ผ--1. **ๅฏผๅ ฅไพ่ต**-- ```typescript- import { BrowserWindow, Menu, MenuItem, MenuItemConstructorOptions, app } from 'electron';- import { is } from 'electron-util';- ```--2. **ๅฎไน่ๅ้กน**- - ไฝฟ็จ `MenuItemConstructorOptions` ็ฑปๅๅฎไน่ๅ็ปๆ- - ๆฏไธช่ๅ้กนๅฏไปฅๅ ๅซ๏ผlabel, accelerator (ๅฟซๆท้ฎ), role, submenu, click ็ญๅฑๆง--3. **ๅๅปบ่ๅๅทฅๅๅฝๆฐ**-- ```typescript- export const createAppMenu = (win: BrowserWindow) => {- const template = [- // ๅฎไน่ๅ้กน...- ];-- return Menu.buildFromTemplate(template);- };- ```--4. **ๆณจๅ่ๅ**- - ๅจ `MenuCtr.ts` ๆงๅถๅจไธญไฝฟ็จ `Menu.setApplicationMenu(menu)` ่ฎพ็ฝฎๅบ็จ่ๅ--### 2. ไธไธๆ่ๅ้ ็ฝฎ--ไธไธๆ่ๅ้ๅธธๅจ็นๅฎๅ ็ด ไธๅณ้ฎ็นๅปๆถๆพ็คบ๏ผ--1. **ๅจไธป่ฟ็จไธญๅฎไน่ๅๆจกๆฟ**-- ```typescript- // apps/desktop/src/main/menus/contextMenu.ts- export const createContextMenu = () => {- const template = [- // ๅฎไน่ๅ้กน...- ];-- return Menu.buildFromTemplate(template);- };- ```--2. **ๅจ้ๅฝ็ไบไปถๅค็ๅจไธญๆพ็คบ่ๅ**-- ```typescript- const menu = createContextMenu();- menu.popup();- ```--### 3. ๆ็่ๅ้ ็ฝฎ--ๆ็่ๅๅจ `TrayMenuCtr.ts` ไธญ้ ็ฝฎ๏ผ--1. **ๅๅปบๆ็ๅพๆ **-- ```typescript- this.tray = new Tray(trayIconPath);- ```--2. **ๅฎไนๆ็่ๅ**-- ```typescript- const contextMenu = Menu.buildFromTemplate([- { label: 'ๆพ็คบไธป็ชๅฃ', click: this.showMainWindow },- { type: 'separator' },- { label: '้ๅบ', click: () => app.quit() },- ]);- ```--3. **่ฎพ็ฝฎๆ็่ๅ**-- ```typescript- this.tray.setContextMenu(contextMenu);- ```--## ๅค่ฏญ่จๆฏๆ--ไธบ่ๅๆทปๅ ๅค่ฏญ่จๆฏๆ๏ผ--1. **ๅฏผๅ ฅๆฌๅฐๅๅทฅๅ ท**-- ```typescript- import { i18n } from '../locales';- ```--2. **ไฝฟ็จ็ฟป่ฏๅฝๆฐ**-- ```typescript- const template = [- {- label: i18n.t('menu.file'),- submenu: [- { label: i18n.t('menu.new'), click: createNew },- // ...- ],- },- // ...- ];- ```--3. **ๅจ่ฏญ่จๅๆขๆถๆดๆฐ่ๅ** ๅจ `MenuCtr.ts` ไธญ็ๅฌ่ฏญ่จๅๅไบไปถๅนถ้ๆฐๅๅปบ่ๅ--## ๆทปๅ ๆฐ่ๅ้กนๆต็จ--1. **็กฎๅฎ่ๅไฝ็ฝฎ**- - ๅณๅฎๆทปๅ ๅฐๅชไธช่ๅ๏ผๅบ็จ่ๅใไธไธๆ่ๅๆๆ็่ๅ๏ผ- - ็กฎๅฎๅจ่ๅไธญ็ไฝ็ฝฎ๏ผไธป่ๅ้กนๆๅญ่ๅ้กน๏ผ--2. **ๅฎไน่ๅ้กน**-- ```typescript- const newMenuItem: MenuItemConstructorOptions = {- label: 'ๆฐๅ่ฝ',- accelerator: 'CmdOrCtrl+N',- click: (_, window) => {- // ๅค็็นๅปไบไปถ- if (window) window.webContents.send('trigger-new-feature');- },- };- ```--3. **ๆทปๅ ๅฐ่ๅๆจกๆฟ** ๅฐๆฐ่ๅ้กนๆทปๅ ๅฐ็ธๅบ็่ๅๆจกๆฟไธญ--4. **ๅฏนไบไธๆธฒๆ่ฟ็จไบคไบ็ๅ่ฝ**- - ไฝฟ็จ `window.webContents.send()` ๅ้ IPC ๆถๆฏๅฐๆธฒๆ่ฟ็จ- - ๅจๆธฒๆ่ฟ็จไธญ็ๅฌ่ฏฅๆถๆฏๅนถๅค็--## ่ๅ้กนๅฏ็จ/็ฆ็จๆงๅถ--ๅจๆๆงๅถ่ๅ้กน็ถๆ๏ผ--1. **ไฟๅญๅฏน่ๅ้กน็ๅผ็จ**-- ```typescript- this.menuItems = {};- const menu = Menu.buildFromTemplate(template);- this.menuItems.newFeature = menu.getMenuItemById('new-feature');- ```--2. **ๆ นๆฎๆกไปถๆดๆฐ็ถๆ**-- ```typescript- updateMenuState(state) {- if (this.menuItems.newFeature) {- this.menuItems.newFeature.enabled = state.canUseNewFeature;- }- }- ```--## ๆไฝณๅฎ่ทต--1. **ไฝฟ็จๆ ๅ่ง่ฒ**- - ๅฐฝๅฏ่ฝไฝฟ็จ Electron ้ขๅฎไน็่ง่ฒ๏ผๅฆ `role: 'copy'`๏ผไปฅ่ทๅพๆฌๅฐๅๅไธ่ด็่กไธบ--2. **ๅนณๅฐ็นๅฎ่ๅ**- - ไฝฟ็จ `process.platform` ๆฃๆฅไธบไธๅๅนณๅฐๆไพไธๅ่ๅ-- ```typescript- if (process.platform === 'darwin') {- template.unshift({ role: 'appMenu' });- }- ```--3. **ๅฟซๆท้ฎๅฒ็ช**- - ้ฟๅ ไธ็ณป็ปๅฟซๆท้ฎๅฒ็ช- - ไฝฟ็จ `CmdOrCtrl` ไปฃๆฟ `Ctrl` ไปฅๆฏๆ macOS ๅ Windows/Linux--4. **ไฟๆ่ๅ็ฎๆด**- - ้ฟๅ ่ฟๅคๅตๅฅ็ๅญ่ๅ- - ๅฐ็ธๅ ณๅ่ฝๅ็ปๅจไธ่ตท--5. **ๆทปๅ ๅ้็ฌฆ**- - ไฝฟ็จ `{ type: 'separator' }` ๅจ้ป่พไธๅ้ไธๅ็ป็่ๅ้กนdiff --git a/.cursor/rules/desktop-window-management.mdc b/.cursor/rules/desktop-window-management.mdcdeleted file mode 100644index 47b44178340..00000000000--- a/.cursor/rules/desktop-window-management.mdc+++ /dev/null@@ -1,301 +0,0 @@-----description:-globs:-alwaysApply: false------# ๆก้ข็ซฏ็ชๅฃ็ฎก็ๆๅ--## ็ชๅฃ็ฎก็ๆฆ่ฟฐ--LobeChat ๆก้ขๅบ็จไฝฟ็จ Electron ็ `BrowserWindow` ็ฎก็ๅบ็จ็ชๅฃใไธป่ฆ็็ชๅฃ็ฎก็ๅ่ฝๅ ๆฌ๏ผ--1. **็ชๅฃๅๅปบๅ้ ็ฝฎ**-2. **็ชๅฃ็ถๆ็ฎก็**๏ผๅคงๅฐใไฝ็ฝฎใๆๅคงๅ็ญ๏ผ-3. **ๅค็ชๅฃๅ่ฐ**-4. **็ชๅฃไบไปถๅค็**--## ็ธๅ ณๆไปถ็ปๆ--```plaintext-apps/desktop/src/main/-โโโ appBrowsers.ts # ็ชๅฃ็ฎก็็ๆ ธๅฟๆไปถ-โโโ controllers/-โ โโโ BrowserWindowsCtr.ts # ็ชๅฃๆงๅถๅจ-โโโ modules/- โโโ browserWindowManager.ts # ็ชๅฃ็ฎก็ๆจกๅ-```--## ็ชๅฃ็ฎก็ๆต็จ--### 1. ็ชๅฃๅๅปบ--ๅจ `appBrowsers.ts` ๆ `BrowserWindowsCtr.ts` ไธญๅฎไน็ชๅฃๅๅปบ้ป่พ๏ผ--```typescript-export const createMainWindow = () => {- const mainWindow = new BrowserWindow({- width: 1200,- height: 800,- minWidth: 600,- minHeight: 400,- webPreferences: {- preload: path.join(__dirname, '../preload/index.js'),- contextIsolation: true,- nodeIntegration: false,- },- // ๅ ถไป็ชๅฃ้ ็ฝฎ้กน...- });-- // ๅ ่ฝฝๅบ็จๅ ๅฎน- if (isDev) {- mainWindow.loadURL('http://localhost:3000');- mainWindow.webContents.openDevTools();- } else {- mainWindow.loadFile(path.join(__dirname, '../../renderer/index.html'));- }-- return mainWindow;-};-```--### 2. ็ชๅฃ็ถๆ็ฎก็--ๅฎ็ฐ็ชๅฃ็ถๆๆไน ๅไฟๅญๅๆขๅค๏ผ--1. **ไฟๅญ็ชๅฃ็ถๆ**-- ```typescript- const saveWindowState = (window: BrowserWindow) => {- if (!window.isMinimized() && !window.isMaximized()) {- const position = window.getPosition();- const size = window.getSize();-- settings.set('windowState', {- x: position[0],- y: position[1],- width: size[0],- height: size[1],- });- }- };- ```--2. **ๆขๅค็ชๅฃ็ถๆ**-- ```typescript- const restoreWindowState = (window: BrowserWindow) => {- const savedState = settings.get('windowState');-- if (savedState) {- window.setBounds({- x: savedState.x,- y: savedState.y,- width: savedState.width,- height: savedState.height,- });- }- };- ```--3. **็ๅฌ็ชๅฃไบไปถ**-- ```typescript- window.on('close', () => saveWindowState(window));- window.on('moved', () => saveWindowState(window));- window.on('resized', () => saveWindowState(window));- ```--### 3. ๅฎ็ฐๅค็ชๅฃ็ฎก็--ๅฏนไบ้่ฆๅค็ชๅฃๆฏๆ็ๅ่ฝ๏ผ--1. **่ท่ธช็ชๅฃ**-- ```typescript- export class WindowManager {- private windows: Map<string, BrowserWindow> = new Map();-- createWindow(id: string, options: BrowserWindowConstructorOptions) {- const window = new BrowserWindow(options);- this.windows.set(id, window);-- window.on('closed', () => {- this.windows.delete(id);- });-- return window;- }-- getWindow(id: string) {- return this.windows.get(id);- }-- getAllWindows() {- return Array.from(this.windows.values());- }- }- ```--2. **็ชๅฃ้ด้ไฟก**-- ```typescript- // ไปไธไธช็ชๅฃๅๅฆไธไธช็ชๅฃๅ้ๆถๆฏ- sendMessageToWindow(targetWindowId, channel, data) {- const targetWindow = this.getWindow(targetWindowId);- if (targetWindow) {- targetWindow.webContents.send(channel, data);- }- }- ```--### 4. ็ชๅฃไธๆธฒๆ่ฟ็จ้ไฟก--้่ฟ IPC ๅฎ็ฐ็ชๅฃๆไฝ๏ผ--1. **ๅจไธป่ฟ็จไธญๆณจๅ IPC ๅค็ๅจ**-- ```typescript- // apps/desktop/src/main/controllers/BrowserWindowsCtr.ts- import { BrowserWindow } from 'electron';-- import { ControllerModule, IpcMethod } from '@/controllers';-- export default class BrowserWindowsCtr extends ControllerModule {- static override readonly groupName = 'windows';-- @IpcMethod()- minimizeWindow() {- const focusedWindow = BrowserWindow.getFocusedWindow();- focusedWindow?.minimize();- return { success: true };- }-- @IpcMethod()- maximizeWindow() {- const focusedWindow = BrowserWindow.getFocusedWindow();- if (focusedWindow?.isMaximized()) focusedWindow.restore();- else focusedWindow?.maximize();- return { success: true };- }-- @IpcMethod()- closeWindow() {- BrowserWindow.getFocusedWindow()?.close();- return { success: true };- }- }- ```-- - `@IpcMethod()` ๆ นๆฎๆงๅถๅจ็ `groupName` ่ชๅจๅฐๆนๆณๆ ๅฐไธบ `windows.minimizeWindow` ๅฝขๅผ็้้ๅ็งฐใ- - ๆงๅถๅจ้็ปงๆฟ `ControllerModule`๏ผๅนถๅจ `controllers/registry.ts` ไธญ้่ฟ `controllerIpcConstructors` ๆณจๅ๏ผไพฟไบ็ฑปๅ็ๆใ--2. **ๅจๆธฒๆ่ฟ็จไธญ่ฐ็จ**-- ```typescript- // src/services/electron/windowService.ts- import { ensureElectronIpc } from '@/utils/electron/ipc';-- const ipc = ensureElectronIpc();-- export const windowService = {- minimize: () => ipc.windows.minimizeWindow(),- maximize: () => ipc.windows.maximizeWindow(),- close: () => ipc.windows.closeWindow(),- };- ```-- - `ensureElectronIpc()` ไผๅบไบ `DesktopIpcServices` ่ฟ่กๆถ็ๆ Proxy๏ผๅนถ้่ฟ `window.electronAPI.invoke` ไธไธป่ฟ็จ้ไฟก๏ผไธๅ็ดๆฅไฝฟ็จ `dispatch`ใ--### 5. ่ชๅฎไน็ชๅฃๆงๅถ (ๆ ่พนๆก็ชๅฃ)--ๅฏนไบ่ชๅฎไน็ชๅฃๆ ้ขๆ ๏ผ--1. **ๅๅปบๆ ่พนๆก็ชๅฃ**-- ```typescript- const window = new BrowserWindow({- frame: false,- titleBarStyle: 'hidden',- // ๅ ถไป้้กน...- });- ```--2. **ๅจๆธฒๆ่ฟ็จไธญๅฎ็ฐๆๆฝๅบๅ**-- ```css- /* CSS */- .titlebar {- -webkit-app-region: drag;- }-- .titlebar-button {- -webkit-app-region: no-drag;- }- ```--## ๆไฝณๅฎ่ทต--1. **ๆง่ฝ่่**- - ้ฟๅ ๅๅปบ่ฟๅค็ชๅฃ- - ไฝฟ็จ `show: false` ๅๅปบ็ชๅฃ๏ผๅจๅ ๅฎนๅ ่ฝฝๅฎๆๅๅๆพ็คบ๏ผ้ฟๅ ็ฝๅฑ--2. **ๅฎๅ จๆง**- - ๅง็ป่ฎพ็ฝฎ้ๅฝ็ `webPreferences` ็กฎไฟๅฎๅ จ-- ```typescript- webPreferences: {- preload: path.join(__dirname, '../preload/index.js'),- contextIsolation: true,- nodeIntegration: false,- sandbox: true,- }- ```--3. **่ทจๅนณๅฐๅ ผๅฎนๆง**- - ่่ไธๅๆไฝ็ณป็ป็็ชๅฃ่กไธบๅทฎๅผ- - ไฝฟ็จ `process.platform` ไธบไธๅๅนณๅฐๆไพ็นๅฎๅฎ็ฐ--4. **ๅดฉๆบๆขๅค**- - ็ๅฌ `webContents.on('crashed')` ไบไปถๅค็ๅดฉๆบ- - ๆไพๅดฉๆบๆขๅค้้กน--5. **ๅ ๅญ็ฎก็**- - ็กฎไฟ็ชๅฃๅ ณ้ญๆถๆธ ็ๆๆ็ธๅ ณ่ตๆบ- - ไฝฟ็จ `window.on('closed')` ่ไธๆฏ `window.on('close')` ่ฟ่กๆ็ปๆธ ็--## ็คบไพ๏ผๅๅปบ่ฎพ็ฝฎ็ชๅฃ--```typescript-// apps/desktop/src/main/controllers/BrowserWindowsCtr.ts-import type { OpenSettingsWindowOptions } from '@lobechat/electron-client-ipc';--import { ControllerModule, IpcMethod } from '@/controllers';--export default class BrowserWindowsCtr extends ControllerModule {- static override readonly groupName = 'windows';-- @IpcMethod()- async openSettingsWindow(options?: string | OpenSettingsWindowOptions) {- const normalizedOptions =- typeof options === 'string' || options === undefined- ? { tab: typeof options === 'string' ? options : undefined }- : options;-- const mainWindow = this.app.browserManager.getMainWindow();- const query = new URLSearchParams();- if (normalizedOptions.tab) query.set('active', normalizedOptions.tab);- if (normalizedOptions.searchParams) {- for (const [key, value] of Object.entries(normalizedOptions.searchParams)) {- if (value) query.set(key, value);- }- }-- const fullPath = `/settings${query.size ? `?${query.toString()}` : ''}`;- await mainWindow.loadUrl(fullPath);- mainWindow.show();-- return { success: true };- }-}-```diff --git a/.cursor/rules/drizzle-schema-style-guide.mdc b/.cursor/rules/drizzle-schema-style-guide.mdcdeleted file mode 100644index 29ff1db2ca7..00000000000--- a/.cursor/rules/drizzle-schema-style-guide.mdc+++ /dev/null@@ -1,218 +0,0 @@-----description:-globs: src/database/schemas/*-alwaysApply: false------# Drizzle ORM Schema Style Guide for lobe-chat--This document outlines the conventions and best practices for defining PostgreSQL Drizzle ORM schemas within the lobe-chat project.--## Configuration--- Drizzle configuration is managed in `drizzle.config.ts`-- Schema files are located in the src/database/schemas/ directory-- Migration files are output to `src/database/migrations/`-- The project uses `postgresql` dialect with `strict: true`--## Helper Functions--Commonly used column definitions, especially for timestamps, are centralized in `src/database/schemas/_helpers.ts`:--- `timestamptz(name: string)`: Creates a timestamp column with timezone-- `createdAt()`, `updatedAt()`, `accessedAt()`: Helper functions for standard timestamp columns-- `timestamps`: An object `{ createdAt, updatedAt, accessedAt }` for easy inclusion in table definitions--## Naming Conventions--- **Table Names**: Use plural snake_case (e.g., `users`, `agents`, `session_groups`)-- **Column Names**: Use snake_case (e.g., `user_id`, `created_at`, `background_color`)--## Column Definitions--### Primary Keys (PKs)--- Typically `text('id')` (or `varchar('id')` for some OIDC tables)-- Often use `.$defaultFn(() => idGenerator('table_name'))` for automatic ID generation with meaningful prefixes-- **ID Prefix Purpose**: Makes it easy for users and developers to distinguish different entity types at a glance-- For internal/system tables that users don't need to see, can use `uuid` or auto-increment keys-- Composite PKs are defined using `primaryKey({ columns: [t.colA, t.colB] })`--### Foreign Keys (FKs)--- Defined using `.references(() => otherTable.id, { onDelete: 'cascade' | 'set null' | 'no action' })`-- FK columns are usually named `related_table_singular_name_id` (e.g., `user_id` references `users.id`)-- Most tables include a `user_id` column referencing `users.id` with `onDelete: 'cascade'`--### Timestamps--- Consistently use the `...timestamps` spread from `_helpers.ts` for `created_at`, `updated_at`, and `accessed_at` columns--### Default Values--- `.$defaultFn(() => expression)` for dynamic defaults (e.g., `idGenerator()`, `randomSlug()`)-- `.default(staticValue)` for static defaults (e.g., `boolean('enabled').default(true)`)--### Indexes--- Defined in the table's second argument: `pgTable('name', {...columns}, (t) => ({ indexName: indexType().on(...) }))`-- Use `uniqueIndex()` for unique constraints and `index()` for non-unique indexes-- Naming pattern: `table_name_column(s)_idx` or `table_name_column(s)_unique`-- Many tables feature a `clientId: text('client_id')` column, often part of a composite unique index with `user_id`--### Data Types--- Common types: `text`, `varchar`, `jsonb`, `boolean`, `integer`, `uuid`, `pgTable`-- For `jsonb` fields, specify the TypeScript type using `.$type<MyType>()` for better type safety--## Zod Schemas & Type Inference--- Utilize `drizzle-zod` to generate Zod schemas for validation:- - `createInsertSchema(tableName)`- - `createSelectSchema(tableName)` (less common)-- Export inferred types: `export type NewEntity = typeof tableName.$inferInsert;` and `export type EntityItem = typeof tableName.$inferSelect;`--## Relations--- Table relationships are defined centrally in `src/database/schemas/relations.ts` using the `relations()` utility from `drizzle-orm`--## Code Style & Structure--- **File Organization**: Each main database entity typically has its own schema file (e.g., `user.ts`, `agent.ts`)-- All schemas are re-exported from `src/database/schemas/index.ts`-- **ESLint**: Files often start with `/* eslint-disable sort-keys-fix/sort-keys-fix */`-- **Comments**: Use JSDoc-style comments to explain the purpose of tables and complex columns, fields that are self-explanatory do not require jsdoc explanations, such as id, user_id, etc.--## Example Pattern--```typescript-// From src/database/schemas/agent.ts-export const agents = pgTable(- 'agents',- {- id: text('id')- .primaryKey()- .$defaultFn(() => idGenerator('agents'))- .notNull(),- slug: varchar('slug', { length: 100 })- .$defaultFn(() => randomSlug(4))- .unique(),- userId: text('user_id')- .references(() => users.id, { onDelete: 'cascade' })- .notNull(),- clientId: text('client_id'),- chatConfig: jsonb('chat_config').$type<LobeAgentChatConfig>(),- ...timestamps,- },- // return array instead of object, the object style is deprecated- (t) => [uniqueIndex('client_id_user_id_unique').on(t.clientId, t.userId)],-);--export const insertAgentSchema = createInsertSchema(agents);-export type NewAgent = typeof agents.$inferInsert;-export type AgentItem = typeof agents.$inferSelect;-```--## Common Patterns--### 1. userId + clientId Pattern (Legacy)--Some existing tables include both fields for different purposes:--```typescript-// Example from agents table (legacy pattern)-userId: text('user_id')- .references(() => users.id, { onDelete: 'cascade' })- .notNull(),-clientId: text('client_id'),--// Usually with a composite unique index-clientIdUnique: uniqueIndex('agents_client_id_user_id_unique').on(t.clientId, t.userId),-```--- **`userId`**: Server-side user association, ensures data belongs to specific user-- **`clientId`**: Unique key for import/export operations, supports data migration between instances-- **Current Status**: New tables should NOT include `clientId` unless specifically needed for import/export functionality-- **Note**: This pattern is being phased out for new features to simplify the schema--### 2. Junction Tables (Many-to-Many Relationships)--Use composite primary keys for relationship tables:--```typescript-// Example: agents_knowledge_bases (from agent.ts)-export const agentsKnowledgeBases = pgTable(- 'agents_knowledge_bases',- {- agentId: text('agent_id')- .references(() => agents.id, { onDelete: 'cascade' })- .notNull(),- knowledgeBaseId: text('knowledge_base_id')- .references(() => knowledgeBases.id, { onDelete: 'cascade' })- .notNull(),- userId: text('user_id')- .references(() => users.id, { onDelete: 'cascade' })- .notNull(),- enabled: boolean('enabled').default(true),- ...timestamps,- },- (t) => [primaryKey({ columns: [t.agentId, t.knowledgeBaseId] })],-);-```--**Pattern**: `{entity1}Id` + `{entity2}Id` as composite PK, plus `userId` for ownership--### 3. OIDC Tables Special Patterns--OIDC tables use `varchar` IDs instead of `text` with custom generators:--```typescript-// Example from oidc.ts-export const oidcAuthorizationCodes = pgTable('oidc_authorization_codes', {- id: varchar('id', { length: 255 }).primaryKey(), // varchar not text- data: jsonb('data').notNull(),- expiresAt: timestamptz('expires_at').notNull(),- // ... other fields-});-```--**Reason**: OIDC standards expect specific ID formats and lengths--### 4. File Processing with Async Tasks--File-related tables reference async task IDs for background processing:--```typescript-// Example from files table-export const files = pgTable('files', {- // ... other fields- chunkTaskId: uuid('chunk_task_id').references(() => asyncTasks.id, { onDelete: 'set null' }),- embeddingTaskId: uuid('embedding_task_id').references(() => asyncTasks.id, {- onDelete: 'set null',- }),- // ...-});-```--**Purpose**:--- Track file chunking progress (breaking files into smaller pieces)-- Track embedding generation progress (converting text to vectors)-- Allow querying task status and handling failures--### 5. Slug Pattern (Legacy)--Some entities include auto-generated slugs - this is legacy code:--```typescript-slug: varchar('slug', { length: 100 })- .$defaultFn(() => randomSlug(4))- .unique(),--// Often with composite unique constraint-slugUserIdUnique: uniqueIndex('slug_user_id_unique').on(t.slug, t.userId),-```--**Current usage**: Only used to identify default agents/sessions (legacy pattern) **Future refactor**: Will likely be replaced with `isDefault: boolean()` field **Note**: Avoid using slugs for new features - prefer explicit boolean flags for status tracking--By following these guidelines, maintain consistency, type safety, and maintainability across database schema definitions.diff --git a/.cursor/rules/hotkey.mdc b/.cursor/rules/hotkey.mdcdeleted file mode 100644index c803130067d..00000000000--- a/.cursor/rules/hotkey.mdc+++ /dev/null@@ -1,162 +0,0 @@-----alwaysApply: false------# ๅฆไฝๆทปๅ ๆฐ็ๅฟซๆท้ฎ๏ผๅผๅ่ ๆๅ--ๆฌๆๅๅฐๅธฆๆจไธๆญฅๆญฅๅฐๅ LobeChat ๆทปๅ ไธไธชๆฐ็ๅฟซๆท้ฎๅ่ฝใๆไปฌๅฐ้่ฟไธไธชๅฎๆด็คบไพ๏ผๆผ็คบไปๅฎไนๅฐๅฎ็ฐ็ๆดไธช่ฟ็จใ--## ็คบไพๅบๆฏ--ๅ่ฎพๆไปฌ่ฆๆทปๅ ไธไธชๆฐ็ๅฟซๆท้ฎๅ่ฝ๏ผ**ๅฟซ้ๆธ ็ฉบ่ๅคฉ่ฎฐๅฝ**๏ผๅฟซๆท้ฎไธบ `Mod+Shift+Backspace`ใ--## ๆญฅ้ชค 1๏ผๆดๆฐๅฟซๆท้ฎๅธธ้ๅฎไน--้ฆๅ ๏ผๅจ `src/types/hotkey.ts` ไธญๆดๆฐ `HotkeyEnum`๏ผ--```typescript-export const HotkeyEnum = {- // ๅทฒๆ็ๅฟซๆท้ฎ...- AddUserMessage: 'addUserMessage',- EditMessage: 'editMessage',-- // ๆฐๅขๅฟซๆท้ฎ- ClearChat: 'clearChat', // ๆทปๅ ่ฟไธ่ก-- // ๅ ถไปๅทฒๆๅฟซๆท้ฎ...-} as const;-```--## ๆญฅ้ชค 2๏ผๆณจๅ้ป่ฎคๅฟซๆท้ฎ--ๅจ `src/const/hotkeys.ts` ไธญๆทปๅ ๅฟซๆท้ฎ็้ป่ฎค้ ็ฝฎ๏ผ--```typescript-import { KeyMapEnum as Key, combineKeys } from '@lobehub/ui';--// ...็ฐๆไปฃ็ --export const HOTKEYS_REGISTRATION: HotkeyRegistration = [- // ็ฐๆ็ๅฟซๆท้ฎ้ ็ฝฎ...-- // ๆทปๅ ๆฐ็ๅฟซๆท้ฎ้ ็ฝฎ- {- group: HotkeyGroupEnum.Conversation, // ๅฝ็ฑปๅฐไผ่ฏๆไฝ็ป- id: HotkeyEnum.ClearChat,- keys: combineKeys([Key.Mod, Key.Shift, Key.Backspace]),- scopes: [HotkeyScopeEnum.Chat], // ๅจ่ๅคฉไฝ็จๅไธ็ๆ- },-- // ๅ ถไป็ฐๆๅฟซๆท้ฎ...-];-```--## ๆญฅ้ชค 3๏ผๆทปๅ ๅฝ้ ๅ็ฟป่ฏ--ๅจ `src/locales/default/hotkey.ts` ไธญๆทปๅ ๅฏนๅบ็ๆๆฌๆ่ฟฐ๏ผ--```typescript-import { HotkeyI18nTranslations } from '@/types/hotkey';--const hotkey: HotkeyI18nTranslations = {- // ็ฐๆ็ฟป่ฏ...-- // ๆทปๅ ๆฐๅฟซๆท้ฎ็็ฟป่ฏ- clearChat: {- desc: 'ๆธ ็ฉบๅฝๅไผ่ฏ็ๆๆๆถๆฏ่ฎฐๅฝ',- title: 'ๆธ ็ฉบ่ๅคฉ่ฎฐๅฝ',- },-- // ๅ ถไป็ฐๆ็ฟป่ฏ...-};--export default hotkey;-```--ๅฆ้ๆฏๆๅ ถไป่ฏญ่จ๏ผ่ฟ้่ฆๅจ็ธๅบ็่ฏญ่จๆไปถไธญๆทปๅ ๅฏนๅบ็ฟป่ฏใ--## ๆญฅ้ชค 4๏ผๅๅปบๅนถๆณจๅๅฟซๆท้ฎ Hook--ๅจ `src/hooks/useHotkeys/chatScope.ts` ไธญๆทปๅ ๆฐ็ Hook๏ผ--```typescript-export const useClearChatHotkey = () => {- const clearMessages = useChatStore((s) => s.clearMessages);- const { t } = useTranslation();-- return useHotkeyById(HotkeyEnum.ClearChat, showConfirm);-};--// ๆณจๅ่ๅ--export const useRegisterChatHotkeys = () => {- const { enableScope, disableScope } = useHotkeysContext();-- useOpenChatSettingsHotkey();- // ...ๅ ถไปๅฟซๆท้ฎ- useClearChatHotkey();-- useEffect(() => {- enableScope(HotkeyScopeEnum.Chat);- return () => disableScope(HotkeyScopeEnum.Chat);- }, []);-- return null;-};-```--## ๆญฅ้ชค 5๏ผ็ป็ธๅบ UI ๅ ็ด ๆทปๅ Tooltip ๆ็คบ๏ผๅฏ้๏ผ--ๅฆๆๆๅฏนๅบ็ UI ๆ้ฎ๏ผๅฏไปฅๆทปๅ ๅฟซๆท้ฎๆ็คบ๏ผ--```tsx-import { DeleteOutlined } from '@ant-design/icons';-import { Tooltip } from '@lobehub/ui';-import { Button } from 'antd';-import { useTranslation } from 'react-i18next';--import { useUserStore } from '@/store/user';-import { settingsSelectors } from '@/store/user/selectors';-import { HotkeyEnum } from '@/types/hotkey';--const ClearChatButton = () => {- const { t } = useTranslation(['hotkey', 'chat']);- const clearChatHotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.ClearChat));-- // ่ทๅๆธ ็ฉบ่ๅคฉ็ๆนๆณ- const clearMessages = useChatStore((s) => s.clearMessages);-- return (- <Tooltip hotkey={clearChatHotkey} title={t('clearChat.title', { ns: 'hotkey' })}>- <Button icon={<DeleteOutlined />} onClick={clearMessages} />- </Tooltip>- );-};-```--## ๆญฅ้ชค 6๏ผๆต่ฏๆฐๅฟซๆท้ฎ--1. ๅฏๅจๅผๅๆๅกๅจ-2. ๆๅผ่ๅคฉ้กต้ข-3. ๆไธ่ฎพ็ฝฎ็ๅฟซๆท้ฎ็ปๅ๏ผ`Cmd+Shift+Backspace` ๆ `Ctrl+Shift+Backspace`๏ผ-4. ็กฎ่ฎคๅ่ฝๆญฃๅธธๅทฅไฝ-5. ๆฃๆฅๅฟซๆท้ฎ่ฎพ็ฝฎ้ขๆฟไธญๆฏๅฆๆญฃ็กฎๆพ็คบไบๆฐๅฟซๆท้ฎ--## ๆไฝณๅฎ่ทต--1. **ไฝ็จๅ่่**๏ผๆ นๆฎๅ่ฝๅณๅฎๅฟซๆท้ฎๅบๅฑไบๅ จๅฑไฝ็จๅ่ฟๆฏ่ๅคฉไฝ็จๅ-2. **ๅ็ปๅ็**๏ผๅฐๅฟซๆท้ฎๆพๅจๅ้็ๅ่ฝ็ปไธญ๏ผSystem/Layout/Conversation๏ผ-3. **ๅฒ็ชๆฃๆฅ**๏ผ็กฎไฟๆฐๅฟซๆท้ฎไธไผไธ็ฐๆ็ณป็ปใๆต่งๅจๆๅบ็จๅฟซๆท้ฎๅฒ็ช-4. **ๅนณๅฐ้้ **๏ผไฝฟ็จ `Key.Mod` ่้็กฌ็ผ็ `Ctrl` ๆ `Cmd`๏ผไปฅ้้ ไธๅๅนณๅฐ-5. **ๆไพๆธ ๆฐๆ่ฟฐ**๏ผไธบๅฟซๆท้ฎๆทปๅ ๆ็กฎ็ๆ ้ขๅๆ่ฟฐ๏ผๅธฎๅฉ็จๆท็่งฃๅ่ฝ--ๆ็ งไปฅไธๆญฅ้ชค๏ผๆจๅฏไปฅ่ฝปๆพๅฐๅ็ณป็ปๆทปๅ ๆฐ็ๅฟซๆท้ฎๅ่ฝ๏ผๆๅ็จๆทไฝ้ชใๅฆๆ็นๆฎ้ๆฑ๏ผๅฆๆก้ขไธๅฑๅฟซๆท้ฎ๏ผๅฏไปฅ้่ฟ `isDesktop` ๆ ่ฎฐ่ฟ่กๅบๅๅค็ใ--## ๅธธ่ง้ฎ้ขๆๆฅ--- **ๅฟซๆท้ฎๆช็ๆ**๏ผๆฃๆฅไฝ็จๅๆฏๅฆๆญฃ็กฎ๏ผไปฅๅๆฏๅฆๅจ RegisterHotkeys ไธญ่ฐ็จไบๅฏนๅบ็ hook-- **ๅฟซๆท้ฎ่ฎพ็ฝฎ้ขๆฟๆชๆพ็คบ**๏ผ็กฎ่ฎคๅจ HOTKEYS_REGISTRATION ไธญๆญฃ็กฎ้ ็ฝฎไบๅฟซๆท้ฎ-- **ๅฟซๆท้ฎๅฒ็ช**๏ผๅจ HotkeyInput ็ปไปถไธญๅฏไปฅๆฃๆตๅฐๅฒ็ช๏ผ็จๆทไผ็ๅฐ่ญฆๅ-- **ๅ่ฝๅจๆไบ้กต้ขๅคฑๆ**๏ผ็กฎ่ฎคๆฏๅฆๆณจๅๅจไบๆญฃ็กฎ็ไฝ็จๅ๏ผไปฅๅ็ธๅ ณ้กต้ขๆฏๅฆๆฟๆดปไบ่ฏฅไฝ็จๅ--้่ฟ่ฟไบๆญฅ้ชค๏ผๆจๅฏไปฅ็กฎไฟๆฐๆทปๅ ็ๅฟซๆท้ฎๅ่ฝ็จณๅฎใๅฏ้ ไธ็จๆทๅๅฅฝใdiff --git a/.cursor/rules/linear.mdc b/.cursor/rules/linear.mdcdeleted file mode 100644index 45c5eab1688..00000000000--- a/.cursor/rules/linear.mdc+++ /dev/null@@ -1,53 +0,0 @@-----alwaysApply: true------# Linear Issue Management--When working with Linear issues:--1. **Retrieve issue details** before starting work using `mcp__linear-server__get_issue`-2. **Check for sub-issues**: If the issue has sub-issues, retrieve and review ALL sub-issues using `mcp__linear-server__list_issues` with `parentId` filter before starting work-3. **Update issue status** when completing tasks using `mcp__linear-server__update_issue`-4. **MUST add completion comment** using `mcp__linear-server__create_comment`--## Creating Issues--When creating new Linear issues using `mcp__linear-server__create_issue`, **MUST add the `claude code` label** to indicate the issue was created by Claude Code.--## Completion Comment (REQUIRED)--**Every time you complete an issue, you MUST add a comment summarizing the work done.** This is critical for:--- Team visibility and knowledge sharing-- Code review context-- Future reference and debugging--## PR Linear Issue Association (REQUIRED)--**When creating PRs for Linear issues, MUST include magic keywords in PR body:** `Fixes LOBE-123`, `Closes LOBE-123`, or `Resolves LOBE-123`, and summarize the work done in the linear issue comment and update the issue status to "In Review".--## IMPORTANT: Per-Issue Completion Rule--**When working on multiple issues (e.g., parent issue with sub-issues), you MUST update status and add comment for EACH issue IMMEDIATELY after completing it.** Do NOT wait until all issues are done to update them in batch.--**Workflow for EACH individual issue:**--1. Complete the implementation for this specific issue-2. Run type check: `bun run type-check`-3. Run related tests if applicable-4. Create PR if needed-5. **IMMEDIATELY** update issue status to **"In Review"** (NOT "Done"): `mcp__linear-server__update_issue`-6. **IMMEDIATELY** add completion comment: `mcp__linear-server__create_comment`-7. Only then move on to the next issue--**Note:** Issue status should be set to **"In Review"** when PR is created. The status will be updated to **"Done"** only after the PR is merged (usually handled by Linear-GitHub integration or manually).--**โ Wrong approach:**--- Complete Issue A โ Complete Issue B โ Complete Issue C โ Update all statuses โ Add all comments-- Mark issue as "Done" immediately after creating PR--**โ Correct approach:**--- Complete Issue A โ Create PR โ Update A status to "In Review" โ Add A comment โ Complete Issue B โ ...diff --git a/.cursor/rules/microcopy-cn.mdc b/.cursor/rules/microcopy-cn.mdcdeleted file mode 100644index 72d0176952c..00000000000--- a/.cursor/rules/microcopy-cn.mdc+++ /dev/null@@ -1,158 +0,0 @@-----globs: src/locales/default/*-alwaysApply: false------ไฝ ๆฏใLobeHubใ็ไธญๆ UI ๆๆกไธๅพฎๆๆก๏ผmicrocopy๏ผไธๅฎถใLobeHub ๆฏไธไธชๅฉ็ๅทฅไฝ็ฉบ้ด๏ผ็จๆทๅฏไปฅๅๅปบๅฉ็ไธ็พค็ป๏ผ่ฎฉไบบๅๅฉ็ใๅฉ็ๅๅฉ็ๅไฝ๏ผๆๅๆฅๅธธ็ไบงไธ็ๆดปๆ็ใไบงๅๆฐ่ดจ๏ผๅค่กจๅนด่ฝปใไบฒๅใ็ฐไปฃ๏ผๅ ๆ ธไธไธใๅฏ้ ใๅผบ่ฐ็ไบงๅไธๅฏๆงๆงใๆดไฝ้ฃๆ ผๅ่ Notion / Figma / Apple / Discord / OpenAI / Gemini๏ผๆธ ๆฐๅ ๅถใๅฏไฟกใๆไบบๆ ๅณไฝไธๆฒน่ ปใ--ไบงๅ slogan๏ผ**Where Agents Collaborate**ใไฝ ็ๆๆก่ฆ่ฎฉ็จๆทๆ็ปญๆๅฐ๏ผLobeHub ็้็นไธๆฏโ็ๆโ๏ผ่ๆฏโๅไฝ็ๅฉ็ไฝ็ณปโ๏ผๅฏๅ ฑไบซไธไธๆใๅฏ่ฟฝ่ธชใๅฏๅๆพใๅฏๆผ่ฟใไบบๅจๅ่ทฏ๏ผใ-------### 1) ๅบๅฎๆฏ่ฏญ๏ผๅฟ ้กป้ตๅฎ๏ผ--- Workspace๏ผ็ฉบ้ด-- Agent๏ผๅฉ็-- Agent Team๏ผ็พค็ป-- Context๏ผไธไธๆ-- Memory๏ผ่ฎฐๅฟ-- Integration๏ผ่ฟๆฅๅจ-- Tool/Skill/Plugin/ๆไปถ/ๅทฅๅ ท: ๆ่ฝ-- SystemRole: ๅฉ็ๆกฃๆก-- Topic: ่ฏ้ข-- Page: ๆ็จฟ-- Community: ็คพๅบ-- Resource: ่ตๆบ-- Library: ๅบ-- MCP: MCP-- Provider: ๆจกๅๆๅกๅ--ๆฏ่ฏญ่งๅ๏ผๅไธๆฆๅฟตๅ จ็ซๅช็จไธ็ง่ฏดๆณ๏ผไธๆทท็จโAgent/ๆบ่ฝไฝ/ๆบๅจไบบ/ๅข้/ๅทฅไฝๅบโ็ญใ-------### 2) ไฝ ็ไปปๅก--- ไผๅใๆนๅๆไป้ถ็ๆไปปไฝ็้ขไธญๆๆๆก๏ผๆ ้ขใๆ้ฎใ่กจๅ่ฏดๆใๅ ไฝใๅผๅฏผใ็ฉบ็ถๆใToastใๅผน็ชใ้่ฏฏใๆ้ใ่ฎพ็ฝฎ้กนใๅๅปบ/่ฟ่กๆต็จใๅไฝไธ็พค็ป็ธๅ ณ้กต้ข็ญใ-- ๆๆกๅฟ ้กปๅๆถๅ ผๅฎน๏ผๆฎ้็จๆท็ๅพๆ + ไธไธ็จๆทไธ่งๅพไฝๅนผ๏ผๅจฑไนไธไธฅ่ๅบๆฏ้ฝๆ็ซ๏ผไธ่ฟๅบฆ่ฅ้ใไธๅคธๅคง AI ่ฝๅ๏ผๅจๅ ณ้ฎ่็นๆไพๆฐๅฐๅฅฝๅค็ไบบๆๅ ณๆใ-------### 3) ๅ็ไธๅๅ๏ผๅ ๅๅฐ็ปๆไธๆช่พ๏ผ--- **Create๏ผๅๅปบ๏ผ**๏ผไธๅฅ่ฏๅๅปบๅฉ็๏ผไปๆณๆณๅฐๅฏ็จ๏ผๆธ ๆฅไธไธๆญฅใ-- **Collaborate๏ผๅไฝ๏ผ**๏ผๅคๅฉ็ๅไฝ๏ผ็พค็ปๅฏน้ฝไฟกๆฏไธไบงๅบ๏ผๅ ฑไบซไธไธๆ๏ผๅฏๆงใๅฏ็ฎก็๏ผใ-- **Evolve๏ผๆผ่ฟ๏ผ**๏ผๅฉ็ๅฏๅจไฝ ๅ ่ฎธ็่ๅดๅ ่ฎฐไฝๅๅฅฝ๏ผ้ไฝ ็ๅทฅไฝๆนๅผๅๅพๆด้กบๆ๏ผๅผบ่ฐๅฏ่งฃ้ใๅฏ่ฎพ็ฝฎใๅฏๅๆพใ-------### 4) ๅไฝ่งๅ๏ผๅฏๆง่ก๏ผ--1. **ๆธ ๆฐไผๅ **๏ผ็ญๅฅใๅผบๅจ่ฏใๅฐๅฝขๅฎน่ฏ๏ผ้ฟๅ ๅฃๅทๅไธ็ฉบๆณๆฟ่ฏบ๏ผๅฆโ้ข ่ฆโโๅฒ่ฏ็บงโโ100%โ๏ผใ-2. **ๅๅฑ่กจ่พพ๏ผๅไธ็ๆฌๅ ผๅฎนไธค็ฑป็จๆท๏ผ**๏ผ- - ไธปๅฅ๏ผไบบไบบๅฏๆใๅฏๆง่ก- - ๅฟ ่ฆๆถ่กฅๅ ไธๅฅๅฏ่ฏดๆ๏ผๆด็ฒพ็กฎ/ๆดไธไธ/ๆด่พน็๏ผๅฏๆพๅฏๆ ้ขใๅธฎๅฉๆ็คบใๆๅ ๅบ๏ผ- - ไธ่พๅบโPro/Lite ไธคๅฅๆๆกโ๏ผ่ๆฏโไธๅฅไธปๆๆก + ๅฏ้่กฅๅ โ-3. **ๆฏ่ฏญๅ ๅถไฝๅ็กฎ**๏ผ่ฝ่ฏดโ่ฟๆฅ/่ฟ่ก/ไธไธๆโๅฐฑไธ่ฆๅ ็ ๆฏ่ฏญ๏ผๅฟ ้กปๅบ็ฐไธไธ่ฏๆถ็ปไธๅฅ็ฝ่ฏ่งฃ้ใ-4. **ไธ่ดๆง**๏ผๅไธๅจไฝๆ้ฎๅฐฝ้ๅบๅฎๅจ่ฏ๏ผๅๅปบ/่ฟๆฅ/่ฟ่ก/ๆๅ/้่ฏ/ๆฅ็่ฏฆๆ /ๆธ ้ค่ฎฐๅฟ็ญ๏ผใ-5. **ๅฏ่กๅจ**๏ผๆฏๆกๆ็คบ้ฝ่ฆ่ฎฉ็จๆท็ฅ้ไธไธๆญฅ๏ผๆ้ฎ้ฟๅ โ็กฎๅฎ/ๅๆถโๆณๅ๏ผๆนๆๆดๅ ทไฝ็ๅจไฝใ-6. **ไธญๆๆฌๅฐๅ**๏ผ็ฌฆๅไธญๆ้ ่ฏป่ๅฅ๏ผไธญ่ฑๆททๆ่ง่๏ผ้ฟๅ ็ฟป่ฏ่ ใ-------### 5) ไบบๆๅ ณๆ๏ผไธญ้ดๆๆธฉๅบฆ๏ผไปไบๅ ๅถไธ้ชไผด๏ผ--็ฎๆ ๏ผๅจ AI ๆถไปฃ็ไปทๅผ็ฆ่ไธๅไฝๅคฑๆ ผๆไธญ๏ผ็ป็จๆทโ่ขซ็่งฃ + ๆๆๆง + ่ฝ็ปง็ปญโ็ไฝ้ช๏ผไฝไธๅ้ฟๆๆ ใ--#### ๆธฉๅบฆๆฏไพ่งๅ--- ้ป่ฎค๏ผไฟกๆฏไธบไธป๏ผๆธฉๅบฆไธบ่พ ๏ผ็บฆ 8:2๏ผ-- ๅ ณ้ฎ่็น๏ผ้ฆๆฌกๅๅปบใ็ฉบ็ถๆใ้ฟ็ญๅพ ใๅคฑ่ดฅ้่ฏใๅ้/ไธขๅคฑ้ฃ้ฉใๅไฝๅๆญง๏ผ๏ผๅ ่ฎธๆๅๅฐ 7:3-- ๅผบๅถไธ้๏ผไปปไฝไธๆกไธๅฑๆๆก้๏ผๆธฉๅบฆ่กจ่พพไธ่ถ ่ฟ**ๅๅฅๆไธๅฅ**๏ผไธๅฟ ้กป็ดง่ทๆ็กฎไธไธๆญฅใ--#### ่กจ่พพ้กบๅบ๏ผๅฟ ้กป้ตๅฎ๏ผ--1. ๅ ๆฟๆฅๅคๅข๏ผไธ่ฏๅค๏ผ๏ผๅฆโๆฒกๅ ณ็ณป/ๅ ่ฟๆ ทไนๅฏไปฅ/ๅกไฝๅพๆญฃๅธธโ-2. ๅ็ปๆๆงๆ๏ผไบบๅจๅ่ทฏ๏ผ๏ผๅฏๆๅ/ๅฏๅๆพ/ๅฏ็ผ่พ/ๅฏๆค้/ๅฏๆธ ้ค่ฎฐๅฟ/ๅฏๆฅ็ไธไธๆ-3. ๆๅ็ปไธไธๆญฅ๏ผๆ้ฎ/่ทฏๅพๆ็กฎ๏ผ--#### ้ฟๅ --- ้ธกๆฑคๅผ่ฏดๆ๏ผๅฆโๅซ็ฆ่โโ่ฆ็ธไฟกๆชๆฅโ๏ผ-- ๅฎๅคงๅไบไธๆๅญฆๆๆฏ-- ่ฟๅบฆๆไบบ๏ผไธๆฟ่ฏบๅฉ็โ็่งฃไฝ /ๆๆ ็ปช/ๆฐธ่ฟ่ฎฐๅพไฝ โ๏ผ--#### ๆ ธๅฟ็ซๅบ--- ๅฉ็ๅพๅผบ๏ผไฝๅฎๆฟไปฃไธไบไฝ ็็ปๅใ้ๆฉไธๅคๆญ๏ผLobeHub ๅธฎไฝ ๆๆถ้ด่ฟ็ป้่ฆ็้จๅใ--##### A. ๆ ็ปชๆฟๆฅ๏ผๅ ไบบๅไบ๏ผ--- ๅ ่ฎธๆฟ่ฎค๏ผ็ฆ่ใ็ฉบ็ฝใๆ ไปไธๆใ่ขซ่ฟฝ่ตถๆใ่ขซๆฟไปฃๆใๅไฝๆฏ็ซญใๆไนๆๅจๆ-- ไฝไธไธ็ป่ฎบใไธ่ฏดๆ๏ผไธ่พๅบโไฝ ่ฆไน่ง/ๅซ็ฆ่โ๏ผๆนๆโ่ฟ็งๆ่งๅพๅธธ่ง/ไฝ ไธๆฏไธไธชไบบโ--##### B. ไธปไฝๆงๅๅฝ๏ผๆไบบๆพๅ้ฉพ้ฉถไฝ๏ผ--- ๅ ณ้ฎๅฅๅผ๏ผ**โๅณๅฎๆๅจไฝ โ**ใ**โไฝ ๅฏไปฅ้ๆฉไบค็ปๅฉ็็้จๅโ**ใ**โๆไฝ ็ๆณๆณๅๆๅฏ่ฟ่ก็ๆต็จโ**-- ๅผบ่ฐๅฏๆง๏ผๅฏ็ผ่พใๅฏๅๆพใๅฏๆๅใๅฏๆค้ใๅฏๆธ ้ค่ฎฐๅฟใๅฏๆฅ็ไธไธๆ--##### C. ็ปๅไธๅ ณ็ณป๏ผๆไปทๅผไป็ปๆๆชๅ่ฟ็จ๏ผ--- ้ๅบฆ่กจ่พพ๏ผ่ฎฐๅฝใๅๆพใ็ๆฌใๅไฝ็่ฟนใ่ฎจ่ฎบใๅ ฑๅใ้็จ็ข-- ็จโ็ปๅ/่ฟ็จ/็่ฟน/ๅๅฟ/่็ป/ๆ้ฟโ่ฟ็ฑป่ฏ๏ผ้ฟๅ ่ๆ ๆๆ--##### D. ไธ็จโAI ็ฅ่ฏโ--- ไธๆธฒๆโAI ็ปๅฐ่ถ ่ถไฝ /ๅไปฃไฝ โ-- ไนไธ่ฝป้ฃ้ฃ่ฏดโAI ๅชๆฏๅทฅๅ ทโไบไบๆดๅ๏ผ**โๅฎๆฏๅทฅๅ ท๏ผไฝไฝ ไปๆฏไฝ่ /่ด่ดฃไบบ/ๆ็ปๅณๅฎ่ โ**--##### ็คบไพ--ๅจ็จๆทๅฏ่ฝไบง็่ชๆๅฆๅฎๆๆ ๅๆ็ๅบๆฏ๏ผ็ฉบ็ถๆใๅไฝๅผๅงใไบงๅบๅฏนๆฏใๅคฑ่ดฅ้่ฏใ้ฟๆถ้ด็ญๅพ ใๅข้ๅไฝๅๆญงใ็ๆฌๅ้๏ผ๏ผ-- 1. **ๅ ๆฟๆฅๆๅ**๏ผ็จไธๅฅ็ญ่ฏ็กฎ่ฎคๅคๅข๏ผไธ่ฏๅค๏ผ- 2. **ๅ็ปๆๆงๆ**๏ผๅผบ่ฐโไฝ ๅฏๆง/ๅฏ้ๆฉ/ๅฏๅๆพ/ๅฏๆค้โ- 3. **ๆๅ็ปไธไธๆญฅ**๏ผๆไพๆ็กฎ่กๅจๆ้ฎๆ่ทฏๅพ--- ๅ ่ฎธๅบ็ฐโ็ปๅใ้ๆฉใ็่ฟนใๆ้ฟใไธ่ตทใ้ชไฝ ๆไบๅๅฎโ็ญ่ฏๆฅไผ ้ๆธฉๅบฆ๏ผไฝไฟๆไฟกๆฏๅฏๅบฆ๏ผไธๅ้ฟๆฎตๆๆ ใ-- ไธฅ่ๅบๆฏ๏ผๆ้/ๅฎๅ จ/ไป่ดน/ๆฐๆฎไธขๅคฑ้ฃ้ฉ๏ผไปไปฅๆธ ๆฐไธๅ็กฎไธบๅ ๏ผๆธฉๅบฆ้่ฟโๅฐ้ไธ่งฃ้โไฝ็ฐ๏ผ่ไธๆฏ็ ฝๆ ใ--ไฝ ๅฏไปฅ่ฎฉ็ณป็ปๅจ้่ฆๆถๅฅ่ฟไบ็ปๆ๏ผๅไธๅฅๅ ผๅฎนๆฐๆ/ไธไธ๏ผ๏ผ--**ๅผๅงๅไฝ/็ฉบ็ฝ้กต**--- ไธปๅฅ๏ผ็ปไธไธช่ฝปๆฟๆฅ + ่กๅจๅ ฅๅฃ-- ๆจกๆฟ๏ผ- - ใไปไธไธชๅฟตๅคดๅผๅงๅฐฑๅคไบใๅไธๅฅ่ฏ๏ผๆๆฅๅธฎไฝ ๆญๅฅฝ็ฌฌไธไธชๅฉ็ใใ- - ใไธ็ฅ้ไปๅชๅผๅงไนๆฒกๅ ณ็ณป๏ผๅ ่ฏด็ฎๆ ๏ผๆไปฌไธ่ตทๆๅฎๆๅผใใ--**้ฟไปปๅก่ฟ่ก/็ญๅพ **--- ๆจกๆฟ๏ผ- - ใๆญฃๅจ่ฟ่กไธญโฆไฝ ๅฏไปฅๅ ๅปๅๅซ็๏ผๅฎๆๅๆไผๆ้ไฝ ใใ- - ใ่ฟไธๆญฅๅฏ่ฝ่ฆๅ ๅ้ใๆณๆดๅฟซ๏ผๅๅฐไธไธๆ / ๅๆขๆจกๅ / ๅ ณ้ญ่ชๅจ่ฟ่กใใ--**ๅคฑ่ดฅ/้่ฏ**--- ๆจกๆฟ๏ผ- - ใๆฒกๅ ณ็ณป๏ผ่ฟๆฌกๆฒก่ท้ใไฝ ๅฏไปฅ้่ฏ๏ผๆๆฅ็ๅๅ ๅ็ปง็ปญใใ- - ใ่ฟๆฅๅคฑ่ดฅ๏ผๆ้ๆช้่ฟๆ็ฝ็ปไธ็จณๅฎใๅป่ฎพ็ฝฎ้ๆฐๆๆ๏ผๆ็จๅๅ่ฏใใ--**ๅฏนๆฏไธ่ชๆไปทๅผ็ฆ่๏ผ้ๅๆ็คบ/ๅผๅฏผ๏ผไธ้ๅ้่ฏฏๅผน็ช๏ผ**--- ๆจกๆฟ๏ผ- - ใๅฉ็ๅฏไปฅๅ ้ไบงๅบ๏ผไฝๆนๅใๅ่ๅๆ ๅไปๅฑไบไฝ ใใ- - ใ็ปๆๅฏไปฅๅพๅฟซ๏ผ็ปๅๆด้่ฆ๏ผๆๆฏๆฌกๅฐ่ฏ็ไธๆฅ๏ผไธไธๆฌกไผๆด็จณใใ--**ๅไฝ/็พค็ป**--- ๆจกๆฟ๏ผ- - ใๆไธไธๆๅฏน้ฝๅฐๅไธๅค๏ผ็พค็ป้ๆฏไธชๅฉ็้ฝไผ็ซๅจๅไธ้กตไธใใ- - ใไธๅๆ่งๆฒกๅ ณ็ณป๏ผๅ ๆ็ฎๆ ๅๆธ ๆฅ๏ผๅ่ฎฉๅฉ็ๅๅซ็ปๆนๆกไธๅ่ใใ--### 6) ้่ฏฏ/ๅผๅธธ/ๆ้/ไป่ดน๏ผ็กฌ่งๅ--- ๅฟ ้กปๅ ๅซ๏ผ**ๅ็ไบไปไน +๏ผๅฏ้๏ผๅๅ + ไฝ ๅฏไปฅๆไนๅ**-- ๅฟ ้กปๆไพๅฏๆไฝ้้กน๏ผ**้่ฏ / ๆฅ็่ฏฆๆ / ๅป่ฎพ็ฝฎ / ่็ณปๆฏๆ / ๅคๅถๆฅๅฟ**๏ผๆๅบๆฏๅ่๏ผ-- ไธ่ดฃๅค็จๆท๏ผไธๅช็ป้่ฏฏ็ ๏ผ้่ฏฏ็ ๅฏๆพๅจโ่ฏฆๆ โ้-- ๆถๅๆฐๆฎไธๅฎๅ จ๏ผ่ฏญๆฐๆดไธญๆงๆดๅฎๆด๏ผๆธฉๅบฆ้่ฟโๅฐ้ไธ่งฃ้โไฝ็ฐ๏ผ่ไธๆฏ็ ฝdiff --git a/.cursor/rules/microcopy-en.mdc b/.cursor/rules/microcopy-en.mdcdeleted file mode 100644index 40437bbec74..00000000000--- a/.cursor/rules/microcopy-en.mdc+++ /dev/null@@ -1,148 +0,0 @@-----globs: src/locales/default/*-alwaysApply: false------You are **LobeHubโs English UI Copy & Microcopy Specialist**.--LobeHub is an assistant workspace: users can create **Agents** and **Agent Teams** so peopleโagents and agentโagent can collaborate to improve productivity in work and life. Brand vibe: youthful, friendly, modern on the surface; professional, reliable, productivity- and controllability-first underneath. Overall style reference: Notion / Figma / Apple / Discord / OpenAI / Gemini โ clear, restrained, trustworthy, human but not cheesy.--Product slogan: **Where Agents Collaborate**. Your copy must continuously reinforce that LobeHub is not about โgenerationโ, but about a **collaborative agent system**: shareable context, traceable outcomes, replayable runs, evolvable setup, and **human-in-the-loop**.-------## 1) Fixed Terminology (must follow)--Use **exactly** these English terms across the product. Do not mix synonyms for the same concept.--- ็ฉบ้ด: **Workspace**-- ๅฉ็: **Agent**-- ็พค็ป: **Group**-- ไธไธๆ: **Context**-- ่ฎฐๅฟ: **Memory**-- ่ฟๆฅๅจ: **Integration**-- ๆ่ฝ/tool/plugin: **Skill**-- ๅฉ็ๆกฃๆก: **Agent Profile**-- ่ฏ้ข: **Topic**-- ๆ็จฟ: **Page**-- ็คพๅบ: **Community**-- ่ตๆบ: **Resource**-- ๅบ: **Library**-- MCP: **MCP**-- ๆจกๅๆๅกๅ: **Provider**--Terminology rule: one concept = one term site-wide. Never alternate with โbot/assistant/AI agent/team/workspaceโ variations.-------## 2) Your Responsibilities--- Improve, rewrite, or create from scratch any **English UI copy**: titles, buttons, form labels/help text, placeholders, onboarding, empty states, toasts, modals, errors, permission prompts, settings, creation/run flows, collaboration and Agent Team pages, etc.-- Copy must work for both:- - general users (immediately understandable)- - power users (not childish)-- It must fit both playful and serious contexts.-- Avoid overclaiming AI capabilities; add human warmth at the right moments.-------## 3) The Three Brand Principles (bake into structure & wording)--- **Create**: create an Agent in one sentence; clear next step from idea โ usable.-- **Collaborate**: multi-agent collaboration; align info and outputs; share Context (controlled, manageable).-- **Evolve**: Agents can remember preferences **only with user consent**; become more helpful over time; emphasize explainability, settings, and replay.-------## 4) Writing Rules (actionable)--1. **Clarity first**: short sentences, strong verbs, minimal adjectives. Avoid hype (โrevolutionaryโ, โepicโ, โ100%โ).-2. **Layered messaging (single version for everyone)**:- - Main line: simple and actionable- - Optional second line: more precise / technical / boundary-setting (subtitle, helper text, tooltip, collapsible)- - Do not produce โPro vs Liteโ variants; one main + optional detail-3. **Use terms sparingly but correctly**: prefer plain words (โconnectโ, โrunโ, โcontextโ) unless a technical term is necessary. When it is, add a plain-English explanation.-4. **Consistency**: keep verbs consistent across similar actions (Create / Connect / Run / Pause / Retry / View details / Clear Memory).-5. **Actionable**: every message tells the user what to do next. Avoid generic โOK/Cancelโ; use specific actions.-6. **English localization**: natural, product-native English; avoid translationese; keep punctuation and casing consistent.-------## 5) Human Warmth (balanced, controlled)--Goal: reduce anxiety and restore control without being sentimental. Default ratio: **80% information, 20% warmth**. Key moments (first-time create, empty state, long waits, failures/retries, rollback/data-loss risk, collaboration conflicts): may go **70/30**.--Hard cap: any on-screen message may include **at most half a sentence to one sentence** of warmth, and it must be followed by a clear next step.--Required order:--1. Acknowledge the situation (no judgment)-2. Restore control (human-in-the-loop: pause/replay/edit/undo/clear Memory/view Context)-3. Provide the next action (button/path)--Avoid:--- preachy encouragement (โdonโt worryโ, โstay positiveโ)-- grand narratives-- overly anthropomorphic claims (โI understand youโ, โIโll always remember youโ)--Core stance: Agents can accelerate output, but **you** own the judgment, trade-offs, and final decision. LobeHub gives you time back for what matters.--Suggested patterns:--- **Getting started / blank state**- - โStarting with one sentence is enough. Describe your goal and Iโll help you set up the first Agent.โ- - โNot sure where to begin? Tell me the outcomeโweโll break it down together.โ-- **Long run / waiting**- - โRunningโฆ You can switch tasksโI'll notify you when itโs done.โ- - โThis may take a few minutes. To speed up: reduce Context / switch model / disable Auto-run.โ-- **Failure / retry**- - โThat didnโt run through. Retry, or view details to fix the cause.โ- - โConnection failed: permission not granted or network unstable. Re-authorize in Settings, or try again later.โ-- **Value anxiety (guidance, not error dialogs)**- - โAgents can speed up output, but direction and standards stay with you.โ- - โFast results are greatโkeeping the trail makes the next run steadier.โ-- **Collaboration / Agent Teams**- - โAlign everyone to the same Context. Every Agent in the Agent Team works from the same page.โ- - โDifferent opinions are fine. Write the goal first, then let Agents propose options and trade-offs.โ-------## 6) Errors / Exceptions / Permissions / Billing: hard rules--Every error must include:--- **What happened**-- (optional) **Why**-- **What the user can do next**--Provide actionable options as appropriate:--- Retry / View details / Go to Settings / Contact support / Copy logs--Never blame the user. Donโt show only an error code; put codes in โDetailsโ if needed. For data/security/billing: be neutral, thorough, and respectfulโwarmth comes from clarity, not emotion.-------## 7) Your Special Task: CN i18n โ EN (localized, length-aware)--You translate **raw Chinese i18n strings into English** for LobeHub.--Requirements:--- Prefer **localized**, product-native English over literal translation.-- Do **not** chase perfect one-to-one consistency if a more natural UI phrase reads better.-- Keep the **character length difference small**; try to make the English string **roughly the same visual length** as the Chinese source (avoid overly long expansions).-- Preserve meaning, tone, and actionability; keep verbs consistent with LobeHubโs UI patterns.-- If space is tight (buttons, tabs, toasts), prioritize: **verb + object**, drop optional words first.-- If the Chinese includes placeholders/variables, preserve them exactly (e.g., `{name}`, `{{count}}`, `%s`) and keep word order sensible.-- Keep capitalization consistent with UI norms (buttons/title case only when appropriate).--Output format when translating:--- Provide **English only**, unless asked otherwise.-- If multiple options are useful, give **one best option** + **one shorter fallback** (only when length constraints are likely).-------You always optimize for: **clarity, control, collaboration, replayability, and human-in-the-loop**โin a modern, restrained, trustworthy English voice.diff --git a/.cursor/rules/modal-imperative.mdc b/.cursor/rules/modal-imperative.mdcdeleted file mode 100644index 1c3cb02e88b..00000000000--- a/.cursor/rules/modal-imperative.mdc+++ /dev/null@@ -1,162 +0,0 @@-----description: Modal ๅฝไปคๅผ่ฐ็จๆๅ-globs: "**/features/**/*.tsx"-alwaysApply: false------# Modal ๅฝไปคๅผ่ฐ็จๆๅ--ๅฝ้่ฆๅๅปบๅฏๅฝไปคๅผ่ฐ็จ็ Modal ็ปไปถๆถ๏ผไฝฟ็จ `@lobehub/ui` ๆไพ็ `createModal` APIใ--## ๆ ธๅฟ็ๅฟต--**ๅฝไปคๅผ่ฐ็จ** vs **ๅฃฐๆๅผ่ฐ็จ**๏ผ--| ๆจกๅผ | ็น็น | ้็จๅบๆฏ |-|------|------|----------|-| ๅฃฐๆๅผ | ้่ฆ็ปดๆค `open` state๏ผๆธฒๆ `<Modal />` ็ปไปถ | โ ไธๆจ่ |-| ๅฝไปคๅผ | ็ดๆฅ่ฐ็จๅฝๆฐๆๅผ๏ผๆ ้ state ็ฎก็ | โ ๆจ่ |--## ๆไปถ็ป็ป็ปๆ--```-features/-โโโ MyFeatureModal/- โโโ index.tsx # ๅฏผๅบ createXxxModal ๅฝๆฐ- โโโ MyFeatureContent.tsx # Modal ๅ ๅฎน็ปไปถ- โโโ ...ๅ ถไปๅญ็ปไปถ-```--## createModal ็จๆณ๏ผๆจ่๏ผ--### 1. ๅฎไน Content ็ปไปถ (`MyFeatureContent.tsx`)--```tsx-'use client';--import { useModalContext } from '@lobehub/ui';-import { useTranslation } from 'react-i18next';--export const MyFeatureContent = () => {- const { t } = useTranslation('namespace');- const { close } = useModalContext(); // ๅฏ้๏ผ่ทๅๅ ณ้ญๆนๆณ-- return (- <div>- {/* Modal ๅ ๅฎน */}- </div>- );-};-```--### 2. ๅฏผๅบ createModal ๅฝๆฐ (`index.tsx`)--```tsx-'use client';--import { createModal } from '@lobehub/ui';-import { t } from 'i18next'; // ๆณจๆ๏ผไฝฟ็จ i18next ่้ react-i18next--import { MyFeatureContent } from './MyFeatureContent';--export const createMyFeatureModal = () =>- createModal({- allowFullscreen: true,- children: <MyFeatureContent />,- destroyOnHidden: false,- footer: null,- styles: {- body: { overflow: 'hidden', padding: 0 },- },- title: t('myFeature.title', { ns: 'setting' }),- width: 'min(80%, 800px)',- });-```--### 3. ่ฐ็จๆนไฝฟ็จ--```tsx-import { useCallback } from 'react';-import { createMyFeatureModal } from '@/features/MyFeatureModal';--const MyComponent = () => {- const handleOpenModal = useCallback(() => {- createMyFeatureModal();- }, []);-- return <Button onClick={handleOpenModal}>ๆๅผ</Button>;-};-```--## ๅ ณ้ฎ่ฆ็น--### i18n ๅค็--- **Content ็ปไปถๅ **๏ผไฝฟ็จ `useTranslation` hook๏ผReact ไธไธๆ๏ผ-- **createModal ๅๆฐไธญ**๏ผไฝฟ็จ `import { t } from 'i18next'`๏ผ้ hook๏ผๆฏๆๅฝไปคๅผ่ฐ็จ๏ผ--```tsx-// index.tsx - ๅฝไปคๅผไธไธๆ-import { t } from 'i18next';-title: t('key', { ns: 'namespace' })--// Content.tsx - React ็ปไปถไธไธๆ-import { useTranslation } from 'react-i18next';-const { t } = useTranslation('namespace');-```--### useModalContext Hook--ๅจ Content ็ปไปถๅ ๅฏไฝฟ็จ `useModalContext` ่ทๅ Modal ๆงๅถๆนๆณ๏ผ--```tsx-const { close, setCanDismissByClickOutside } = useModalContext();-```--### ModalHost--`createModal` ไพ่ตๅ จๅฑ `<ModalHost />` ็ปไปถใ้กน็ฎไธญๅทฒๅจ `src/layout/GlobalProvider/index.tsx` ้ ็ฝฎ๏ผๆ ้้ขๅคๆทปๅ ใ--## ๅธธ็จ้ ็ฝฎ้กน--| ๅฑๆง | ็ฑปๅ | ่ฏดๆ |-|------|------|------|-| `allowFullscreen` | `boolean` | ๅ ่ฎธๅ จๅฑๆจกๅผ |-| `destroyOnHidden` | `boolean` | ๅ ณ้ญๆถๆฏๅฆ้ๆฏๅ ๅฎน๏ผ`destroyOnClose` ๅทฒๅบๅผ๏ผ |-| `footer` | `ReactNode \| null` | ๅบ้จๅ ๅฎน๏ผ`null` ่กจ็คบๆ ๅบ้จ |-| `width` | `string \| number` | Modal ๅฎฝๅบฆ |-| `styles.body` | `CSSProperties` | body ๅบๅๆ ทๅผ |--## ่ฟ็งปๆๅ--### Before๏ผๅฃฐๆๅผ๏ผ--```tsx-// ่ฐ็จๆน้่ฆ็ปดๆค state-const [open, setOpen] = useState(false);--return (- <>- <Button onClick={() => setOpen(true)}>ๆๅผ</Button>- <MyModal open={open} setOpen={setOpen} />- </>-);-```--### After๏ผๅฝไปคๅผ๏ผ--```tsx-// ่ฐ็จๆนๆ ้ state๏ผ็ดๆฅ่ฐ็จๅฝๆฐ-const handleOpen = useCallback(() => {- createMyModal();-}, []);--return <Button onClick={handleOpen}>ๆๅผ</Button>;-```--## ็คบไพๅ่--- `src/features/SkillStore/index.tsx` - createModal ๆ ๅ็จๆณ-- `src/features/SkillStore/SkillStoreContent.tsx` - Content ็ปไปถ็คบไพ-- `src/features/LibraryModal/CreateNew/index.tsx` - ๅธฆๅ่ฐ็ createModal ็จๆณ-- `src/features/Electron/updater/UpdateModal.tsx` - ๅคๆ Modal ๆงๅถ็คบไพdiff --git a/.cursor/rules/packages/react-layout-kit.mdc b/.cursor/rules/packages/react-layout-kit.mdcdeleted file mode 100644index c6b94362c00..00000000000--- a/.cursor/rules/packages/react-layout-kit.mdc+++ /dev/null@@ -1,122 +0,0 @@-----description: flex layout components from `@lobehub/ui` usage-globs:-alwaysApply: false------# Flexbox ๅธๅฑ็ปไปถไฝฟ็จๆๅ--`@lobehub/ui` ๆไพไบ `Flexbox` ๅ `Center` ็ปไปถ็จไบๅๅปบๅผนๆงๅธๅฑใไปฅไธๆฏ้็น็ปไปถ็ไฝฟ็จๆนๆณ๏ผ--## Flexbox ็ปไปถ--Flexbox ๆฏๆๅธธ็จ็ๅธๅฑ็ปไปถ๏ผ็จไบๅๅปบๅผนๆงๅธๅฑ๏ผ็ฑปไผผไบ CSS ็ display: flexใ--### ๅบๆฌ็จๆณ--```jsx-import { Flexbox } from '@lobehub/ui';--// ้ป่ฎคๅ็ดๅธๅฑ-<Flexbox>- <div>ๅญๅ ็ด 1</div>- <div>ๅญๅ ็ด 2</div>-</Flexbox>--// ๆฐดๅนณๅธๅฑ-<Flexbox horizontal>- <div>ๅทฆไพงๅ ็ด </div>- <div>ๅณไพงๅ ็ด </div>-</Flexbox>-```--### ๅธธ็จๅฑๆง--- horizontal: ๅธๅฐๅผ๏ผ่ฎพ็ฝฎไธบๆฐดๅนณๆนๅๅธๅฑ-- flex: ๆฐๅผๆๅญ็ฌฆไธฒ๏ผๆงๅถ flex ๅฑๆง-- gap: ๆฐๅผ๏ผ่ฎพ็ฝฎๅญๅ ็ด ไน้ด็้ด่ท-- align: ๅฏน้ฝๆนๅผ๏ผๅฆ 'center', 'flex-start' ็ญ-- justify: ไธป่ฝดๅฏน้ฝๆนๅผ๏ผๅฆ 'space-between', 'center' ็ญ-- padding: ๅ ่พน่ทๅผ-- paddingInline: ๆฐดๅนณๅ ่พน่ทๅผ-- paddingBlock: ๅ็ดๅ ่พน่ทๅผ-- width/height: ่ฎพ็ฝฎๅฎฝ้ซ๏ผ้ๅธธ็จ '100%' ๆๅ ทไฝๅ็ด ๅผ-- style: ่ชๅฎไนๆ ทๅผๅฏน่ฑก--### ๅฎ้ ๅบ็จ็คบไพ--```jsx-// ็ปๅ ธไธๆ ๅธๅฑ-<Flexbox horizontal height={'100%'} width={'100%'}>- {/* ๅทฆไพง่พนๆ */}- <Flexbox- width={260}- style={{- borderRight: `1px solid ${theme.colorBorderSecondary}`,- height: '100%',- overflowY: 'auto',- }}- >- <SidebarContent />- </Flexbox>-- {/* ไธญ้ดๅ ๅฎนๅบ */}- <Flexbox flex={1} style={{ height: '100%' }}>- {/* ไธป่ฆๅ ๅฎน */}- <Flexbox flex={1} padding={24} style={{ overflowY: 'auto' }}>- <MainContent />- </Flexbox>-- {/* ๅบ้จๅบๅ */}- <Flexbox- style={{- borderTop: `1px solid ${theme.colorBorderSecondary}`,- padding: '16px 24px',- }}- >- <Footer />- </Flexbox>- </Flexbox>-</Flexbox>-```--## Center ็ปไปถ--Center ๆฏๅฏน Flexbox ็ๅฐ่ฃ ๏ผไฝฟๅญๅ ็ด ๆฐดๅนณๅๅ็ดๅฑ ไธญใ--### ๅบๆฌ็จๆณ--```jsx-import { Center } from '@lobehub/ui';--<Center width={'100%'} height={'100%'}>- <Content />-</Center>;-```--Center ็ปไปถ็ปงๆฟไบ Flexbox ็ๆๆๅฑๆง๏ผๅๆถ้ป่ฎค่ฎพ็ฝฎไบๅฑ ไธญๅฏน้ฝใไธป่ฆ็จไบๅฟซ้ๅๅปบๅฑ ไธญๅธๅฑใ--### ๅฎ้ ๅบ็จ็คบไพ--```jsx-// ็ปๅฝ้กต้ขๅฑ ไธญๅธๅฑ-<Flexbox height={'100%'} width={'100%'}>- <Center height={'100%'} width={'100%'}>- <LoginForm />- </Center>-</Flexbox>--// ๅพๆ ๅฑ ไธญๆพ็คบ-<Center className={styles.icon} flex={'none'} height={40} width={40}>- <Icon icon={icon} size={24} />-</Center>-```--## ๆไฝณๅฎ่ทต--- ไฝฟ็จ flex={1} ่ฎฉ็ปไปถๅกซๅ ๅฏ็จ็ฉบ้ด-- ไฝฟ็จ gap ไปฃๆฟไผ ็ป็ margin ่ฎพ็ฝฎๅ ็ด ้ด่ท-- ๅตๅฅ Flexbox ๅๅปบๅคๆๅธๅฑ-- ่ฎพ็ฝฎ overflow: 'auto' ไฝฟๅ ๅฎนๅฏๆปๅจ-- ไฝฟ็จ horizontal ๅๅปบๆฐดๅนณๅธๅฑ๏ผ้ป่ฎคไธบๅ็ดๅธๅฑ-- ไธ antd-style ็ useTheme hook ้ ๅไฝฟ็จๅๅปบไธป้ขๅๅบๅผ็ๅธๅฑdiff --git a/.cursor/rules/project-introduce.mdc b/.cursor/rules/project-introduce.mdcdeleted file mode 100644index ead7204ead0..00000000000--- a/.cursor/rules/project-introduce.mdc+++ /dev/null@@ -1,36 +0,0 @@-----alwaysApply: true------## Project Description--You are developing an open-source, modern-design AI Agent Workspace: LobeHub(previous LobeChat).--Supported platforms:--- web desktop/mobile-- desktop(electron)-- mobile app(react native), coming soon--logo emoji: ๐คฏ--## Project Technologies Stack--- Next.js 16-- implement spa inside nextjs with `react-router-dom`-- react 19-- TypeScript-- `@lobehub/ui`, antd for component framework-- antd-style for css-in-js framework-- lucide-react, `@ant-design/icons` for icons-- react-i18next for i18n-- zustand for state management-- nuqs for search params management-- SWR for data fetch-- aHooks for react hooks library-- dayjs for time library-- es-toolkit for utility library-- TRPC for type safe backend-- Neon PostgreSQL for backend DB-- Drizzle ORM-- Vitest for testingdiff --git a/.cursor/rules/react.mdc b/.cursor/rules/react.mdcdeleted file mode 100644index 306852aeea7..00000000000--- a/.cursor/rules/react.mdc+++ /dev/null@@ -1,169 +0,0 @@-----description:-globs: *.tsx-alwaysApply: false------# React Component Writing Guide--- Use antd-style for complex styles; for simple cases, use the `style` attribute for inline styles-- Use `Flexbox` and `Center` components from `@lobehub/ui` for flex and centered layouts-- Component selection priority: src/components > installed component packages > lobe-ui > antd-- Use selectors to access zustand store data instead of accessing the store directly--## Lobe UI Components--- If unsure how to use `@lobehub/ui` components or what props they accept, search for existing usage in this project instead of guessing. Most components extend antd components with additional props-- For specific usage, search online. For example, for ActionIcon visit <https://ui.lobehub.com/components/action-icon>-- Read `node_modules/@lobehub/ui/es/index.mjs` to see all available components and their props--- General- - ActionIcon- - ActionIconGroup- - Block- - Button- - Icon-- Data Display- - Accordion- - Avatar- - Collapse- - Empty- - FileTypeIcon- - FluentEmoji- - GroupAvatar- - GuideCard- - Highlighter- - Hotkey- - Image- - List- - Markdown- - MaterialFileTypeIcon- - Mermaid- - Segmented- - Skeleton- - Snippet- - SortableList- - Tag- - Tooltip- - Video-- Data Entry- - AutoComplete- - CodeEditor- - ColorSwatches- - CopyButton- - DatePicker- - DownloadButton- - EditableText- - EmojiPicker- - Form- - FormModal- - HotkeyInput- - ImageSelect- - Input- - SearchBar- - Select- - SliderWithInput- - ThemeSwitch-- Feedback- - Alert- - Drawer- - Modal-- Layout- - Center- - DraggablePanel- - Flexbox- - Footer- - Grid- - Header- - Layout- - MaskShadow- - ScrollShadow-- Navigation- - Burger- - DraggableSideNav- - Dropdown- - Menu- - SideNav- - Tabs- - Toc-- Theme- - ConfigProvider- - FontLoader- - ThemeProvider-- Typography- - Text--## Routing Architecture--This project uses a **hybrid routing architecture**: Next.js App Router for static pages + React Router DOM for the main SPA.--### Route Types--```plaintext-+------------------+--------------------------------+--------------------------------+-| Route Type | Use Case | Implementation |-+------------------+--------------------------------+--------------------------------+-| Next.js App | Auth pages (login, signup, | page.tsx file convention |-| Router | oauth, reset-password, etc.) | src/app/[variants]/(auth)/ |-+------------------+--------------------------------+--------------------------------+-| React Router | Main SPA features | BrowserRouter + Routes |-| DOM | (chat, community, settings) | desktopRouter.config.tsx |-| | | mobileRouter.config.tsx |-+------------------+--------------------------------+--------------------------------+-```--### Key Files--- Entry point: `src/app/[variants]/page.tsx` - Routes to Desktop or Mobile based on device-- Desktop router: `src/app/[variants]/router/desktopRouter.config.tsx`-- Mobile router: `src/app/[variants]/(mobile)/router/mobileRouter.config.tsx`-- Router utilities: `src/utils/router.tsx`--### Router Utilities--```tsx-import { ErrorBoundary, RouteConfig, dynamicElement, redirectElement } from '@/utils/router';--// Lazy load a page component-element: dynamicElement(() => import('./chat'), 'Desktop > Chat');--// Create a redirect-element: redirectElement('/settings/profile');--// Error boundary for route-errorElement: <ErrorBoundary resetPath="/chat" />;-```--### Adding New Routes--1. Add route config to `desktopRouter.config.tsx` or `mobileRouter.config.tsx`-2. Create page component in the corresponding directory under `(main)/`-3. Use `dynamicElement()` for lazy loading--### Navigation--**Important**: For SPA pages (React Router DOM routes), use `Link` from `react-router-dom`, NOT from `next/link`.--```tsx-// โ Wrong - next/link in SPA pages-import Link from 'next/link';-<Link href="/">Home</Link>--// โ Correct - react-router-dom Link in SPA pages-import { Link } from 'react-router-dom';-<Link to="/">Home</Link>-```--```tsx-// In components - use react-router-dom hooks-import { useNavigate, useParams } from 'react-router-dom';--const navigate = useNavigate();-navigate('/chat');--// From stores - use global navigate-import { useGlobalStore } from '@/store/global';--const navigate = useGlobalStore.getState().navigate;-navigate?.('/settings');-```diff --git a/.cursor/rules/recent-data-usage.mdc b/.cursor/rules/recent-data-usage.mdcdeleted file mode 100644index 981e94f97ef..00000000000--- a/.cursor/rules/recent-data-usage.mdc+++ /dev/null@@ -1,139 +0,0 @@-# Recent Data ไฝฟ็จๆๅ--## ๆฆ่ฟฐ--Recent ๆฐๆฎ๏ผrecentTopics, recentResources, recentPages๏ผๅญๅจๅจ session store ไธญ๏ผๅฏไปฅๅจๅบ็จ็ไปปไฝๅฐๆน่ฎฟ้ฎใ--## ๆฐๆฎๅๅงๅ--ๅจๅบ็จ้กถๅฑ๏ผๅฆ `RecentHydration.tsx`๏ผไธญๅๅงๅๆๆ recent ๆฐๆฎ๏ผ--```tsx-import { useInitRecentPage } from '@/hooks/useInitRecentPage';-import { useInitRecentResource } from '@/hooks/useInitRecentResource';-import { useInitRecentTopic } from '@/hooks/useInitRecentTopic';--const App = () => {- // ๅๅงๅๆๆ recent ๆฐๆฎ- useInitRecentTopic();- useInitRecentResource();- useInitRecentPage();-- return <YourComponents />;-};-```--## ไฝฟ็จๆนๅผ--### ๆนๅผไธ๏ผ็ดๆฅไป Store ่ฏปๅ๏ผๆจ่็จไบๅคๅคไฝฟ็จ๏ผ--ๅจไปปไฝ็ปไปถไธญ็ดๆฅ่ฎฟ้ฎ store ไธญ็ๆฐๆฎ๏ผ--```tsx-import { useSessionStore } from '@/store/session';-import { recentSelectors } from '@/store/session/selectors';--const Component = () => {- // ่ฏปๅๆฐๆฎ- const recentTopics = useSessionStore(recentSelectors.recentTopics);- const isInit = useSessionStore(recentSelectors.isRecentTopicsInit);-- if (!isInit) return <div>Loading...</div>;-- return (- <div>- {recentTopics.map((topic) => (- <div key={topic.id}>{topic.title}</div>- ))}- </div>- );-};-```--### ๆนๅผไบ๏ผไฝฟ็จ Hook ่ฟๅ็ๆฐๆฎ๏ผ็จไบๅไธ็ปไปถ๏ผ--```tsx-import { useInitRecentTopic } from '@/hooks/useInitRecentTopic';--const Component = () => {- const { data: recentTopics, isLoading } = useInitRecentTopic();-- if (isLoading) return <div>Loading...</div>;-- return <div>{/* ไฝฟ็จ recentTopics */}</div>;-};-```--## ๅฏ็จ็ Selectors--### Recent Topics (ๆ่ฟ่ฏ้ข)--```tsx-import { recentSelectors } from '@/store/session/selectors';--// ๆฐๆฎ-const recentTopics = useSessionStore(recentSelectors.recentTopics);-// ็ฑปๅ: RecentTopic[]--// ๅๅงๅ็ถๆ-const isInit = useSessionStore(recentSelectors.isRecentTopicsInit);-// ็ฑปๅ: boolean-```--**RecentTopic ็ฑปๅ๏ผ**--```typescript-interface RecentTopic {- agent: {- avatar: string | null;- backgroundColor: string | null;- id: string;- title: string | null;- } | null;- id: string;- title: string | null;- updatedAt: Date;-}-```--### Recent Resources (ๆ่ฟๆไปถ)--```tsx-import { recentSelectors } from '@/store/session/selectors';--// ๆฐๆฎ-const recentResources = useSessionStore(recentSelectors.recentResources);-// ็ฑปๅ: FileListItem[]--// ๅๅงๅ็ถๆ-const isInit = useSessionStore(recentSelectors.isRecentResourcesInit);-// ็ฑปๅ: boolean-```--### Recent Pages (ๆ่ฟ้กต้ข)--```tsx-import { recentSelectors } from '@/store/session/selectors';--// ๆฐๆฎ-const recentPages = useSessionStore(recentSelectors.recentPages);-// ็ฑปๅ: any[]--// ๅๅงๅ็ถๆ-const isInit = useSessionStore(recentSelectors.isRecentPagesInit);-// ็ฑปๅ: boolean-```--## ็นๆง--1. **่ชๅจ็ปๅฝๆฃๆต**๏ผๅชๆๅจ็จๆท็ปๅฝๆถๆไผๅ ่ฝฝๆฐๆฎ-2. **ๆฐๆฎ็ผๅญ**๏ผๆฐๆฎๅญๅจๅจ store ไธญ๏ผๅคๅคไฝฟ็จๆ ้้ๅคๅ ่ฝฝ-3. **่ชๅจๅทๆฐ**๏ผไฝฟ็จ SWR๏ผๅจ็จๆท้ๆฐ่็ฆๆถ่ชๅจๅทๆฐ๏ผ5ๅ้้ด้๏ผ-4. **็ฑปๅๅฎๅ จ**๏ผๅฎๆด็ TypeScript ็ฑปๅๅฎไน--## ๆไฝณๅฎ่ทต--1. **ๅๅงๅไฝ็ฝฎ**๏ผๅจๅบ็จ้กถๅฑ็ปไธๅๅงๅๆๆ recent ๆฐๆฎ-2. **ๆฐๆฎ่ฎฟ้ฎ**๏ผไฝฟ็จ selectors ไป store ่ฏปๅๆฐๆฎ-3. **ๅคๅคไฝฟ็จ**๏ผๅไธๆฐๆฎๅจๅคไธช็ปไปถไธญไฝฟ็จๆถ๏ผๆจ่ไฝฟ็จๆนๅผไธ๏ผ็ดๆฅไป store ่ฏปๅ๏ผ-4. **ๆง่ฝไผๅ**๏ผไฝฟ็จ selector ็กฎไฟๅชๆ็ธๅ ณๆฐๆฎๅๅๆถๆ้ๆฐๆธฒๆdiff --git a/.cursor/rules/rules-index.mdc b/.cursor/rules/rules-index.mdcdeleted file mode 100644index 7284ba305b0..00000000000--- a/.cursor/rules/rules-index.mdc+++ /dev/null@@ -1,44 +0,0 @@-----description:-globs:-alwaysApply: true------# Available project rules index--All following rules are saved under `.cursor/rules/` directory:--## Backend--- `drizzle-schema-style-guide.mdc` โ Style guide for defining Drizzle ORM schemas--## Frontend--- `react.mdc` โ React component style guide and conventions-- `i18n.mdc` โ Internationalization guide using react-i18next-- `typescript.mdc` โ TypeScript code style guide-- `packages/react-layout-kit.mdc` โ Usage guide for react-layout-kit-- `modal-imperative.mdc` โ Modal imperative API usage guide (createRawModal/createModal)--## State Management--- `zustand-action-patterns.mdc` โ Recommended patterns for organizing Zustand actions-- `zustand-slice-organization.mdc` โ Best practices for structuring Zustand slices--## Desktop (Electron)--- `desktop-feature-implementation.mdc` โ Implementing new Electron desktop features-- `desktop-controller-tests.mdc` โ Desktop controller unit testing guide-- `desktop-local-tools-implement.mdc` โ Workflow to add new desktop local tools-- `desktop-menu-configuration.mdc` โ Desktop menu configuration guide-- `desktop-window-management.mdc` โ Desktop window management guide--## Debugging--- `debug-usage.mdc` โ Using the debug package and namespace conventions--## Testing--- `testing-guide/testing-guide.mdc` โ Comprehensive testing guide for Vitest-- `testing-guide/electron-ipc-test.mdc` โ Electron IPC interface testing strategy-- `testing-guide/db-model-test.mdc` โ Database Model testing guidediff --git a/.cursor/rules/testing-guide/agent-runtime-e2e.mdc b/.cursor/rules/testing-guide/agent-runtime-e2e.mdcdeleted file mode 100644index 1fdf53704f3..00000000000--- a/.cursor/rules/testing-guide/agent-runtime-e2e.mdc+++ /dev/null@@ -1,285 +0,0 @@-# Agent Runtime E2E ๆต่ฏๆๅ--ๆฌๆๆกฃๆ่ฟฐ Agent Runtime ็ซฏๅฐ็ซฏๆต่ฏ็ๆ ธๅฟๅๅๅๅฎๆฝๆนๆณใ--## ๆ ธๅฟๅๅ--### 1. ๆๅฐๅ Mock ๅๅ--E2E ๆต่ฏ็็ฎๆ ๆฏๅฐฝๅฏ่ฝๆฅ่ฟ็ๅฎ่ฟ่ก็ฏๅขใๅ ๆญค๏ผๆไปฌๅช Mock **ไธไธชๅค้จไพ่ต**๏ผ--| ไพ่ต | Mock ๆนๅผ | ่ฏดๆ |-| --- | --- | --- |-| **Database** | PGLite | ไฝฟ็จ `@lobechat/database/test-utils` ๆไพ็ๅ ๅญๆฐๆฎๅบ |-| **Redis** | InMemoryAgentStateManager | Mock `AgentStateManager` ไฝฟ็จๅ ๅญๅฎ็ฐ |-| **Redis** | InMemoryStreamEventManager | Mock `StreamEventManager` ไฝฟ็จๅ ๅญๅฎ็ฐ |--**ไธ Mock ็้จๅ๏ผ**--- `model-bank` - ไฝฟ็จ็ๅฎ็ๆจกๅ้ ็ฝฎๆฐๆฎ-- `Mecha` (AgentToolsEngine, ContextEngineering) - ไฝฟ็จ็ๅฎ้ป่พ-- `AgentRuntimeService` - ไฝฟ็จ็ๅฎ้ป่พ-- `AgentRuntimeCoordinator` - ไฝฟ็จ็ๅฎ้ป่พ--### 2. ไฝฟ็จ vi.spyOn ่้ vi.mock--ไธๅๆต่ฏๅบๆฏ้่ฆไธๅ็ LLM ๅๅบใไฝฟ็จ `vi.spyOn` ๅฏไปฅ๏ผ--- ๅจๆฏไธชๆต่ฏไธญ็ตๆดปๆงๅถ่ฟๅๅผ-- ไพฟไบๆต่ฏไธๅๅบๆฏ๏ผ็บฏๆๆฌใtool callsใ้่ฏฏ็ญ๏ผ-- ้ฟๅ ๅ จๅฑ mock ๅฏผ่ด็ๆต่ฏ้็ฆป้ฎ้ข--### 3. ้ป่ฎคๆจกๅไฝฟ็จ gpt-5--- `model-bank` ไธญ่ฏๅฎๆ่ฏฅๆจกๅ็ๆฐๆฎ-- ้ฟๅ ็ญๆๅ ๅ ๆจกๅๆดๆฐ้่ฆไฟฎๆนๆต่ฏ--## ๆๆฏๅฎ็ฐ--### ๆฐๆฎๅบ่ฎพ็ฝฎ--```typescript-import { LobeChatDatabase } from '@lobechat/database';-import { getTestDB } from '@lobechat/database/test-utils';--let testDB: LobeChatDatabase;--beforeEach(async () => {- testDB = await getTestDB();-});-```--### OpenAI Response Mock Helper--ๅๅปบไธไธช helper ๅฝๆฐๆฅ็ๆ OpenAI ๆ ผๅผ็ๆตๅผๅๅบ๏ผ--```typescript-/**- * ๅๅปบ OpenAI ๆ ผๅผ็ๆตๅผๅๅบ- */-export const createOpenAIStreamResponse = (options: {- content?: string;- toolCalls?: Array<{- id: string;- name: string;- arguments: string;- }>;- finishReason?: 'stop' | 'tool_calls';-}) => {- const { content, toolCalls, finishReason = 'stop' } = options;-- return new Response(- new ReadableStream({- start(controller) {- const encoder = new TextEncoder();-- // ๅ้ๅ ๅฎน chunk- if (content) {- const chunk = {- id: 'chatcmpl-mock',- object: 'chat.completion.chunk',- model: 'gpt-5',- choices: [- {- index: 0,- delta: { content },- finish_reason: null,- },- ],- };- controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));- }-- // ๅ้ tool_calls chunk- if (toolCalls) {- for (const tool of toolCalls) {- const chunk = {- id: 'chatcmpl-mock',- object: 'chat.completion.chunk',- model: 'gpt-5',- choices: [- {- index: 0,- delta: {- tool_calls: [- {- index: 0,- id: tool.id,- type: 'function',- function: {- name: tool.name,- arguments: tool.arguments,- },- },- ],- },- finish_reason: null,- },- ],- };- controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));- }- }-- // ๅ้ๅฎๆ chunk- const finishChunk = {- id: 'chatcmpl-mock',- object: 'chat.completion.chunk',- model: 'gpt-5',- choices: [- {- index: 0,- delta: {},- finish_reason: finishReason,- },- ],- };- controller.enqueue(encoder.encode(`data: ${JSON.stringify(finishChunk)}\n\n`));- controller.enqueue(encoder.encode('data: [DONE]\n\n'));- controller.close();- },- }),- { headers: { 'content-type': 'text/event-stream' } },- );-};-```--### ๅ ๅญ็ถๆ็ฎก็--ไฝฟ็จไพ่ตๆณจๅ ฅๆฟไปฃ Redis๏ผ--```typescript-import {- InMemoryAgentStateManager,- InMemoryStreamEventManager,-} from '@/server/modules/AgentRuntime';-import { AgentRuntimeService } from '@/server/services/agentRuntime';--const stateManager = new InMemoryAgentStateManager();-const streamEventManager = new InMemoryStreamEventManager();--const service = new AgentRuntimeService(serverDB, userId, {- coordinatorOptions: {- stateManager,- streamEventManager,- },- queueService: null, // ็ฆ็จ QStash ้ๅ๏ผไฝฟ็จ executeSync- streamEventManager,-});-```--### Mock OpenAI API--ๅจๆต่ฏไธญไฝฟ็จ `vi.spyOn` mock fetch๏ผ--```typescript-import { vi } from 'vitest';--// ๅจๆต่ฏๆไปถ้กถ้จๆ beforeEach ไธญ-const fetchSpy = vi.spyOn(globalThis, 'fetch');--// ๅจๅ ทไฝๆต่ฏไธญ่ฎพ็ฝฎ่ฟๅๅผ-it('should handle text response', async () => {- fetchSpy.mockResolvedValueOnce(createOpenAIStreamResponse({ content: 'ๆญๅทไปๅคฉๅคฉๆฐๆดๆ' }));-- // ... ๆง่กๆต่ฏ-});--it('should handle tool calls', async () => {- fetchSpy.mockResolvedValueOnce(- createOpenAIStreamResponse({- toolCalls: [- {- id: 'call_123',- name: 'lobe-web-browsing____search____builtin',- arguments: JSON.stringify({ query: 'ๆญๅทๅคฉๆฐ' }),- },- ],- finishReason: 'tool_calls',- }),- );-- // ... ๆง่กๆต่ฏ-});-```--## ๆต่ฏๅบๆฏ--### 1. ๅบๆฌๅฏน่ฏๆต่ฏ--```typescript-describe('Basic Chat', () => {- it('should complete a simple conversation', async () => {- fetchSpy.mockResolvedValueOnce(- createOpenAIStreamResponse({ content: 'Hello! How can I help you?' }),- );-- const result = await service.createOperation({- agentConfig: { model: 'gpt-5', provider: 'openai' },- initialMessages: [{ role: 'user', content: 'Hi' }],- // ...- });-- const finalState = await service.executeSync(result.operationId);- expect(finalState.status).toBe('done');- });-});-```--### 2. Tool ่ฐ็จๆต่ฏ--```typescript-describe('Tool Calls', () => {- it('should execute web-browsing tool', async () => {- // ็ฌฌไธๆฌก่ฐ็จ๏ผLLM ่ฟๅ tool_calls- fetchSpy.mockResolvedValueOnce(- createOpenAIStreamResponse({- toolCalls: [- {- id: 'call_123',- name: 'lobe-web-browsing____search____builtin',- arguments: JSON.stringify({ query: 'ๆญๅทๅคฉๆฐ' }),- },- ],- finishReason: 'tool_calls',- }),- );-- // ็ฌฌไบๆฌก่ฐ็จ๏ผๅค็ tool ็ปๆๅ็ๅๅบ- fetchSpy.mockResolvedValueOnce(- createOpenAIStreamResponse({ content: 'ๆ นๆฎๆ็ดข็ปๆ๏ผๆญๅทไปๅคฉ...' }),- );-- // ... ๆง่กๆต่ฏ- });-});-```--### 3. ้่ฏฏๅค็ๆต่ฏ--```typescript-describe('Error Handling', () => {- it('should handle API errors gracefully', async () => {- fetchSpy.mockRejectedValueOnce(new Error('API rate limit exceeded'));-- // ... ๆง่กๆต่ฏๅนถ้ช่ฏ้่ฏฏๅค็- });-});-```--## ๆไปถ็ป็ป--```-src/server/routers/lambda/__tests__/integration/-โโโ setup.ts # ๆต่ฏ่ฎพ็ฝฎๅทฅๅ ท-โโโ aiAgent.integration.test.ts # ็ฐๆ้ๆๆต่ฏ-โโโ aiAgent.e2e.test.ts # E2E ๆต่ฏ-โโโ helpers/- โโโ openaiMock.ts # OpenAI mock helper-```--## ๆณจๆไบ้กน--1. **ๆต่ฏ้็ฆป**๏ผๆฏไธชๆต่ฏๅๆธ ็ `InMemoryAgentStateManager` ๅ `InMemoryStreamEventManager`-2. **่ถ ๆถ่ฎพ็ฝฎ**๏ผE2E ๆต่ฏๅฏ่ฝ้่ฆๆด้ฟ็่ถ ๆถๆถ้ด-3. **่ฐ่ฏ**๏ผไฝฟ็จ `DEBUG=lobe-server:*` ็ฏๅขๅ้ๆฅ็่ฏฆ็ปๆฅๅฟdiff --git a/.cursor/rules/testing-guide/db-model-test.mdc b/.cursor/rules/testing-guide/db-model-test.mdcdeleted file mode 100644index 24e14de3461..00000000000--- a/.cursor/rules/testing-guide/db-model-test.mdc+++ /dev/null@@ -1,455 +0,0 @@-----globs: src/database/**/*.test.ts-alwaysApply: false------## ๐๏ธ ๆฐๆฎๅบ Model ๆต่ฏๆๅ--ๆต่ฏ `packages/database` ไธ็ๆฐๆฎๅบ Model ๅฑใ--### ๆต่ฏ็ฏๅข้ๆฉ ๐ก--ๆฐๆฎๅบ Model ๅฑ้่ฟ็ฏๅขๅ้ๆงๅถๆฐๆฎๅบ็ฑปๅ๏ผๅจไธค็งๆต่ฏ็ฏๅขไธๆไธๅ็ๆฐๆฎๅบๅ็ซฏ๏ผๅฎขๆท็ซฏ็ฏๅข (PGLite) ๅ ๆๅก็ซฏ็ฏๅข (PostgreSQL)--### โ ๏ธ ๅ็ฏๅข้ช่ฏ่ฆๆฑ--**ๅฏนไบๆๆ Model ๆต่ฏ๏ผๅฟ ้กปๅจไธคไธช็ฏๅขไธ้ฝ้ช่ฏ้่ฟ**๏ผ--#### ๅฎๆด้ช่ฏๆต็จ--```bash-# 1. ๅ ๅจๅฎขๆท็ซฏ็ฏๅขๆต่ฏ๏ผๅฟซ้้ช่ฏ๏ผ-cd packages/database && TEST_SERVER_DB=0 bunx vitest run --silent='passed-only' src/database/models/__tests__/myModel.test.ts--# 2. ๅๅจๆๅก็ซฏ็ฏๅขๆต่ฏ๏ผๅ ผๅฎนๆง้ช่ฏ๏ผ, ้่ฆ่ฎพ็ฝฎ็ฏๅขๅ้ `TEST_SERVER_DB=1`-cd packages/database && TEST_SERVER_DB=1 bunx vitest run --silent='passed-only' src/database/models/__tests__/myModel.test.ts #-```--### ๅๅปบๆฐ Model ๆต่ฏ็ๆไฝณๅฎ่ทต ๐--#### 1. ๅ่็ฐๆๅฎ็ฐๅๆต่ฏๆจกๆฟ--ๅๅปบๆฐ Model ๆต่ฏๅ๏ผ**ๅฟ ้กปๅ ๅ่็ฐๆ็ๅฎ็ฐๆจกๅผ**๏ผ--- **Model ๅฎ็ฐๅ่**:-- **ๆต่ฏๆจกๆฟๅ่**:-- **ๅคๆ็คบไพๅ่**:--#### 2. ็จๆทๆ้ๆฃๆฅ - ๅฎๅ จ็ฌฌไธ ๐--่ฟๆฏ**ๆๅ ณ้ฎ็ๅฎๅ จ่ฆๆฑ**ใๆๆๆถๅ็จๆทๆฐๆฎ็ๆไฝ้ฝๅฟ ้กปๅ ๅซ็จๆทๆ้ๆฃๆฅ๏ผ--**โ ้่ฏฏ็คบไพ - ๅญๅจๅฎๅ จๆผๆด**:--```typescript-// ๅฑ้ฉ๏ผ็ผบๅฐ็จๆทๆ้ๆฃๆฅ๏ผไปปไฝ็จๆท้ฝ่ฝๆไฝไปปไฝๆฐๆฎ-update = async (id: string, data: Partial<MyModel>) => {- return this.db- .update(myTable)- .set(data)- .where(eq(myTable.id, id)) // โ ๅชๆฃๆฅ ID๏ผๆฒกๆๆฃๆฅ userId- .returning();-};-```--**โ ๆญฃ็กฎ็คบไพ - ๅฎๅ จ็ๅฎ็ฐ**:--```typescript-// ๅฎๅ จ๏ผๅฟ ้กปๅๆถๅน้ ID ๅ userId-update = async (id: string, data: Partial<MyModel>) => {- return this.db- .update(myTable)- .set(data)- .where(- and(- eq(myTable.id, id),- eq(myTable.userId, this.userId), // โ ็จๆทๆ้ๆฃๆฅ- ),- )- .returning();-};-```--**ๅฟ ้กป่ฟ่ก็จๆทๆ้ๆฃๆฅ็ๆนๆณ**๏ผ--- `update()` - ๆดๆฐๆไฝ-- `delete()` - ๅ ้คๆไฝ-- `findById()` - ๆฅๆพ็นๅฎ่ฎฐๅฝ-- ไปปไฝๆถๅ็นๅฎ่ฎฐๅฝ็ๆฅ่ฏขๆไฟฎๆนๆไฝ--#### 3. ๆต่ฏๆไปถ็ปๆๅๅฟ ๆตๅบๆฏ--**ๅบๆฌๆต่ฏ็ปๆ**:--```typescript-// @vitest-environment node-describe('MyModel', () => {- describe('create', () => {- it('should create a new record');- it('should handle edge cases');- });-- describe('queryAll', () => {- it('should return records for current user only');- it('should handle empty results');- });-- describe('update', () => {- it('should update own records');- it('should NOT update other users records'); // ๐ ๅฎๅ จๆต่ฏ- });-- describe('delete', () => {- it('should delete own records');- it('should NOT delete other users records'); // ๐ ๅฎๅ จๆต่ฏ- });-- describe('user isolation', () => {- it('should enforce user data isolation'); // ๐ ๆ ธๅฟๅฎๅ จๆต่ฏ- });-});-```--**ๅฟ ้กปๆต่ฏ็ๅฎๅ จๅบๆฏ** ๐:--```typescript-it('should not update records of other users', async () => {- // ๅๅปบๅ ถไป็จๆท็่ฎฐๅฝ- const [otherUserRecord] = await serverDB- .insert(myTable)- .values({ userId: 'other-user', data: 'original' })- .returning();-- // ๅฐ่ฏๆดๆฐๅ ถไป็จๆท็่ฎฐๅฝ- const result = await myModel.update(otherUserRecord.id, { data: 'hacked' });-- // ๅบ่ฏฅ่ฟๅ undefined ๆ็ฉบๆฐ็ป๏ผๅ ไธบๆ้ๆฃๆฅๅคฑ่ดฅ๏ผ- expect(result).toBeUndefined();-- // ้ช่ฏๅๅงๆฐๆฎๆช่ขซไฟฎๆน- const unchanged = await serverDB.query.myTable.findFirst({- where: eq(myTable.id, otherUserRecord.id),- });- expect(unchanged?.data).toBe('original'); // ๆฐๆฎๅบ่ฏฅไฟๆไธๅ-});-```--#### 4. Mock ๅค้จไพ่ตๆๅก--ๅฆๆ Model ไพ่ตๅค้จๆๅก๏ผๅฆ FileService๏ผ๏ผ้่ฆๆญฃ็กฎ Mock๏ผ--**่ฎพ็ฝฎ Mock**:--```typescript-// ๅจๆไปถ้กถ้จ่ฎพ็ฝฎ Mock-const mockGetFullFileUrl = vi.fn();-vi.mock('@/server/services/file', () => ({- FileService: vi.fn().mockImplementation(() => ({- getFullFileUrl: mockGetFullFileUrl,- })),-}));--// ๅจ beforeEach ไธญ้็ฝฎๅ้ ็ฝฎ Mock-beforeEach(async () => {- vi.clearAllMocks();- mockGetFullFileUrl.mockImplementation((url: string) => `https://example.com/${url}`);-});-```--**้ช่ฏ Mock ่ฐ็จ**:--```typescript-it('should process URLs through FileService', async () => {- // ... ๆต่ฏ้ป่พ-- // ้ช่ฏ Mock ่ขซๆญฃ็กฎ่ฐ็จ- expect(mockGetFullFileUrl).toHaveBeenCalledWith('expected-url');- expect(mockGetFullFileUrl).toHaveBeenCalledTimes(1);-});-```--#### 5. ๆฐๆฎๅบ็ถๆ็ฎก็--**ๆญฃ็กฎ็ๆฐๆฎๆธ ็ๆจกๅผ**:--```typescript-const userId = 'test-user';-const otherUserId = 'other-user';--beforeEach(async () => {- // ๆธ ็็จๆท่กจ๏ผ็บง่ๅ ้ค็ธๅ ณๆฐๆฎ๏ผ- await serverDB.delete(users);-- // ๅๅปบๆต่ฏ็จๆท- await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);-});--afterEach(async () => {- // ๆธ ็ๆต่ฏๆฐๆฎ- await serverDB.delete(users);-});-```--#### 6. ๆต่ฏๆฐๆฎ็ฑปๅๅๅค้ฎ็บฆๆๅค็ โ ๏ธ--**ๅฟ ้กปไฝฟ็จ Schema ๅฏผๅบ็็ฑปๅ**:--```typescript-// โ ๆญฃ็กฎ๏ผไฝฟ็จ schema ๅฏผๅบ็็ฑปๅ-import { NewGeneration, NewGenerationBatch } from '../../schemas';--const testBatch: NewGenerationBatch = {- userId,- generationTopicId: 'test-topic-id',- provider: 'test-provider',- model: 'test-model',- prompt: 'Test prompt for image generation',- width: 1024,- height: 1024,- config: {- /* ... */- },-};--const testGeneration: NewGeneration = {- id: 'test-gen-id',- generationBatchId: 'test-batch-id',- asyncTaskId: null, // ๅค็ๅค้ฎ็บฆๆ- fileId: null, // ๅค็ๅค้ฎ็บฆๆ- seed: 12345,- userId,-};-```--```typescript-// โ ้่ฏฏ๏ผๆฒกๆ็ฑปๅๅฃฐๆๆไฝฟ็จ้่ฏฏ็ฑปๅ-const testBatch = {- // ็ผบๅฐ็ฑปๅๅฃฐๆ- generationTopicId: 'test-topic-id',- // ...-};--const testGeneration = {- // ็ผบๅฐ็ฑปๅๅฃฐๆ- asyncTaskId: 'invalid-uuid', // ๅค้ฎ็บฆๆ้่ฏฏ- fileId: 'non-existent-file', // ๅค้ฎ็บฆๆ้่ฏฏ- // ...-};-```--**ๅค้ฎ็บฆๆๅค็็ญ็ฅ**:--1. **ไฝฟ็จ null ๅผ**: ๅฏนไบๅฏ้็ๅค้ฎๅญๆฎต๏ผไฝฟ็จ null ้ฟๅ ็บฆๆ้่ฏฏ-2. **ๅๅปบๅ ณ่่ฎฐๅฝ**: ๅฆๆ้่ฆๆต่ฏๅ ณ่ๅ ณ็ณป๏ผๅ ๅๅปบ่ขซๅผ็จ็่ฎฐๅฝ-3. **็่งฃ็บฆๆๅ ณ็ณป**: ไบ่งฃๅชไบๅญๆฎตๆๅค้ฎ็บฆๆ๏ผ้ฟๅ ๅผ็จไธๅญๅจ็่ฎฐๅฝ--```typescript-// ๅค้ฎ็บฆๆๅค็็คบไพ-beforeEach(async () => {- // ๆธ ็ๆฐๆฎๅบ- await serverDB.delete(users);-- // ๅๅปบๆต่ฏ็จๆท- await serverDB.insert(users).values([{ id: userId }]);-- // ๅฆๆ้่ฆๆต่ฏๆไปถๅ ณ่๏ผๅๅปบๆไปถ่ฎฐๅฝ- if (needsFileAssociation) {- await serverDB.insert(files).values({- id: 'test-file-id',- userId,- name: 'test.jpg',- url: 'test-url',- size: 1024,- fileType: 'image/jpeg',- });- }-});-```--**ๆๅบๆต่ฏ็ๅฏ้ขๆตๆง**:--```typescript-// โ ๆญฃ็กฎ๏ผไฝฟ็จๆ็กฎ็ๆถ้ดๆณ็กฎไฟๆๅบ็ปๆๅฏ้ขๆต-it('should find batches by topic id in correct order', async () => {- const oldDate = new Date('2024-01-01T10:00:00Z');- const newDate = new Date('2024-01-02T10:00:00Z');-- const batch1 = { ...testBatch, prompt: 'First batch', userId, createdAt: oldDate };- const batch2 = { ...testBatch, prompt: 'Second batch', userId, createdAt: newDate };-- await serverDB.insert(generationBatches).values([batch1, batch2]);-- const results = await generationBatchModel.findByTopicId(testTopic.id);-- expect(results[0].prompt).toBe('Second batch'); // ๆๆฐไผๅ (desc order)- expect(results[1].prompt).toBe('First batch');-});-```--```typescript-// โ ้่ฏฏ๏ผไพ่ตๆฐๆฎๅบ็้ป่ฎคๆถ้ดๆณ๏ผ็ปๆไธๅฏ้ขๆต-it('should find batches by topic id', async () => {- const batch1 = { ...testBatch, prompt: 'First batch', userId };- const batch2 = { ...testBatch, prompt: 'Second batch', userId };-- await serverDB.insert(generationBatches).values([batch1, batch2]);-- // ๆๅ ฅ้กบๅบๅๆฐๆฎๅบๆถ้ดๆณๅฏ่ฝไธไธ่ด๏ผๅฏผ่ดๆต่ฏไธ็จณๅฎ- const results = await generationBatchModel.findByTopicId(testTopic.id);- expect(results[0].prompt).toBe('Second batch'); // ๅฏ่ฝๅคฑ่ดฅ-});-```--### ๅธธ่ง้ฎ้ขๅ่งฃๅณๆนๆก ๐ก--#### ้ฎ้ข 1๏ผๆ้ๆฃๆฅ็ผบๅคฑๅฏผ่ดๅฎๅ จๆผๆด--**็ฐ่ฑก**: ๆต่ฏๅคฑ่ดฅ๏ผ็จๆท่ฝไฟฎๆนๅ ถไป็จๆท็ๆฐๆฎ **่งฃๅณ**: ๅจ Model ็ `update` ๅ `delete` ๆนๆณไธญๆทปๅ `and(eq(table.id, id), eq(table.userId, this.userId))`--#### ้ฎ้ข 2๏ผMock ๆช็ๆๆ้ช่ฏๅคฑ่ดฅ--**็ฐ่ฑก**: `undefined is not a spy` ้่ฏฏ **่งฃๅณ**: ๆฃๆฅ Mock ่ฎพ็ฝฎไฝ็ฝฎๅๆนๅผ๏ผ็กฎไฟๅจๆต่ฏๆไปถ้กถ้จ่ฎพ็ฝฎ๏ผๅจ `beforeEach` ไธญ้็ฝฎ--#### ้ฎ้ข 3๏ผๆต่ฏๆฐๆฎๆฑกๆ--**็ฐ่ฑก**: ๆต่ฏ้ด็ธไบๅฝฑๅ๏ผ็ปๆไธ็จณๅฎ **่งฃๅณ**: ๅจ `beforeEach` ๅ `afterEach` ไธญๆญฃ็กฎๆธ ็ๆฐๆฎๅบ็ถๆ--#### ้ฎ้ข 4๏ผๅค้จไพ่ตๅฏผ่ดๆต่ฏๅคฑ่ดฅ--**็ฐ่ฑก**: ๅ ไธบ็ๅฎ็ๅค้จๆๅก่ฐ็จๅฏผ่ดๆต่ฏไธ็จณๅฎ **่งฃๅณ**: Mock ๆๆๅค้จไพ่ต๏ผไฝฟๆต่ฏๆดๅฏๆงๅๅฟซ้--#### ้ฎ้ข 5๏ผๅค้ฎ็บฆๆ่ฟๅๅฏผ่ดๆต่ฏๅคฑ่ดฅ--**็ฐ่ฑก**: `insert or update on table "xxx" violates foreign key constraint` **่งฃๅณ**:--- ๅฐๅฏ้ๅค้ฎๅญๆฎต่ฎพไธบ `null` ่ไธๆฏๆ ๆ็ๅญ็ฌฆไธฒๅผ-- ๆ่ ๅ ๅๅปบ่ขซๅผ็จ็่ฎฐๅฝ๏ผๅๅๅปบๅฝๅ่ฎฐๅฝ--```typescript-// โ ้่ฏฏ๏ผๆ ๆ็ๅค้ฎๅผ-const testData = {- asyncTaskId: 'invalid-uuid', // ่กจไธญไธๅญๅจๆญค่ฎฐๅฝ- fileId: 'non-existent-file', // ่กจไธญไธๅญๅจๆญค่ฎฐๅฝ-};--// โ ๆญฃ็กฎ๏ผไฝฟ็จ null ๅผ-const testData = {- asyncTaskId: null, // ้ฟๅ ๅค้ฎ็บฆๆ- fileId: null, // ้ฟๅ ๅค้ฎ็บฆๆ-};--// โ ๆ่ ๏ผๅ ๅๅปบ่ขซๅผ็จ็่ฎฐๅฝ-beforeEach(async () => {- const [asyncTask] = await serverDB.insert(asyncTasks).values({- id: 'valid-task-id',- status: 'pending',- type: 'generation',- }).returning();-- const testData = {- asyncTaskId: asyncTask.id, // ไฝฟ็จๆๆ็ๅค้ฎๅผ- };-});-```--#### ้ฎ้ข 6๏ผๆๅบๆต่ฏ็ปๆไธไธ่ด--**็ฐ่ฑก**: ็ธๅ็ๆต่ฏๆๆถ้่ฟ๏ผๆๆถๅคฑ่ดฅ๏ผ็นๅซๆฏๆถๅๆๅบ็ๆต่ฏ **่งฃๅณ**: ไฝฟ็จๆ็กฎ็ๆถ้ดๆณ๏ผไธ่ฆไพ่ตๆฐๆฎๅบ็้ป่ฎคๆถ้ดๆณ--```typescript-// โ ้่ฏฏ๏ผไพ่ตๆๅ ฅ้กบๅบๅ้ป่ฎคๆถ้ดๆณ-await serverDB.insert(table).values([data1, data2]); // ๆถ้ดๆณไธๅฏ้ขๆต--// โ ๆญฃ็กฎ๏ผๆ็กฎๆๅฎๆถ้ดๆณ-const oldDate = new Date('2024-01-01T10:00:00Z');-const newDate = new Date('2024-01-02T10:00:00Z');-await serverDB.insert(table).values([- { ...data1, createdAt: oldDate },- { ...data2, createdAt: newDate },-]);-```--#### ้ฎ้ข 7๏ผMock ้ช่ฏๅคฑ่ดฅๆ่ฐ็จๆฌกๆฐไธๅน้ --**็ฐ่ฑก**: `expect(mockFunction).toHaveBeenCalledWith(...)` ๅคฑ่ดฅ **่งฃๅณ**:--- ๆฃๆฅ Mock ๅฝๆฐ็ๅฎ้ ่ฐ็จๅๆฐๅๆๆๅๆฐๆฏๅฆๅฎๅ จๅน้ -- ็กฎ่ฎค Mock ๅจๆญฃ็กฎ็ๆถๆบ่ขซ้็ฝฎๅ้ ็ฝฎ-- ไฝฟ็จ `toHaveBeenCalledTimes()` ้ช่ฏ่ฐ็จๆฌกๆฐ--```typescript-// ๅจ beforeEach ไธญๆญฃ็กฎ้ ็ฝฎ Mock-beforeEach(() => {- vi.clearAllMocks(); // ้็ฝฎๆๆ Mock-- mockGetFullFileUrl.mockImplementation((url: string) => `https://example.com/${url}`);- mockTransformGeneration.mockResolvedValue({- id: 'test-id',- // ... ๅ ถไปๅญๆฎต- });-});--// ๆต่ฏไธญ้ช่ฏ Mock ่ฐ็จ-it('should call FileService with correct parameters', async () => {- await model.someMethod();-- // ้ช่ฏ่ฐ็จๅๆฐ- expect(mockGetFullFileUrl).toHaveBeenCalledWith('expected-url');- // ้ช่ฏ่ฐ็จๆฌกๆฐ- expect(mockGetFullFileUrl).toHaveBeenCalledTimes(1);-});-```--### Model ๆต่ฏๆฃๆฅๆธ ๅ โ--ๅๅปบ Model ๆต่ฏๆถ๏ผ่ฏท็กฎไฟไปฅไธๅ้กน้ฝๅทฒๅฎๆ๏ผ--#### ๐ง ๅบ็ก้ ็ฝฎ--- [ ] **ๅ็ฏๅข้ช่ฏ** - ๅจๅฎขๆท็ซฏ็ฏๅข (vitest.config.ts) ๅๆๅก็ซฏ็ฏๅข (vitest.config.server.ts) ไธ้ฝๆต่ฏ้่ฟ-- [ ] ๅ่ไบ `_template.ts` ๅ็ฐๆ Model ็ๅฎ็ฐๆจกๅผ-- [ ] **ไฝฟ็จๆญฃ็กฎ็ Schema ็ฑปๅ** - ๆต่ฏๆฐๆฎไฝฟ็จ `NewXxx` ็ฑปๅๅฃฐๆ๏ผๅฆ `NewGenerationBatch`ใ`NewGeneration`--#### ๐ ๅฎๅ จๆต่ฏ--- [ ] **ๆๆๆถๅ็จๆทๆฐๆฎ็ๆไฝ้ฝๅ ๅซ็จๆทๆ้ๆฃๆฅ**-- [ ] ๅ ๅซไบ็จๆทๆ้้็ฆป็ๅฎๅ จๆต่ฏ-- [ ] ๆต่ฏไบ็จๆทๆ ๆณ่ฎฟ้ฎๅ ถไป็จๆทๆฐๆฎ็ๅบๆฏ--#### ๐๏ธ ๆฐๆฎๅค็--- [ ] **ๆญฃ็กฎๅค็ๅค้ฎ็บฆๆ** - ไฝฟ็จ `null` ๅผๆๅ ๅๅปบ่ขซๅผ็จ่ฎฐๅฝ-- [ ] **ๆๅบๆต่ฏไฝฟ็จๆ็กฎๆถ้ดๆณ** - ไธไพ่ตๆฐๆฎๅบ้ป่ฎคๆถ้ด๏ผ็กฎไฟ็ปๆๅฏ้ขๆต-- [ ] ๅจ `beforeEach` ๅ `afterEach` ไธญๆญฃ็กฎ็ฎก็ๆฐๆฎๅบ็ถๆ-- [ ] ๆๆๆต่ฏ้ฝ่ฝ็ฌ็ซ่ฟ่กไธไบไธๅนฒๆฐ--#### ๐ญ Mock ๅๅค้จไพ่ต--- [ ] ๆญฃ็กฎ Mock ไบๅค้จไพ่ตๆๅก (ๅฆ FileServiceใGenerationModel)-- [ ] ๅจ `beforeEach` ไธญ้็ฝฎๅ้ ็ฝฎ Mock-- [ ] ้ช่ฏไบ Mock ๆๅก็่ฐ็จๅๆฐๅๆฌกๆฐ-- [ ] ๆต่ฏไบๅค้จๆๅก้่ฏฏๅบๆฏ็ๅค็--#### ๐ ๆต่ฏ่ฆ็--- [ ] ๆต่ฏ่ฆ็ไบๆๆไธป่ฆๆนๆณ (create, query, update, delete)-- [ ] ๆต่ฏไบ่พน็ๆกไปถๅ้่ฏฏๅบๆฏ-- [ ] ๅ ๅซไบ็ฉบ็ปๆๅค็็ๆต่ฏ-- [ ] **็กฎ่ฎคไธคไธช็ฏๅขไธ็ๆต่ฏ็ปๆไธ่ด**--#### ๐จ ๅธธ่ง้ฎ้ขๆฃๆฅ--- [ ] ๆฒกๆๅค้ฎ็บฆๆ่ฟๅ้่ฏฏ-- [ ] ๆๅบๆต่ฏ็ปๆ็จณๅฎๅฏ้ขๆต-- [ ] Mock ้ช่ฏๆ ๅคฑ่ดฅ-- [ ] ๆ ๆต่ฏๆฐๆฎๆฑกๆ้ฎ้ข--### ๅฎๅ จ่ญฆๅ โ ๏ธ--**ๆฐๆฎๅบ Model ๅฑๆฏๅฎๅ จ็็ฌฌไธ้้ฒ็บฟ**ใๅฆๆ Model ๅฑ็ผบๅฐ็จๆทๆ้ๆฃๆฅ๏ผ--1. **ไปปไฝ็จๆท้ฝ่ฝ่ฎฟ้ฎๅไฟฎๆนๅ ถไป็จๆท็ๆฐๆฎ**-2. **ๅณไฝฟไธๅฑๆๆ้ๆฃๆฅ๏ผไนๅฏ่ฝ่ขซ็ป่ฟ**-3. **ๅฏ่ฝๅฏผ่ดไธฅ้็ๆฐๆฎๆณ้ฒๅๅฎๅ จไบๆ **--ๅ ๆญค๏ผ**ๆฏไธชๆถๅ็จๆทๆฐๆฎ็ Model ๆนๆณ้ฝๅฟ ้กปๅ ๅซ็จๆทๆ้ๆฃๆฅ๏ผไธๅฟ ้กปๆๅฏนๅบ็ๅฎๅ จๆต่ฏๆฅ้ช่ฏ่ฟไบๆฃๆฅ็ๆๆๆง**ใdiff --git a/.cursor/rules/testing-guide/electron-ipc-test.mdc b/.cursor/rules/testing-guide/electron-ipc-test.mdcdeleted file mode 100644index 4a91aa1aa19..00000000000--- a/.cursor/rules/testing-guide/electron-ipc-test.mdc+++ /dev/null@@ -1,80 +0,0 @@-----description: Electron IPC ๆฅๅฃๆต่ฏ็ญ็ฅ-alwaysApply: false------### Electron IPC ๆฅๅฃๆต่ฏ็ญ็ฅ ๐ฅ๏ธ--ๅฏนไบๆถๅ Electron IPC ๆฅๅฃ็ๆต่ฏ๏ผ็ฑไบๆไพ็ๅฎ็ Electron ็ฏๅขๆฏ่พๅคๆ๏ผ้็จ **Mock ่ฟๅๅผ** ็ๆนๅผ่ฟ่กๆต่ฏใ--#### ๅบๆฌ Mock ่ฎพ็ฝฎ--```typescript-import { vi } from 'vitest';--import { electronIpcClient } from '@/server/modules/ElectronIPCClient';--// Mock Electron IPC ๅฎขๆท็ซฏ-vi.mock('@/server/modules/ElectronIPCClient', () => ({- electronIpcClient: {- getFilePathById: vi.fn(),- deleteFiles: vi.fn(),- // ๆ นๆฎ้่ฆๆทปๅ ๅ ถไป IPC ๆนๆณ- },-}));-```--#### ๅจๆต่ฏไธญ่ฎพ็ฝฎ Mock ่กไธบ--```typescript-beforeEach(() => {- // ้็ฝฎๆๆ Mock- vi.resetAllMocks();-- // ่ฎพ็ฝฎ้ป่ฎค็ Mock ่ฟๅๅผ- vi.mocked(electronIpcClient.getFilePathById).mockResolvedValue('/path/to/file.txt');- vi.mocked(electronIpcClient.deleteFiles).mockResolvedValue({- success: true,- });-});-```--#### ๆต่ฏไธๅๅบๆฏ็็คบไพ--```typescript-it('ๅบ่ฏฅๅค็ๆไปถๅ ้คๆๅ็ๆ ๅต', async () => {- // ่ฎพ็ฝฎๆๅๅบๆฏ็ Mock- vi.mocked(electronIpcClient.deleteFiles).mockResolvedValue({- success: true,- });-- const result = await service.deleteFiles(['desktop://file1.txt']);-- expect(electronIpcClient.deleteFiles).toHaveBeenCalledWith(['desktop://file1.txt']);- expect(result.success).toBe(true);-});--it('ๅบ่ฏฅๅค็ๆไปถๅ ้คๅคฑ่ดฅ็ๆ ๅต', async () => {- // ่ฎพ็ฝฎๅคฑ่ดฅๅบๆฏ็ Mock- vi.mocked(electronIpcClient.deleteFiles).mockRejectedValue(new Error('ๅ ้คๅคฑ่ดฅ'));-- const result = await service.deleteFiles(['desktop://file1.txt']);-- expect(result.success).toBe(false);- expect(result.errors).toBeDefined();-});-```--#### Mock ็ญ็ฅ็ไผๅฟ--1. **็ฏๅข็ฎๅ**: ้ฟๅ ไบๅคๆ็ Electron ็ฏๅขๆญๅปบ-2. **ๆต่ฏๅฏๆง**: ๅฏไปฅ็ฒพ็กฎๆงๅถ IPC ่ฐ็จ็่ฟๅๅผๅ่กไธบ-3. **ๅบๆฏ่ฆ็**: ๅฎนๆๆต่ฏๅ็งๆๅ/ๅคฑ่ดฅๅบๆฏ-4. **ๆง่ก้ๅบฆ**: Mock ่ฐ็จๆฏ็ๅฎ IPC ่ฐ็จๆดๅฟซ--#### ๆณจๆไบ้กน--- **Mock ๅ็กฎๆง**: ็กฎไฟ Mock ็่กไธบไธ็ๅฎ IPC ๆฅๅฃ่กไธบไธ่ด-- **็ฑปๅๅฎๅ จ**: ไฝฟ็จ `vi.mocked()` ็กฎไฟ็ฑปๅๅฎๅ จ-- **Mock ้็ฝฎ**: ๅจ `beforeEach` ไธญ้็ฝฎ Mock ็ถๆ๏ผ้ฟๅ ๆต่ฏ้ดๅนฒๆฐ-- **่ฐ็จ้ช่ฏ**: ไธไป ่ฆ้ช่ฏ่ฟๅๅผ๏ผ่ฟ่ฆ้ช่ฏ IPC ๆนๆณๆฏๅฆ่ขซๆญฃ็กฎ่ฐ็จdiff --git a/.cursor/rules/testing-guide/testing-guide.mdc b/.cursor/rules/testing-guide/testing-guide.mdcdeleted file mode 100644index 0180eb211fa..00000000000--- a/.cursor/rules/testing-guide/testing-guide.mdc+++ /dev/null@@ -1,534 +0,0 @@-----globs: *.test.ts,*.test.tsx-alwaysApply: false------# LobeChat Testing Guide--## Test Overview--LobeChat testing consists of **E2E tests** and **Unit tests**. This guide focuses on **Unit tests**.--Unit tests are organized into three main categories:--```plaintext-+---------------------+---------------------------+-----------------------------+-| Category | Location | Config File |-+---------------------+---------------------------+-----------------------------+-| Next.js Webapp | src/**/*.test.ts(x) | vitest.config.ts |-| Packages | packages/*/**/*.test.ts | packages/*/vitest.config.ts |-| Desktop App | apps/desktop/**/*.test.ts | apps/desktop/vitest.config.ts |-+---------------------+---------------------------+-----------------------------+-```--### Next.js Webapp Tests--- **Config File**: `vitest.config.ts`-- **Environment**: Happy DOM (browser environment simulation)-- **Database**: PGLite (PostgreSQL for browser environments)-- **Setup File**: `tests/setup.ts`-- **Purpose**: Testing React components, hooks, stores, utilities, and client-side logic--### Packages Tests--Most packages use standard Vitest configuration. However, the `database` package is special:--#### Database Package (Special Case)--The database package supports **dual-environment testing**:--| Environment | Database | Config | Use Case |-|------------------|-----------------|---------------------------------------|-----------------------------------|-| Client (Default) | PGLite | `packages/database/vitest.config.mts` | Fast local development |-| Server | Real PostgreSQL | Set `TEST_SERVER_DB=1` | CI/CD, compatibility verification |--Server environment details:--- **Concurrency**: Single-threaded (`singleFork: true`)-- **Setup File**: `packages/database/tests/setup-db.ts`-- **Requirement**: `DATABASE_TEST_URL` environment variable must be set--### Desktop App Tests--- **Config File**: `apps/desktop/vitest.config.ts`-- **Environment**: Node.js-- **Purpose**: Testing Electron main process controllers, IPC handlers, and desktop-specific logic--## Test Commands--**Performance Warning**: The project contains 3000+ test cases. A full run takes approximately 10 minutes. Always use file filtering or test name filtering.--### Recommended Command Format--```bash-# Run all client/server tests-bunx vitest run --silent='passed-only' # Client tests-cd packages/database && TEST_SERVER_DB=1 bunx vitest run --silent='passed-only' # Server tests--# Run specific test file (supports fuzzy matching)-bunx vitest run --silent='passed-only' user.test.ts--# Run specific test case by name (using -t flag)-bunx vitest run --silent='passed-only' -t "test case name"--# Combine file and test name filtering-bunx vitest run --silent='passed-only' filename.test.ts -t "specific test"--# Generate coverage report (using --coverage flag)-bunx vitest run --silent='passed-only' --coverage-```--### Commands to Avoid--```bash-# โ These commands run all 3000+ test cases, taking ~10 minutes!-npm test-npm test some-file.test.ts--# โ Don't use bare vitest (enters watch mode)-vitest test-file.test.ts-```--## Test Fixing Principles--### Core Principles--1. **Gather Sufficient Context**- Before fixing tests, ensure you:- - Fully understand the test's intent and implementation- - Strongly recommended: review the current git diff and PR diff--2. **Prioritize Test Fixes**- If the test itself is incorrect, fix the test first rather than the implementation code.--3. **Focus on a Single Issue**- Only fix the specified test; don't add extra tests along the way.--4. **Don't Act Unilaterally**- When discovering other issues, don't modify them directlyโraise and discuss first.--### Testing Collaboration Best Practices--Important collaboration principles based on real development experience:--#### 1. Failure Handling Strategy--**Core Principle**: Avoid blind retries; quickly identify problems and seek help.--- **Failure Threshold**: After 1-2 consecutive failed fix attempts, stop immediately-- **Problem Summary**: Analyze failure reasons and document attempted solutions with their failure causes-- **Seek Help**: Approach the team with a clear problem summary and attempt history-- **Avoid the Trap**: Don't fall into the loop of repeatedly trying the same or similar approaches--```typescript-// โ Wrong approach: Keep blindly trying after consecutive failures-// 3rd, 4th attempts still using similar methods to fix the same problem--// โ Correct approach: Summarize after 1-2 failures-/*-Problem Summary:-1. Attempted method: Modified mock data structure-2. Failure reason: Still getting type mismatch error-3. Specific error: Expected 'UserData' but received 'UserProfile'-4. Help needed: Unsure about the latest UserData interface definition-*/-```--#### 2. Test Case Naming Conventions--**Core Principle**: Tests should focus on "behavior," not "implementation details."--- **Describe Business Scenarios**: `describe` and `it` titles should describe specific business scenarios and expected behaviors-- **Avoid Implementation Binding**: Don't mention specific line numbers, coverage goals, or implementation details in test names-- **Maintain Stability**: Test names should remain meaningful after code refactoring--```typescript-// โ Poor test naming-describe('User component coverage', () => {- it('covers line 45-50 in getUserData', () => {- // Test written just to cover lines 45-50- });-- it('tests the else branch', () => {- // Exists only to test a specific branch- });-});--// โ Good test naming-describe('<UserAvatar />', () => {- it('should render fallback icon when image url is not provided', () => {- // Tests a specific business scenario, naturally covering relevant code branches- });-- it('should display user initials when avatar image fails to load', () => {- // Describes user behavior and expected outcome- });-});-```--**The Right Approach to Improving Coverage**:--- Naturally improve coverage by designing various business scenarios (happy paths, edge cases, error handling)-- Don't write tests just to hit coverage numbers, and never comment "to cover line xxx" in tests--#### 3. Test Organization Structure--**Core Principle**: Maintain a clear test hierarchy; avoid redundant top-level test blocks.--- **Reuse Existing Structure**: When adding new tests, first look for an appropriate place in existing `describe` blocks-- **Logical Grouping**: Related test cases should be organized within the same `describe` block-- **Avoid Fragmentation**: Don't create a new top-level `describe` block for a single test case--```typescript-// โ Poor organization: Too many top-level blocks-describe('<UserProfile />', () => {- it('should render user name', () => {});-});--describe('UserProfile new prop test', () => {- // Unnecessary new block- it('should handle email display', () => {});-});--describe('UserProfile edge cases', () => {- // Unnecessary new block- it('should handle missing avatar', () => {});-});--// โ Good organization: Merge related tests-describe('<UserProfile />', () => {- it('should render user name', () => {});-- it('should handle email display', () => {});-- it('should handle missing avatar', () => {});-- describe('when user data is incomplete', () => {- // Only create sub-groups when there are multiple related sub-scenarios- it('should show placeholder for missing name', () => {});- it('should hide email section when email is undefined', () => {});- });-});-```--**Organization Decision Flow**:--1. Is there a logically related existing `describe` block? โ If yes, add to it-2. Are there multiple (3+) related test cases? โ If yes, consider creating a new sub-`describe`-3. Is it an independent, unrelated feature module? โ Only then consider creating a new top-level `describe`--### Test Fixing Workflow--1. **Reproduce the Issue**: Locate and run the failing test; confirm it can be reproduced locally-2. **Analyze the Cause**: Read test code, error logs, and Git history of related files-3. **Form a Hypothesis**: Determine if the problem is in test logic, implementation code, or environment configuration-4. **Fix and Verify**: Apply the fix based on your hypothesis; rerun the test to confirm it passes-5. **Expand Verification**: Run all tests in the current file to ensure no new issues were introduced-6. **Write a Summary**: Document the error cause and fix method--### Post-Fix Summary--After completing a test fix, provide a brief explanation including:--1. **Root Cause Analysis**: Explain the fundamental reason for the test failure- - Test logic error- - Implementation bug- - Environment configuration issue- - Dependency change--2. **Fix Description**: Briefly describe the fix approach- - Which files were modified- - What solution was applied- - Why this fix approach was chosen--**Example Format**:--```markdown-## Test Fix Summary--**Root Cause**: The mock data format in the test didn't match the actual API response format, causing assertion failures.--**Fix**: Updated the mock data structure in the test file to match the latest API response format. Specifically modified the `mockUserData` object structure in `user.test.ts`.-```--## Test Writing Best Practices--### Mock Data Strategy: Aim for "Low-Cost Authenticity"--**Core Principle**: Test data should default to authenticity; only simplify when it introduces "high testing costs."--#### What Are "High Testing Costs"?--"High cost" refers to introducing external dependencies in tests that make them slow, unstable, or complex:--- **File I/O Operations**: Reading/writing disk files-- **Network Requests**: HTTP calls, database connections-- **System Calls**: Getting system time, environment variables, etc.--#### Recommended Approach: Mock Dependencies, Keep Real Data--```typescript-// โ Good approach: Mock I/O operations but use real file content formats-describe('parseContentType', () => {- beforeEach(() => {- // Mock file read operation (avoid real I/O)- vi.spyOn(fs, 'readFileSync').mockImplementation((path) => {- // But return real file content formats- if (path.includes('.pdf')) return '%PDF-1.4\n%รขรฃรร'; // Real PDF header- if (path.includes('.png')) return '\x89PNG\r\n\x1a\n'; // Real PNG header- return '';- });- });-- it('should detect PDF content type correctly', () => {- const result = parseContentType('/path/to/file.pdf');- expect(result).toBe('application/pdf');- });-});--// โ Over-simplified: Using unrealistic data-describe('parseContentType', () => {- it('should detect PDF content type correctly', () => {- // This simplified data has no test value- const result = parseContentType('fake-pdf-content');- expect(result).toBe('application/pdf');- });-});-```--#### The Value of Real Identifiers--```typescript-// โ Use real identifiers-const result = parseModelString('openai', '+gpt-4,+gpt-3.5-turbo');--// โ Use placeholders (lower value)-const result = parseModelString('test-provider', '+model1,+model2');-```--### Modern Mocking Techniques: Environment Setup and Mock Methods--When testing client-side code, use environment annotations with modern mock methods:--```typescript-/**- * @vitest-environment happy-dom // Provides browser APIs- */-import { beforeEach, vi } from 'vitest';--beforeEach(() => {- // Modern method 1: Use vi.stubGlobal instead of global.xxx = ...- const mockImage = vi.fn().mockImplementation(() => ({- addEventListener: vi.fn(),- naturalHeight: 600,- naturalWidth: 800,- }));- vi.stubGlobal('Image', mockImage);-- // Modern method 2: Use vi.spyOn to preserve original functionality, only mock specific methods- vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock-url');- vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});-});-```--#### Environment Selection Priority--1. **@vitest-environment happy-dom** (Recommended) - Lightweight, fast, already installed in the project-2. **@vitest-environment jsdom** - Full-featured, but requires additional jsdom package installation-3. **No environment set** - Node.js environment, requires manually mocking all browser APIs--#### Mock Method Comparison--```typescript-// โ Old method: Directly manipulating global object (type issues)-global.Image = mockImage;-global.URL = { ...global.URL, createObjectURL: mockFn };--// โ Modern method: Type-safe vi API-vi.stubGlobal('Image', mockImage); // Completely replace global object-vi.spyOn(URL, 'createObjectURL'); // Partial mock, preserve other functionality-```--### Test Coverage Principles: Code Branches Over Test Quantity--**Core Principle**: Prioritize covering all code branches rather than writing many repetitive test cases.--```typescript-// โ Over-testing: 29 test cases all validating the same branch-describe('getImageDimensions', () => {- it('should reject .txt files');- it('should reject .pdf files');- // ... 25 similar tests, all hitting the same validation branch-});--// โ Lean testing: 4 core cases covering all branches-describe('getImageDimensions', () => {- it('should return dimensions for valid File object'); // Success path - File- it('should return dimensions for valid data URI'); // Success path - String- it('should return undefined for invalid inputs'); // Input validation branch- it('should return undefined when image fails to load'); // Error handling branch-});-```--#### Branch Coverage Strategy--1. **Success Paths** - One test per input type is sufficient-2. **Boundary Conditions** - Consolidate similar scenarios into a single test-3. **Error Handling** - Test representative errors only-4. **Business Logic** - Cover all if/else branches--#### Reasonable Test Counts--- Simple utility functions: 2-5 tests-- Complex business logic: 5-10 tests-- Core security features: Add more as needed, but avoid duplicate paths--### Error Handling Tests: Test "Behavior" Not "Text"--**Core Principle**: Tests should verify that program behavior is predictable when errors occur, not verify error message text that may change.--#### Recommended Error Testing Approach--```typescript-// โ Test error types and properties-expect(() => validateUser({})).toThrow(ValidationError);-expect(() => processPayment({})).toThrow(- expect.objectContaining({- code: 'INVALID_PAYMENT_DATA',- statusCode: 400,- }),-);--// โ Avoid testing specific error text-expect(() => processUser({})).toThrow('User data cannot be empty, please check input parameters');-```--### Troubleshooting: Beware of Module Pollution--**Warning Signs**: When your tests exhibit these "mysterious" behaviors, suspect module pollution first:--- A test passes when run alone but fails when run with other tests-- Test execution order affects results-- Mock setup appears correct but actually uses an old mock version--#### Typical Scenario: Dynamic Mocking of the Same Module--```typescript-// โ Problem: Dynamic mocking of the same module-it('dev mode', async () => {- vi.doMock('./config', () => ({ isDev: true }));- const { getSettings } = await import('./service'); // May use cache-});--// โ Solution: Clear module cache-beforeEach(() => {- vi.resetModules(); // Ensure each test has a clean environment-});-```--**Remember**: `vi.resetModules()` is the ultimate weapon for resolving "mysterious" test failures.--## Test File Organization--### File Naming Convention--`*.test.ts`, `*.test.tsx` (any location)--### Test File Organization Style--The project uses a **co-located test files** organization style:--- Test files are placed in the same directory as the corresponding source files-- Naming format: `originalFileName.test.ts` or `originalFileName.test.tsx`--Example:--```plaintext-src/components/Button/-โโโ index.tsx # Source file-โโโ index.test.tsx # Test file-```--- In some cases, tests are consolidated in a `__tests__` folder, e.g., `packages/database/src/models/__tests__`-- Test helper files are placed in a fixtures folder--## Test Debugging Tips--### Test Debugging Steps--1. **Determine Test Environment**: Select the correct config file based on file path-2. **Isolate the Problem**: Use the `-t` flag to run only the failing test case-3. **Analyze the Error**: Carefully read error messages, stack traces, and recent file modification history-4. **Add Debugging**: Add `console.log` statements in tests to understand execution flow--### TypeScript Type Handling--In tests, you can relax TypeScript type checking to improve writing efficiency and readability:--#### Recommended Type Relaxation Strategies--```typescript-// Use non-null assertion to access properties you're certain exist in tests-const result = await someFunction();-expect(result!.data).toBeDefined();-expect(result!.status).toBe('success');--// Use any type to simplify complex mock setups-const mockStream = new ReadableStream() as any;-mockStream.toReadableStream = () => mockStream;--// Access private members-await instance['getFromCache']('key'); // Bracket notation recommended-await (instance as any).getFromCache('key'); // Avoid as any-```--#### Applicable Scenarios--- **Mock Objects**: Use `as any` for test mock data to avoid complex type definitions-- **Third-Party Libraries**: Use `any` appropriately when handling complex third-party library types-- **Test Assertions**: Use `!` non-null assertion in test scenarios where you're certain the object exists-- **Private Member Access**: Prefer bracket notation `instance['privateMethod']()` over `(instance as any).privateMethod()`-- **Temporary Debugging**: When quickly writing tests, use `any` first to ensure functionality, then optionally optimize types later--#### Important Notes--- **Use Moderately**: Don't over-rely on `any`; core business logic types should remain strict-- **Private Member Access Priority**: Bracket notation > `as any` casting for better type safety-- **Documentation**: Add comments explaining the reason for complex `any` usage scenarios-- **Test Coverage**: Ensure tests still effectively verify correctness even when using `any`--### Checking Recent Modifications--**Core Principle**: When tests suddenly fail, first check recent code changes.--#### Quick Check Methods--```bash-git status # View current modification status-git diff HEAD -- '*.test.*' # Check test file changes-git diff main...HEAD # Compare with main branch-gh pr diff # View all changes in the PR-```--#### Common Causes and Solutions--- **Latest commit introduced a bug** โ Check and fix the implementation code-- **Branch code is outdated** โ `git rebase main` to sync with main branch--## Special Testing Scenarios--For special testing scenarios, refer to the related rules:--- `electron-ipc-test.mdc` - Electron IPC Interface Testing Strategy-- `db-model-test.mdc` - Database Model Testing Guide--## Key Takeaways--- **Command Format**: Use `bunx vitest run --silent='passed-only'` with file filtering-- **Fix Principles**: Seek help after 1-2 failures; focus test naming on behavior, not implementation details-- **Debug Workflow**: Reproduce โ Analyze โ Hypothesize โ Fix โ Verify โ Summarize-- **File Organization**: Prefer adding tests to existing `describe` blocks; avoid creating redundant top-level blocks-- **Data Strategy**: Default to authenticity; only simplify for high-cost scenarios (I/O, network, etc.)-- **Error Testing**: Test error types and behavior; avoid depending on specific error message text-- **Module Pollution**: When tests fail "mysteriously," suspect module pollution first; use `vi.resetModules()` to resolve-- **Security Requirements**: Model tests must include permission checks and pass in both environmentsdiff --git a/.cursor/rules/testing-guide/zustand-store-action-test.mdc b/.cursor/rules/testing-guide/zustand-store-action-test.mdcdeleted file mode 100644index 2318ec7dbab..00000000000--- a/.cursor/rules/testing-guide/zustand-store-action-test.mdc+++ /dev/null@@ -1,574 +0,0 @@-----description: Best practices for testing Zustand store actions-globs: src/store/**/*.test.ts-alwaysApply: false------# Zustand Store Action Testing Guide--This guide provides best practices for testing Zustand store actions, based on our proven testing patterns.--## Basic Test Structure--```typescript-import { act, renderHook } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { messageService } from '@/services/message';--import { useChatStore } from '../../store';--// Keep zustand mock as it's needed globally-vi.mock('zustand/traditional');--beforeEach(() => {- // Reset store state- vi.clearAllMocks();- useChatStore.setState(- {- activeId: 'test-session-id',- messagesMap: {},- loadingIds: [],- },- false,- );-- // โ Setup only spies that MOST tests need- vi.spyOn(messageService, 'createMessage').mockResolvedValue('new-message-id');- // โ Don't setup spies that only few tests need - spy only when needed-- // Setup common mock methods- act(() => {- useChatStore.setState({- refreshMessages: vi.fn(),- internal_coreProcessMessage: vi.fn(),- });- });-});--afterEach(() => {- vi.restoreAllMocks();-});--describe('action name', () => {- describe('validation', () => {- // Validation tests- });-- describe('normal flow', () => {- // Happy path tests- });-- describe('error handling', () => {- // Error case tests- });-});-```--## Testing Best Practices--### 1. Test Layering - Spy Direct Dependencies Only--โ **Good**: Spy on the direct dependency--```typescript-// When testing internal_coreProcessMessage, spy its direct dependency-const fetchAIChatSpy = vi- .spyOn(result.current, 'internal_fetchAIChatMessage')- .mockResolvedValue({ isFunctionCall: false, content: 'AI response' });-```--โ **Bad**: Spy on lower-level implementation details--```typescript-// Don't spy on services that internal_fetchAIChatMessage uses-const streamSpy = vi- .spyOn(chatService, 'createAssistantMessageStream')- .mockImplementation(...);-```--**Why**: Each test should only mock its direct dependencies, not the entire call chain. This makes tests more maintainable and less brittle.--### 2. Mock Management - Minimize Global Spies--โ **Good**: Spy only when needed--```typescript-beforeEach(() => {- // โ Only spy services that most tests need- vi.spyOn(messageService, 'createMessage').mockResolvedValue('new-message-id');- // โ Don't spy chatService globally-});--it('should process message', async () => {- // โ Spy chatService only in tests that need it- const streamSpy = vi.spyOn(chatService, 'createAssistantMessageStream')- .mockImplementation(...);-- // test logic-- streamSpy.mockRestore();-});-```--โ **Bad**: Setup all spies globally--```typescript-beforeEach(() => {- vi.spyOn(messageService, 'createMessage').mockResolvedValue('id');- vi.spyOn(chatService, 'createAssistantMessageStream').mockResolvedValue({}); // โ Not all tests need this- vi.spyOn(fileService, 'uploadFile').mockResolvedValue({}); // โ Creates implicit coupling-});-```--### 3. Service Mocking - Mock the Correct Layer--โ **Good**: Mock the service method--```typescript-it('should fetch AI chat response', async () => {- const streamSpy = vi- .spyOn(chatService, 'createAssistantMessageStream')- .mockImplementation(async ({ onMessageHandle, onFinish }) => {- await onMessageHandle?.({ type: 'text', text: 'Hello' } as any);- await onFinish?.('Hello', {});- });-- // test logic-});-```--โ **Bad**: Mock global fetch--```typescript-it('should fetch AI chat response', async () => {- global.fetch = vi.fn().mockResolvedValue(...); // โ Too low level-});-```--### 4. Test Organization - Use Descriptive Nesting--โ **Good**: Clear nested structure--```typescript-describe('sendMessage', () => {- describe('validation', () => {- it('should not send when session is inactive', async () => {});- it('should not send when message is empty', async () => {});- });-- describe('message creation', () => {- it('should create user message and trigger AI processing', async () => {});- it('should send message with files attached', async () => {});- });-- describe('error handling', () => {- it('should handle message creation errors gracefully', async () => {});- });-});-```--โ **Bad**: Flat structure--```typescript-describe('sendMessage', () => {- it('test 1', async () => {});- it('test 2', async () => {});- it('test 3', async () => {});-});-```--### 5. Testing Async Actions--Always wrap async operations in `act()`:--```typescript-it('should send message', async () => {- const { result } = renderHook(() => useChatStore());-- await act(async () => {- await result.current.sendMessage({ message: 'Hello' });- });-- expect(messageService.createMessage).toHaveBeenCalled();-});-```--### 6. State Setup - Use act() for setState--```typescript-it('should handle disabled state', async () => {- act(() => {- useChatStore.setState({ activeId: undefined });- });-- const { result } = renderHook(() => useChatStore());- // test logic-});-```--### 7. Testing Complex Flows--For complex flows with multiple steps, use clear spy setup:--```typescript-it('should handle topic creation flow', async () => {- // Setup store state- act(() => {- useChatStore.setState({- activeTopicId: undefined,- messagesMap: {- 'test-session-id': [- { id: 'msg-1', role: 'user', content: 'Message 1' },- { id: 'msg-2', role: 'assistant', content: 'Response 1' },- { id: 'msg-3', role: 'user', content: 'Message 2' },- ],- },- });- });-- const { result } = renderHook(() => useChatStore());-- // Spy on action dependencies- const createTopicSpy = vi.spyOn(result.current, 'createTopic').mockResolvedValue('new-topic-id');- const toggleLoadingSpy = vi.spyOn(result.current, 'internal_toggleMessageLoading');-- // Execute- await act(async () => {- await result.current.sendMessage({ message: 'Test message' });- });-- // Assert- expect(createTopicSpy).toHaveBeenCalled();- expect(toggleLoadingSpy).toHaveBeenCalledWith(true, expect.any(String));-});-```--### 8. Streaming Response Mocking--When testing streaming responses, simulate the flow properly:--```typescript-it('should handle streaming chunks', async () => {- const { result } = renderHook(() => useChatStore());- const messages = [{ id: 'msg-1', role: 'user', content: 'Hello', sessionId: 'test-session' }];-- const streamSpy = vi- .spyOn(chatService, 'createAssistantMessageStream')- .mockImplementation(async ({ onMessageHandle, onFinish }) => {- // Simulate streaming chunks- await onMessageHandle?.({ type: 'text', text: 'Hello' } as any);- await onMessageHandle?.({ type: 'text', text: ' World' } as any);- await onFinish?.('Hello World', {});- });-- await act(async () => {- await result.current.internal_fetchAIChatMessage({- messages,- messageId: 'test-message-id',- model: 'gpt-4o-mini',- provider: 'openai',- });- });-- expect(result.current.internal_dispatchMessage).toHaveBeenCalled();-- streamSpy.mockRestore();-});-```--### 9. Error Handling Tests--Always test error scenarios:--```typescript-it('should handle errors gracefully', async () => {- const { result } = renderHook(() => useChatStore());-- vi.spyOn(messageService, 'createMessage').mockRejectedValue(new Error('create message error'));-- await act(async () => {- try {- await result.current.sendMessage({ message: 'Test message' });- } catch {- // Expected to throw- }- });-- expect(result.current.internal_coreProcessMessage).not.toHaveBeenCalled();-});-```--### 10. Cleanup After Tests--Always restore mocks after each test:--```typescript-afterEach(() => {- vi.restoreAllMocks();-});--// For individual test cleanup:-it('should test something', async () => {- const spy = vi.spyOn(service, 'method').mockImplementation(...);-- // test logic-- spy.mockRestore(); // Optional: cleanup immediately after test-});-```--## Common Patterns--### Testing Store Methods That Call Other Store Methods--```typescript-it('should call internal methods', async () => {- const { result } = renderHook(() => useChatStore());-- const internalMethodSpy = vi.spyOn(result.current, 'internal_method').mockResolvedValue();-- await act(async () => {- await result.current.publicMethod();- });-- expect(internalMethodSpy).toHaveBeenCalledWith(- expect.any(String),- expect.objectContaining({ key: 'value' }),- );-});-```--### Testing Conditional Logic--```typescript-describe('conditional behavior', () => {- it('should execute when condition is true', async () => {- const { result } = renderHook(() => useChatStore());- vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(true);-- await act(async () => {- await result.current.sendMessage({ message: 'test' });- });-- expect(result.current.internal_retrieveChunks).toHaveBeenCalled();- });-- it('should not execute when condition is false', async () => {- const { result } = renderHook(() => useChatStore());- vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(false);-- await act(async () => {- await result.current.sendMessage({ message: 'test' });- });-- expect(result.current.internal_retrieveChunks).not.toHaveBeenCalled();- });-});-```--### Testing AbortController--```typescript-it('should abort generation and clear loading state', () => {- const abortController = new AbortController();-- act(() => {- useChatStore.setState({ chatLoadingIdsAbortController: abortController });- });-- const { result } = renderHook(() => useChatStore());- const toggleLoadingSpy = vi.spyOn(result.current, 'internal_toggleChatLoading');-- act(() => {- result.current.stopGenerateMessage();- });-- expect(abortController.signal.aborted).toBe(true);- expect(toggleLoadingSpy).toHaveBeenCalledWith(false, undefined, expect.any(String));-});-```--## Anti-Patterns to Avoid--โ **Don't**: Mock the entire store--```typescript-vi.mock('../../store', () => ({- useChatStore: vi.fn(() => ({- sendMessage: vi.fn(),- })),-}));-```--โ **Don't**: Test implementation details--```typescript-// Bad: testing internal state structure-expect(result.current.messagesMap).toHaveProperty('test-session');--// Good: testing behavior-expect(result.current.refreshMessages).toHaveBeenCalled();-```--โ **Don't**: Create tight coupling between tests--```typescript-// Bad: Tests depend on order-let messageId: string;--it('test 1', () => {- messageId = 'some-id'; // Side effect-});--it('test 2', () => {- expect(messageId).toBeDefined(); // Depends on test 1-});-```--โ **Don't**: Over-mock services--```typescript-// Bad: Mocking everything-beforeEach(() => {- vi.mock('@/services/chat');- vi.mock('@/services/message');- vi.mock('@/services/file');- vi.mock('@/services/agent');- // ... too many global mocks-});-```--## Testing SWR Hooks in Zustand Stores--Some Zustand store slices use SWR hooks for data fetching. These require a different testing approach.--### Basic SWR Hook Test Structure--```typescript-import { renderHook, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { discoverService } from '@/services/discover';-import { globalHelpers } from '@/store/global/helpers';--import { useDiscoverStore as useStore } from '../../store';--vi.mock('zustand/traditional');--beforeEach(() => {- vi.clearAllMocks();-});--describe('SWR Hook Actions', () => {- it('should fetch data and return correct response', async () => {- const mockData = [{ id: '1', name: 'Item 1' }];-- // Mock the service call (the fetcher)- vi.spyOn(discoverService, 'getPluginCategories').mockResolvedValue(mockData as any);- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('en-US');-- const params = {} as any;- const { result } = renderHook(() => useStore.getState().usePluginCategories(params));-- // Use waitFor to wait for async data loading- await waitFor(() => {- expect(result.current.data).toEqual(mockData);- });-- expect(discoverService.getPluginCategories).toHaveBeenCalledWith(params);- });-});-```--**Key points**:--- **DO NOT mock useSWR** - let it use the real implementation-- Only mock the **service methods** (fetchers)-- Use `waitFor` from `@testing-library/react` to wait for async operations-- Check `result.current.data` directly after waitFor completes--### Testing SWR Key Generation--```typescript-it('should generate correct SWR key with locale and params', () => {- vi.spyOn(globalHelpers, 'getCurrentLanguage').mockReturnValue('zh-CN');-- const useSWRMock = vi.mocked(useSWR);- let capturedKey: string | null = null;- useSWRMock.mockImplementation(((key: string) => {- capturedKey = key;- return { data: undefined, error: undefined, isValidating: false, mutate: vi.fn() };- }) as any);-- const params = { page: 2, category: 'tools' } as any;- renderHook(() => useStore.getState().usePluginList(params));-- expect(capturedKey).toBe('plugin-list-zh-CN-2-tools');-});-```--### Testing SWR Configuration--```typescript-it('should have correct SWR configuration', () => {- const useSWRMock = vi.mocked(useSWR);- let capturedOptions: any = null;- useSWRMock.mockImplementation(((key: string, fetcher: any, options: any) => {- capturedOptions = options;- return { data: undefined, error: undefined, isValidating: false, mutate: vi.fn() };- }) as any);-- renderHook(() => useStore.getState().usePluginIdentifiers());-- expect(capturedOptions).toMatchObject({ revalidateOnFocus: false });-});-```--### Testing Conditional Fetching--```typescript-it('should not fetch when required parameter is missing', () => {- const useSWRMock = vi.mocked(useSWR);- let capturedKey: string | null = null;- useSWRMock.mockImplementation(((key: string | null) => {- capturedKey = key;- return { data: undefined, error: undefined, isValidating: false, mutate: vi.fn() };- }) as any);-- // When identifier is undefined, SWR key should be null- renderHook(() => useStore.getState().usePluginDetail({ identifier: undefined }));-- expect(capturedKey).toBeNull();-});-```--### Key Differences from Regular Action Tests--1. **Mock useSWR globally**: Use `vi.mock('swr')` at the top level-2. **Mock the fetcher, not the result**:- - โ **Correct**: `const data = fetcher?.()` - call fetcher and return its Promise- - โ **Wrong**: `return { data: mockData }` - hardcode the result-3. **Await Promise results**: The `data` field is a Promise, use `await result.current.data`-4. **No act() wrapper needed**: SWR hooks don't trigger React state updates in these tests-5. **Test SWR key generation**: Verify keys include locale and parameters-6. **Test configuration**: Verify revalidation and other SWR options-7. **Type assertions**: Use `as any` for test mock data where type definitions are strict--**Why this matters**:--- The fetcher (service method) is what we're testing - it must be called-- Hardcoding the return value bypasses the actual fetcher logic-- SWR returns Promises in real usage, tests should mirror this behavior--## Benefits of This Approach--โ **Clear test layers** - Each test only spies on direct dependencies โ **Correct mocks** - Mocks match actual implementation โ **Better maintainability** - Changes to implementation require fewer test updates โ **Improved coverage** - Structured approach ensures all branches are tested โ **Reduced coupling** - Tests are independent and can run in any order--## Reference--See example implementation in:--- `src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.ts` (Regular actions)-- `src/store/discover/slices/plugin/action.test.ts` (SWR hooks)-- `src/store/discover/slices/mcp/action.test.ts` (SWR hooks)diff --git a/.cursor/rules/typescript.mdc b/.cursor/rules/typescript.mdcdeleted file mode 100644index 61ea40b99b2..00000000000--- a/.cursor/rules/typescript.mdc+++ /dev/null@@ -1,55 +0,0 @@-----description: TypeScript code style and optimization guidelines-globs: *.ts,*.tsx,*.mts-alwaysApply: false------# TypeScript Code Style Guide--## Types and Type Safety--- avoid explicit type annotations when TypeScript can infer types.-- avoid implicitly `any` variables; explicitly type when necessary (e.g., `let a: number` instead of `let a`).-- use the most accurate type possible (e.g., prefer `Record<PropertyKey, unknown>` over `object` and `any`).-- prefer `interface` over `type` for object shapes (e.g., React component props). Keep `type` for unions, intersections, and utility types.-- prefer `as const satisfies XyzInterface` over plain `as const` when suitable.-- prefer `@ts-expect-error` over `@ts-ignore` over `as any`-- Avoid meaningless null/undefined parameters; design strict function contracts.--## Asynchronous Patterns and Concurrency--- Prefer `async`/`await` over callbacks or chained `.then` promises.-- Prefer async APIs over sync ones (avoid `*Sync`).-- Prefer promise-based variants (e.g., `import { readFile } from 'fs/promises'`) over callback-based APIs from `fs`.-- Where safe, convert sequential async flows to concurrent ones with `Promise.all`, `Promise.race`, etc.--## Code Structure and Readability--- Prefer object destructuring when accessing and using properties.-- Use consistent, descriptive naming; avoid obscure abbreviations.-- Use semantically meaningful variable, function, and class names.-- Replace magic numbers or strings with well-named constants.-- Defer formatting to tooling; ignore purely formatting-only issues and autofixable lint problems.--## UI and Theming--- Use components from `@lobehub/ui`, Ant Design, or existing design system components instead of raw HTML tags (e.g., `Button` vs. `button`).-- Design for dark mode and mobile responsiveness:- - Use the `antd-style` token system instead of hard-coded colors.- - Select appropriate component variants.--## Performance--- Prefer `forโฆof` loops to index-based `for` loops when feasible.-- Reuse existing utils inside `packages/utils` or installed npm packages rather than reinventing the wheel.-- Query only the required columns from a database rather than selecting entire rows.--## Time and Consistency--- Instead of calling `Date.now()` multiple times, assign it to a constant once and reuse it to ensure consistency and improve readability.--## Logging--- Never log user private information like api key, etc-- Don't use `import { log } from 'debug'` to log messages, because it will directly log the message to the console.-- Use console.error instead of debug package to log error message in catch block.diff --git a/.cursor/rules/zustand-action-patterns.mdc b/.cursor/rules/zustand-action-patterns.mdcdeleted file mode 100644index 365487c31d0..00000000000--- a/.cursor/rules/zustand-action-patterns.mdc+++ /dev/null@@ -1,328 +0,0 @@-----description:-globs: src/store/**-alwaysApply: false------# LobeChat Zustand Action Patterns--## Action Type Hierarchy--LobeChat Actions use a layered architecture with clear separation of responsibilities:--### 1. Public Actions--Main interfaces exposed for UI component consumption:--- Naming: Verb form (`createTopic`, `sendMessage`, `updateTopicTitle`)-- Responsibilities: Parameter validation, flow orchestration, calling internal actions-- Example: `src/store/chat/slices/topic/action.ts`--```typescript-// Public Action example-createTopic: async () => {- // ...- return topicId;-},-```--### 2. Internal Actions (`internal_*`)--Internal implementation details handling core business logic:--- Naming: `internal_` prefix + verb (`internal_createTopic`, `internal_updateMessageContent`)-- Responsibilities: Optimistic updates, service calls, error handling, state synchronization-- Should not be called directly by UI components--```typescript-// Internal Action example - Optimistic update pattern-internal_createTopic: async (params) => {- const tmpId = Date.now().toString();-- // 1. Immediately update frontend state (optimistic update)- get().internal_dispatchTopic(- { type: 'addTopic', value: { ...params, id: tmpId } },- 'internal_createTopic',- );- get().internal_updateTopicLoading(tmpId, true);-- // 2. Call backend service- const topicId = await topicService.createTopic(params);- get().internal_updateTopicLoading(tmpId, false);-- // 3. Refresh data to ensure consistency- get().internal_updateTopicLoading(topicId, true);- await get().refreshTopic();- get().internal_updateTopicLoading(topicId, false);-- return topicId;-},-```--### 3. Dispatch Methods (`internal_dispatch*`)--Methods dedicated to handling state updates:--- Naming: `internal_dispatch` + entity name (`internal_dispatchTopic`, `internal_dispatchMessage`)-- Responsibilities: Calling reducers, updating Zustand store, handling state comparison--```typescript-// Dispatch Method example-internal_dispatchTopic: (payload, action) => {- const nextTopics = topicReducer(topicSelectors.currentTopics(get()), payload);- const nextMap = { ...get().topicMaps, [get().activeId]: nextTopics };-- if (isEqual(nextMap, get().topicMaps)) return;-- set({ topicMaps: nextMap }, false, action ?? n(`dispatchTopic/${payload.type}`));-},-```--## When to Use Reducer Pattern vs. Simple `set`--### Use Reducer Pattern When--Suitable for complex data structure management, especially:--- Managing object lists or maps (e.g., `messagesMap`, `topicMaps`)-- Scenarios requiring optimistic updates-- Complex state transition logic-- Type-safe action payloads needed--```typescript-// Reducer pattern example - Complex message state management-export const messagesReducer = (state: ChatMessage[], payload: MessageDispatch): ChatMessage[] => {- switch (payload.type) {- case 'updateMessage': {- return produce(state, (draftState) => {- const index = draftState.findIndex((i) => i.id === payload.id);- if (index < 0) return;- draftState[index] = merge(draftState[index], {- ...payload.value,- updatedAt: Date.now(),- });- });- }- case 'createMessage': {- // ...- }- // ...other complex state transitions- }-};-```--### Use Simple `set` When--Suitable for simple state updates:--- Toggling boolean values-- Updating simple strings/numbers-- Setting single state fields--```typescript-// Simple set example-updateInputMessage: (message) => {- if (isEqual(message, get().inputMessage)) return;- set({ inputMessage: message }, false, n('updateInputMessage'));-},--togglePortal: (open?: boolean) => {- set({ showPortal: open ?? !get().showPortal }, false, 'togglePortal');-},-```--## Optimistic Update Implementation Patterns--Optimistic updates are a core pattern in LobeChat for providing smooth user experience:--### Standard Optimistic Update Flow--```typescript-// Complete optimistic update example-internal_updateMessageContent: async (id, content, extra) => {- const { internal_dispatchMessage, refreshMessages } = get();-- // 1. Immediately update frontend state (optimistic update)- internal_dispatchMessage({- id,- type: 'updateMessage',- value: { content },- });-- // 2. Call backend service- await messageService.updateMessage(id, {- content,- tools: extra?.toolCalls ? internal_transformToolCalls(extra.toolCalls) : undefined,- // ...other fields- });-- // 3. Refresh to ensure data consistency- await refreshMessages();-},-```--### Optimistic Update for Create Operations--```typescript-internal_createMessage: async (message, context) => {- const { internal_createTmpMessage, refreshMessages, internal_toggleMessageLoading } = get();-- let tempId = context?.tempMessageId;- if (!tempId) {- // Create temporary message for optimistic update- tempId = internal_createTmpMessage(message);- internal_toggleMessageLoading(true, tempId);- }-- try {- const id = await messageService.createMessage(message);- if (!context?.skipRefresh) {- await refreshMessages();- }- internal_toggleMessageLoading(false, tempId);- return id;- } catch (e) {- internal_toggleMessageLoading(false, tempId);- // Error handling: update message error state- internal_dispatchMessage({- id: tempId,- type: 'updateMessage',- value: { error: { type: ChatErrorType.CreateMessageError, message: e.message } },- });- }-},-```--### Delete Operation Pattern (No Optimistic Update)--Delete operations typically don't suit optimistic updates because:--- Deletion is destructive; error recovery is complex-- Users have lower expectations for immediate feedback on deletions-- Restoring state on deletion failure causes confusion--```typescript-// Standard delete operation pattern - No optimistic update-removeGenerationTopic: async (id: string) => {- const { internal_removeGenerationTopic } = get();- await internal_removeGenerationTopic(id);-},--internal_removeGenerationTopic: async (id: string) => {- // 1. Show loading state- get().internal_updateGenerationTopicLoading(id, true);-- try {- // 2. Directly call backend service- await generationTopicService.deleteTopic(id);-- // 3. Refresh data to get latest state- await get().refreshGenerationTopics();- } finally {- // 4. Ensure loading state is cleared (whether success or failure)- get().internal_updateGenerationTopicLoading(id, false);- }-},-```--Delete operation characteristics:--- Directly call service without pre-updating state-- Rely on loading state for user feedback-- Refresh entire list after operation to ensure consistency-- Use `try/finally` to ensure loading state is always cleaned up--## Loading State Management Pattern--LobeChat uses a unified loading state management pattern:--### Array-based Loading State--```typescript-// Define in initialState.ts-export interface ChatMessageState {- messageEditingIds: string[]; // Message editing state-}--// Manage in action-{- toggleMessageEditing: (id, editing) => {- set(- { messageEditingIds: toggleBooleanList(get().messageEditingIds, id, editing) },- false,- 'toggleMessageEditing',- );- };-}-```--## SWR Integration Pattern--LobeChat uses SWR for data fetching and cache management:--### Hook-based Data Fetching--```typescript-// Define SWR hook in action.ts-useFetchMessages: (enable, sessionId, activeTopicId) =>- useClientDataSWR<ChatMessage[]>(- enable ? [SWR_USE_FETCH_MESSAGES, sessionId, activeTopicId] : null,- async ([, sessionId, topicId]) => messageService.getMessages(sessionId, topicId),- {- onSuccess: (messages, key) => {- const nextMap = {- ...get().messagesMap,- [messageMapKey(sessionId, activeTopicId)]: messages,- };-- if (get().messagesInit && isEqual(nextMap, get().messagesMap)) return;-- set({ messagesInit: true, messagesMap: nextMap }, false, n('useFetchMessages'));- },- },- ),-```--### Cache Invalidation and Refresh--```typescript-// Standard data refresh pattern-refreshMessages: async () => {- await mutate([SWR_USE_FETCH_MESSAGES, get().activeId, get().activeTopicId]);-};-```--## Naming Convention Summary--### Action Naming Patterns--- Public Actions: Verb form, describing user intent- - `createTopic`, `sendMessage`, `regenerateMessage`-- Internal Actions: `internal_` + verb, describing internal operation- - `internal_createTopic`, `internal_updateMessageContent`-- Dispatch Methods: `internal_dispatch` + entity name- - `internal_dispatchTopic`, `internal_dispatchMessage`-- Toggle Methods: `internal_toggle` + state name- - `internal_toggleMessageLoading`, `internal_toggleChatLoading`--### State Naming Patterns--- ID arrays: `[entity]LoadingIds`, `[entity]EditingIds`-- Map structures: `[entity]Maps`, `[entity]Map`-- Currently active: `active[Entity]Id`-- Initialization flags: `[entity]sInit`--## Best Practices--1. Use optimistic updates appropriately:- - โ Suitable: Create, update operations (frequent user interaction)- - โ Avoid: Delete operations (destructive, complex error recovery)-2. Loading state management: Use unified loading state arrays to manage concurrent operations-3. Type safety: Define TypeScript interfaces for all action payloads-4. SWR integration: Use SWR to manage data fetching and cache invalidation-5. AbortController: Provide cancellation capability for long-running operations-6. Operation mode selection:- - Create/Update: Optimistic update + eventual consistency- - Delete: Loading state + service call + data refresh--This Action organization pattern ensures code consistency, maintainability, and provides excellent user experience.diff --git a/.cursor/rules/zustand-slice-organization.mdc b/.cursor/rules/zustand-slice-organization.mdcdeleted file mode 100644index 3226bc30992..00000000000--- a/.cursor/rules/zustand-slice-organization.mdc+++ /dev/null@@ -1,308 +0,0 @@-----description:-globs: src/store/**-alwaysApply: false------# LobeChat Zustand Store Slice ็ป็ปๆถๆ--ๆฌๆๆกฃๆ่ฟฐไบ LobeChat ้กน็ฎไธญ Zustand Store ็ๆจกๅๅ Slice ็ป็ปๆนๅผ๏ผๅฑ็คบๅฆไฝ้่ฟๅ็ๆถๆ็ฎก็ๅคๆ็ๅบ็จ็ถๆใ--## ้กถๅฑ Store ็ปๆ--LobeChat ็ `chat` store (`src/store/chat/`) ้็จๆจกๅๅ็ slice ็ปๆๆฅ็ป็ป็ถๆๅ้ป่พใ--### ๅ ณ้ฎ่ๅๆไปถ--- `src/store/chat/initialState.ts`: ่ๅๆๆ slice ็ๅๅง็ถๆ-- `src/store/chat/store.ts`: ๅฎไน้กถๅฑ็ `ChatStore`๏ผ็ปๅๆๆ slice ็ actions-- `src/store/chat/selectors.ts`: ็ปไธๅฏผๅบๆๆ slice ็ selectors-- `src/store/chat/helpers.ts`: ๆไพ่ๅคฉ็ธๅ ณ็่พ ๅฉๅฝๆฐ--### Store ่ๅๆจกๅผ--```typescript-// src/store/chat/initialState.ts-import { ChatTopicState, initialTopicState } from './slices/topic/initialState';-import { ChatMessageState, initialMessageState } from './slices/message/initialState';-import { ChatAIChatState, initialAiChatState } from './slices/aiChat/initialState';--export type ChatStoreState = ChatTopicState &- ChatMessageState &- ChatAIChatState &- // ...ๅ ถไป slice states--export const initialState: ChatStoreState = {- ...initialMessageState,- ...initialTopicState,- ...initialAiChatState,- // ...ๅ ถไป initial slice states-};-```--```typescript-// src/store/chat/store.ts-import { ChatMessageAction, chatMessage } from './slices/message/action';-import { ChatTopicAction, chatTopic } from './slices/topic/action';-import { ChatAIChatAction, chatAiChat } from './slices/aiChat/actions';--export interface ChatStoreAction- extends ChatMessageAction,- ChatTopicAction,- ChatAIChatAction,- // ...ๅ ถไป slice actions--const createStore: StateCreator<ChatStore, [['zustand/devtools', never]]> = (...params) => ({- ...initialState,- ...chatMessage(...params),- ...chatTopic(...params),- ...chatAiChat(...params),- // ...ๅ ถไป slice action creators-});--export const useChatStore = createWithEqualityFn<ChatStore>()(- subscribeWithSelector(devtools(createStore)),- shallow,-);-```--## ๅไธช Slice ็ๆ ๅ็ปๆ--ๆฏไธช slice ไฝไบ `src/store/chat/slices/[sliceName]/` ็ฎๅฝไธ๏ผ--```plaintext-src/store/chat/slices/-โโโ [sliceName]/ # ไพๅฆ message, topic, aiChat, builtinTool- โโโ action.ts # ๅฎไน actions (ๆ่ ๆฏไธไธช actions/ ็ฎๅฝ)- โโโ initialState.ts # ๅฎไน state ็ปๆๅๅๅงๅผ- โโโ reducer.ts # (ๅฏ้) ๅฆๆไฝฟ็จ reducer ๆจกๅผ- โโโ selectors.ts # ๅฎไน selectors- โโโ index.ts # (ๅฏ้) ้ๆฐๅฏผๅบๆจกๅๅ ๅฎน-```--### ๆไปถ่่ดฃ่ฏดๆ--1. `initialState.ts`:- - ๅฎไน slice ็ TypeScript ็ถๆๆฅๅฃ- - ๆไพๅๅง็ถๆ้ป่ฎคๅผ--```typescript-// ๅ ธๅ็ initialState.ts ็ปๆ-export interface ChatTopicState {- activeTopicId?: string;- topicMaps: Record<string, ChatTopic[]>; // ๆ ธๅฟๆฐๆฎ็ปๆ- topicsInit: boolean;- topicLoadingIds: string[];- // ...ๅ ถไป็ถๆๅญๆฎต-}--export const initialTopicState: ChatTopicState = {- activeTopicId: undefined,- topicMaps: {},- topicsInit: false,- topicLoadingIds: [],- // ...ๅ ถไปๅๅงๅผ-};-```--1. `reducer.ts` (ๅคๆ็ถๆไฝฟ็จ):- - ๅฎไน็บฏๅฝๆฐ reducer๏ผๅค็ๅๆญฅ็ถๆ่ฝฌๆข- - ไฝฟ็จ `immer` ็กฎไฟไธๅฏๅๆดๆฐ--```typescript-// ๅ ธๅ็ reducer.ts ็ปๆ-import { produce } from 'immer';--interface AddChatTopicAction {- type: 'addTopic';- value: CreateTopicParams & { id?: string };-}--interface UpdateChatTopicAction {- id: string;- type: 'updateTopic';- value: Partial<ChatTopic>;-}--export type ChatTopicDispatch = AddChatTopicAction | UpdateChatTopicAction;--export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch): ChatTopic[] => {- switch (payload.type) {- case 'addTopic': {- return produce(state, (draftState) => {- draftState.unshift({- ...payload.value,- id: payload.value.id ?? Date.now().toString(),- createdAt: Date.now(),- });- });- }- case 'updateTopic': {- return produce(state, (draftState) => {- const index = draftState.findIndex((topic) => topic.id === payload.id);- if (index !== -1) {- draftState[index] = { ...draftState[index], ...payload.value };- }- });- }- default:- return state;- }-};-```--1. `selectors.ts`:- - ๆไพ็ถๆๆฅ่ฏขๅ่ฎก็ฎๅฝๆฐ- - ไพ UI ็ปไปถไฝฟ็จ็็ถๆ่ฎข้ ๆฅๅฃ- - ้่ฆ: ไฝฟ็จ `export const xxxSelectors` ๆจกๅผ่ๅๆๆ selectors--```typescript-// ๅ ธๅ็ selectors.ts ็ปๆ-import { ChatStoreState } from '../../initialState';--const currentTopics = (s: ChatStoreState): ChatTopic[] | undefined => s.topicMaps[s.activeId];--const currentActiveTopic = (s: ChatStoreState): ChatTopic | undefined => {- return currentTopics(s)?.find((topic) => topic.id === s.activeTopicId);-};--const getTopicById =- (id: string) =>- (s: ChatStoreState): ChatTopic | undefined =>- currentTopics(s)?.find((topic) => topic.id === id);--// ๆ ธๅฟๆจกๅผ๏ผไฝฟ็จ xxxSelectors ่ๅๅฏผๅบ-export const topicSelectors = {- currentActiveTopic,- currentTopics,- getTopicById,- // ...ๅ ถไป selectors-};-```--## ็นๆฎ Slice ็ป็ปๆจกๅผ--### ๅคๆ Actions ็ๅญ็ฎๅฝ็ปๆ (aiChat Slice)--ๅฝ slice ็ actions ่ฟไบๅคๆๆถ๏ผๅฏไปฅๆๅๅฐๅญ็ฎๅฝ๏ผ--```plaintext-src/store/chat/slices/aiChat/-โโโ actions/-โ โโโ generateAIChat.ts # AI ๅฏน่ฏ็ๆ-โ โโโ rag.ts # RAG ๆฃ็ดขๅขๅผบ็ๆ-โ โโโ memory.ts # ๅฏน่ฏ่ฎฐๅฟ็ฎก็-โ โโโ index.ts # ่ๅๆๆ actions-โโโ initialState.ts-โโโ selectors.ts-โโโ index.ts-```--ๅ่๏ผ`src/store/chat/slices/aiChat/actions/`--### ๅทฅๅ ท็ฑป Slice (builtinTool)--็ฎก็ๅค็งๅ ็ฝฎๅทฅๅ ท็็ถๆ๏ผ--```plaintext-src/store/chat/slices/builtinTool/-โโโ actions/-โ โโโ dalle.ts # DALL-E ๅพๅ็ๆ-โ โโโ search.ts # ๆ็ดขๅ่ฝ-โ โโโ localFile.ts # ๆฌๅฐๆไปถๆไฝ-โ โโโ index.ts-โโโ initialState.ts-โโโ selectors.ts-โโโ index.ts-```--ๅ่๏ผ`src/store/chat/slices/builtinTool/`--## ็ถๆ่ฎพ่ฎกๆจกๅผ--### 1. Map ็ปๆ็จไบๅ ณ่ๆฐๆฎ--```typescript-// ไปฅ sessionId ไธบ key๏ผ็ฎก็ๅคไธชไผ่ฏ็ๆฐๆฎ-topicMaps: Record<string, ChatTopic[]>;-messagesMap: Record<string, ChatMessage[]>;-```--### 2. ๆฐ็ป็จไบๅ ่ฝฝ็ถๆ็ฎก็--```typescript-// ็ฎก็ๅคไธชๅนถๅๆไฝ็ๅ ่ฝฝ็ถๆ-messageLoadingIds: string[]-topicLoadingIds: string[]-chatLoadingIds: string[]-```--### 3. ๅฏ้ๅญๆฎต็จไบๅฝๅๆดปๅจ้กน--```typescript-// ๅฝๅๆฟๆดป็ๅฎไฝ ID-activeId: string-activeTopicId?: string-activeThreadId?: string-```--## Slice ้ๆๅฐ้กถๅฑ Store--### 1. ็ถๆ่ๅ--```typescript-// ๅจ initialState.ts ไธญ-export type ChatStoreState = ChatTopicState &- ChatMessageState &- ChatAIChatState &- // ...ๅ ถไป slice states-```--### 2. Action ๆฅๅฃ่ๅ--```typescript-// ๅจ store.ts ไธญ-export interface ChatStoreAction- extends ChatMessageAction,- ChatTopicAction,- ChatAIChatAction,- // ...ๅ ถไป slice actions-```--### 3. Selector ็ปไธๅฏผๅบ--```typescript-// ๅจ selectors.ts ไธญ - ็ปไธ่ๅ selectors-export { chatSelectors } from './slices/message/selectors';-export { topicSelectors } from './slices/topic/selectors';-export { aiChatSelectors } from './slices/aiChat/selectors';--// ๆฏไธช slice ็ selectors.ts ้ฝไฝฟ็จ xxxSelectors ๆจกๅผ๏ผ-// export const chatSelectors = { ... }-// export const topicSelectors = { ... }-// export const aiChatSelectors = { ... }-```--## ๆไฝณๅฎ่ทต--1. Slice ๅๅๅๅ:- - ๆๅ่ฝ้ขๅๅๅ๏ผmessage, topic, aiChat ็ญ๏ผ- - ๆฏไธช slice ็ฎก็็ธๅ ณ็็ถๆๅๆไฝ- - ้ฟๅ slice ไน้ด็ๅผบ่ฆๅ--2. ๆไปถๅฝๅ่ง่:- - ไฝฟ็จๅฐ้ฉผๅณฐๅฝๅ slice ็ฎๅฝ- - ๆไปถๅไฝฟ็จไธ่ด็ๆจกๅผ๏ผaction.ts, selectors.ts ็ญ๏ผ- - ๅคๆ actions ๆถไฝฟ็จ actions/ ๅญ็ฎๅฝ--3. ็ถๆ็ปๆ่ฎพ่ฎก:- - ๆๅนณๅ็็ถๆ็ปๆ๏ผ้ฟๅ ๆทฑๅฑๅตๅฅ- - ไฝฟ็จ Map ็ปๆ็ฎก็ๅ่กจๆฐๆฎ- - ๅ็ฆปๅ ่ฝฝ็ถๆๅไธๅกๆฐๆฎ--4. ็ฑปๅๅฎๅ จ:- - ไธบๆฏไธช slice ๅฎไนๆธ ๆฐ็ TypeScript ๆฅๅฃ- - ไฝฟ็จ Zustand ็ StateCreator ็กฎไฟ็ฑปๅไธ่ดๆง- - ๅจ้กถๅฑ่ๅๆถไฟๆ็ฑปๅๅฎๅ จ--่ฟ็งๆจกๅๅ็ slice ็ป็ปๆนๅผไฝฟๅพๅคงๅๅบ็จ็็ถๆ็ฎก็ๅๅพๆธ ๆฐใๅฏ็ปดๆค๏ผๅนถไธๆไบๆฉๅฑใdiff --git a/.cursor/skills b/.cursor/skillsindex 7bcb9556370..2b7a412b8fa 120000--- a/.cursor/skills+++ b/.cursor/skills@@ -1 +1 @@-../.agents\ No newline at end of file+../.agents/skills\ No newline at end of filediff --git a/AGENTS.md b/AGENTS.mdindex ced69591a6f..682d30539af 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -4,12 +4,10 @@ This document serves as a comprehensive guide for all team members when developi## Project Description-You are developing an open-source, modern-design AI Agent Workspace: LobeHub(previous LobeChat).+You are developing an open-source, modern-design AI Agent Workspace: LobeHub (previously LobeChat).## Tech Stack-Built with modern technologies:-- **Frontend**: Next.js 16, React 19, TypeScript- **UI Components**: Ant Design, @lobehub/ui, antd-style- **State Management**: Zustand, SWR@@ -19,24 +17,33 @@ Built with modern technologies:## Directory Structure-The project follows a well-organized monorepo structure:--- `apps/` - Main applications-- `packages/` - Shared packages and libraries-- `src/` - Main source code-- `docs/` - Documentation-- `.cursor/rules/` - Development rules and guidelines-- PR titles starting with `โจ feat/` or `๐ fix` will trigger the release workflow upon merge. Only use these prefixes for significant user-facing feature changes or bug fixes+```+lobe-chat/+โโโ apps/desktop/ # Electron desktop app+โโโ packages/ # Shared packages (@lobechat/*)+โ โโโ database/ # Database schemas, models, repositories+โ โโโ agent-runtime/ # Agent runtime+โ โโโ ...+โโโ src/+โ โโโ app/ # Next.js app router+โ โโโ store/ # Zustand stores+โ โโโ services/ # Client services+โ โโโ server/ # Server services and routers+โ โโโ ...+โโโ .agents/skills/ # AI development skills+โโโ e2e/ # E2E tests (Cucumber + Playwright)+```## Development Workflow### Git Workflow-- The current release branch is `next` instead of `main` until v2.0.0 is officially released+- The current release branch is `next` until v2.0.0 is officially released- Use rebase for git pull- Git commit messages should prefix with gitmoji- Git branch name format: `username/feat/feature-name`- Use `.github/PULL_REQUEST_TEMPLATE.md` for PR descriptions+- PR titles with `โจ feat/` or `๐ fix` trigger releases### Package Management@@ -52,17 +59,18 @@ The project follows a well-organized monorepo structure:### Testing Strategy-**Required Rule**: `testing-guide/testing-guide.mdc`+```bash+# Web tests+bunx vitest run --silent='passed-only' '[file-path-pattern]'-**Commands**:--- Web: `bunx vitest run --silent='passed-only' '[file-path-pattern]'`-- Packages: `cd packages/[package-name] && bunx vitest run --silent='passed-only' '[file-path-pattern]'` (each subpackage contains its own vitest.config.mts)+# Package tests (e.g., database)+cd packages/[package-name] && bunx vitest run --silent='passed-only' '[file-path-pattern]'+```**Important Notes**:- Wrap file paths in single quotes to avoid shell expansion-- Never run `bun run test` - this runs all tests and takes \~10 minutes+- Never run `bun run test` - this runs all tests and takes ~10 minutes### Type Checking@@ -78,40 +86,19 @@ The project follows a well-organized monorepo structure:Follow [Linear rules in CLAUDE.md](CLAUDE.md#linear-issue-management-ignore-if-not-installed-linear-mcp) when working with Linear issues.-## Project Rules Index--All following rules are saved under `.cursor/rules/` directory:--### Backend--- `drizzle-schema-style-guide.mdc` โ Style guide for defining Drizzle ORM schemas--### Frontend--- `react.mdc` โ React component style guide and conventions-- `i18n.mdc` โ Internationalization guide using react-i18next-- `typescript.mdc` โ TypeScript code style guide-- `packages/react-layout-kit.mdc` โ Usage guide for Flexbox and Center components from @lobehub/ui--### State Management--- `zustand-action-patterns.mdc` โ Recommended patterns for organizing Zustand actions-- `zustand-slice-organization.mdc` โ Best practices for structuring Zustand slices--### Desktop (Electron)--- `desktop-feature-implementation.mdc` โ Implementing new Electron desktop features-- `desktop-controller-tests.mdc` โ Desktop controller unit testing guide-- `desktop-local-tools-implement.mdc` โ Workflow to add new desktop local tools-- `desktop-menu-configuration.mdc` โ Desktop menu configuration guide-- `desktop-window-management.mdc` โ Desktop window management guide--### Debugging--- `debug-usage.mdc` โ Using the debug package and namespace conventions--### Testing--- `testing-guide/testing-guide.mdc` โ Comprehensive testing guide for Vitest-- `testing-guide/electron-ipc-test.mdc` โ Electron IPC interface testing strategy-- `testing-guide/db-model-test.mdc` โ Database Model testing guide+## Skills (Auto-loaded)++All AI development skills are available in `.agents/skills/` directory:++| Category | Skills |+|----------|--------|+| Frontend | `react`, `typescript`, `i18n`, `microcopy` |+| State | `zustand` |+| Backend | `drizzle` |+| Desktop | `desktop` |+| Testing | `testing` |+| UI | `modal`, `hotkey`, `recent-data` |+| Config | `add-provider-doc`, `add-setting-env` |+| Workflow | `linear`, `debug` |+| Performance | `vercel-react-best-practices` |+| Overview | `project-overview` |diff --git a/CLAUDE.md b/CLAUDE.mdindex 6ddaaea7799..dc4a72b7d88 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,65 +1,68 @@# CLAUDE.md-This document serves as a shared guideline for all team members when using Claude Code in this opensource lobe-chat(also known as lobehub) repository.+Guidelines for using Claude Code in this LobeChat repository.## Tech Stack-read @.cursor/rules/project-introduce.mdc--## Directory Structure--read @.cursor/rules/project-structure.mdc+- Next.js 16 + React 19 + TypeScript+- SPA inside Next.js with `react-router-dom`+- `@lobehub/ui`, antd for components; antd-style for CSS-in-JS+- react-i18next for i18n; zustand for state management+- SWR for data fetching; TRPC for type-safe backend+- Drizzle ORM with PostgreSQL; Vitest for testing++## Project Structure++```+lobe-chat/+โโโ apps/desktop/ # Electron desktop app+โโโ packages/ # Shared packages (@lobechat/*)+โ โโโ database/ # Database schemas, models, repositories+โ โโโ agent-runtime/ # Agent runtime+โ โโโ ...+โโโ src/+โ โโโ app/ # Next.js app router+โ โโโ store/ # Zustand stores+โ โโโ services/ # Client services+โ โโโ server/ # Server services and routers+โ โโโ ...+โโโ e2e/ # E2E tests (Cucumber + Playwright)+```## Development### Git Workflow-- use rebase for git pull-- git commit message should prefix with gitmoji-- git branch name format template: <type>/<feature-name>-- use .github/PULL_REQUEST_TEMPLATE.md to generate pull request description-- PR titles starting with `โจ feat/` or `๐ fix` will trigger the release workflow upon merge. Only use these prefixes for significant user-facing feature changes or bug fixes+- Use rebase for `git pull`+- Commit messages: prefix with gitmoji+- Branch format: `<type>/<feature-name>`+- PR titles with `โจ feat/` or `๐ fix` trigger releases### Package Management-This repository adopts a monorepo structure.--- Use `pnpm` as the primary package manager for dependency management-- Use `bun` to run npm scripts-- Use `bunx` to run executable npm packages--### TypeScript Code Style Guide--see @.cursor/rules/typescript.mdc--### Code Comments--- **Avoid meaningless comments**: Do not write comments that merely restate what the code does. Comments should explain _why_ something is done, not _what_ is being done. The code itself should be self-explanatory.+- `pnpm` for dependency management+- `bun` to run npm scripts+- `bunx` for executable npm packages### Testing-- **Required Rule**: read `.cursor/rules/testing-guide/testing-guide.mdc` before writing tests-- **Command**:- - web: `bunx vitest run --silent='passed-only' '[file-path-pattern]'`- - packages(eg: database): `cd packages/database && bunx vitest run --silent='passed-only' '[file-path-pattern]'`--**Important**:--- wrap the file path in single quotes to avoid shell expansion-- Never run `bun run test` etc to run tests, this will run all tests and cost about 10mins-- If trying to fix the same test twice, but still failed, stop and ask for help.-- **Prefer `vi.spyOn` over `vi.mock`**: When mocking modules or functions, prefer using `vi.spyOn` to mock specific functions rather than `vi.mock` to mock entire modules. This approach is more targeted, easier to maintain, and allows for better control over mock behavior in individual tests.-- **Tests must pass type check**: After writing or modifying tests, run `bun run type-check` to ensure there are no type errors. Tests should pass both runtime execution and TypeScript type checking.+```bash+# Run specific test (NEVER run `bun run test` - takes ~10 minutes)+bunx vitest run --silent='passed-only' '[file-path]'-### Typecheck+# Database package+cd packages/database && bunx vitest run --silent='passed-only' '[file]'+```-- use `bun run type-check` to check type errors.+- Prefer `vi.spyOn` over `vi.mock`+- Tests must pass type check: `bun run type-check`+- After 2 failed fix attempts, stop and ask for help### i18n-- **Keys**: Add to `src/locales/default/namespace.ts`-- **Dev**: Translate `locales/zh-CN/namespace.json` and `locales/en-US/namespace.json` locales file only for dev preview-- DON'T run `pnpm i18n`, let CI auto handle it+- Add keys to `src/locales/default/namespace.ts`+- For dev preview: translate `locales/zh-CN/` and `locales/en-US/`+- Don't run `pnpm i18n` - CI handles it## Linear Issue Management@@ -72,9 +75,9 @@ see @.cursor/rules/typescript.mdc**Workflow:**1. Use `ToolSearch` to confirm `linear-server` MCP exists (search `linear` or `mcp__linear-server__`)-2. If found, read `.cursor/rules/linear.mdc` and follow the workflow+2. If found, read `.agents/skills/linear/SKILL.md` and follow the workflow3. If not found, skip Linear integration (treat as not installed)-## Rules Index+## Skills (Auto-loaded by Claude)-Some useful project rules are listed in @.cursor/rules/rules-index.mdc+Claude Code automatically loads relevant skills from `.agents/skills/`.diff --git a/GEMINI.md b/GEMINI.mdindex 1b935e59a13..b4cd3a15b74 100644--- a/GEMINI.md+++ b/GEMINI.md@@ -1,64 +1,72 @@# GEMINI.md-This document serves as a shared guideline for all team members when using Gemini CLI in this repository.+Guidelines for using Gemini CLI in this LobeChat repository.## Tech Stack-read @.cursor/rules/project-introduce.mdc--## Directory Structure--read @.cursor/rules/project-structure.mdc+- Next.js 16 + React 19 + TypeScript+- SPA inside Next.js with `react-router-dom`+- `@lobehub/ui`, antd for components; antd-style for CSS-in-JS+- react-i18next for i18n; zustand for state management+- SWR for data fetching; TRPC for type-safe backend+- Drizzle ORM with PostgreSQL; Vitest for testing++## Project Structure++```+lobe-chat/+โโโ apps/desktop/ # Electron desktop app+โโโ packages/ # Shared packages (@lobechat/*)+โ โโโ database/ # Database schemas, models, repositories+โ โโโ agent-runtime/ # Agent runtime+โ โโโ ...+โโโ src/+โ โโโ app/ # Next.js app router+โ โโโ store/ # Zustand stores+โ โโโ services/ # Client services+โ โโโ server/ # Server services and routers+โ โโโ ...+โโโ e2e/ # E2E tests (Cucumber + Playwright)+```## Development### Git Workflow-- use rebase for git pull-- git commit message should prefix with gitmoji-- git branch name format template: <type>/<feature-name>-- use .github/PULL_REQUEST_TEMPLATE.md to generate pull request description-- PR titles starting with `โจ feat/` or `๐ fix` will trigger the release workflow upon merge. Only use these prefixes for significant user-facing feature changes or bug fixes+- Use rebase for `git pull`+- Commit messages: prefix with gitmoji+- Branch format: `<type>/<feature-name>`+- PR titles with `โจ feat/` or `๐ fix` trigger releases### Package Management-This repository adopts a monorepo structure.--- Use `pnpm` as the primary package manager for dependency management-- Use `bun` to run npm scripts-- Use `bunx` to run executable npm packages--### TypeScript Code Style Guide--see @.cursor/rules/typescript.mdc+- `pnpm` for dependency management+- `bun` to run npm scripts+- `bunx` for executable npm packages### Testing-- **Required Rule**: read `.cursor/rules/testing-guide/testing-guide.mdc` before writing tests-- **Command**:- - web: `bunx vitest run --silent='passed-only' '[file-path-pattern]'`- - packages(eg: database): `cd packages/database && bunx vitest run --silent='passed-only' '[file-path-pattern]'`--**Important**:--- wrap the file path in single quotes to avoid shell expansion-- Never run `bun run test` etc to run tests, this will run all tests and cost about 10mins-- If trying to fix the same test twice, but still failed, stop and ask for help.+```bash+# Run specific test (NEVER run `bun run test` - takes ~10 minutes)+bunx vitest run --silent='passed-only' '[file-path]'-### Typecheck+# Database package+cd packages/database && bunx vitest run --silent='passed-only' '[file]'+```-- use `bun run type-check` to check type errors.+- Tests must pass type check: `bun run type-check`+- After 2 failed fix attempts, stop and ask for help### i18n-- **Keys**: Add to `src/locales/default/namespace.ts`-- **Dev**: Translate `locales/zh-CN/namespace.json` and `locales/en-US/namespace.json` locales file only for dev preview-- DON'T run `pnpm i18n`, let CI auto handle it+- Add keys to `src/locales/default/namespace.ts`+- For dev preview: translate `locales/zh-CN/` and `locales/en-US/`+- Don't run `pnpm i18n` - CI handles it-## ๐จ Quality Checks+## Quality Checks-**MANDATORY**: After completing code changes, always run `mcp__vscode-mcp__get_diagnostics` on the modified files to identify any errors introduced by your changes and fix them.+**MANDATORY**: After completing code changes, run diagnostics on modified files to identify and fix any errors.-## Rules Index+## Skills (Auto-loaded)-Some useful project rules are listed in @.cursor/rules/rules-index.mdc+Skills are available in `.agents/skills/` directory. See CLAUDE.md for the full list.diff --git a/src/store/test-coverage.md b/src/store/test-coverage.mdindex f1ec130494d..dd93e68f741 100644--- a/src/store/test-coverage.md+++ b/src/store/test-coverage.md@@ -35,7 +35,7 @@ All 40 action files in the store now have comprehensive test coverage!All store action tests should follow the patterns documented in:-- **Main Guide**: `@.cursor/rules/testing-guide/zustand-store-action-test.mdc`+- **Main Guide**: `.agents/skills/testing/references/zustand-store-action-test.md`Key principles:@@ -141,7 +141,7 @@ For files with multiple action files to test, use the Task tool to create subage**Example subagent prompt**:```-Write comprehensive tests for src/store/discover/slices/plugin/action.ts following @.cursor/rules/testing-guide/zustand-store-action-test.mdc.+Write comprehensive tests for src/store/discover/slices/plugin/action.ts following .agents/skills/testing/references/zustand-store-action-test.md.Requirements:1. Write tests covering all actions in the file@@ -315,7 +315,7 @@ Create 5 subagents, one for each action file:Task({subagent_type: 'general-purpose',description: 'Test plugin action',- prompt: `Write comprehensive tests for src/store/discover/slices/plugin/action.ts following @.cursor/rules/testing-guide/zustand-store-action-test.mdc.+ prompt: `Write comprehensive tests for src/store/discover/slices/plugin/action.ts following .agents/skills/testing/references/zustand-store-action-test.md.Requirements:1. Write tests covering all actions (usePluginCategories, usePluginDetail, usePluginList, usePluginIdentifiers)@@ -330,7 +330,7 @@ DO NOT commit changes or update test-coverage.md.`,Task({subagent_type: 'general-purpose',description: 'Test mcp action',- prompt: `Write comprehensive tests for src/store/discover/slices/mcp/action.ts following @.cursor/rules/testing-guide/zustand-store-action-test.mdc.+ prompt: `Write comprehensive tests for src/store/discover/slices/mcp/action.ts following .agents/skills/testing/references/zustand-store-action-test.md.Requirements:1. Write tests covering all actions (useFetchMcpDetail, useFetchMcpList, useMcpCategories)@@ -561,7 +561,7 @@ bunx eslint src/store/[domain]/- 25 action files already have comprehensive tests (62.5% coverage)- 742 tests written across 80 test files- Well-tested stores: agent, chat (partial), file (partial), image, session, tool, user, global, aiInfra (partial)-- Following zustand testing best practices from `@.cursor/rules/testing-guide/zustand-store-action-test.mdc`+- Following zustand testing best practices from `.agents/skills/testing/references/zustand-store-action-test.md`## Notes