Skip to content

๐Ÿคฏ 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.

โ™ป๏ธ 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.md
new file mode 100644
index 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 docs
diff --git a/.agents/skills/add-setting-env/SKILL.md b/.agents/skills/add-setting-env/SKILL.md
new file mode 100644
index 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.md
new file mode 100644
index 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.md
new file mode 100644
index 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 documentation
diff --git a/.agents/skills/desktop/references/feature-implementation.md b/.agents/skills/desktop/references/feature-implementation.md
new file mode 100644
index 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 feedback
diff --git a/.agents/skills/desktop/references/local-tools.md b/.agents/skills/desktop/references/local-tools.md
new file mode 100644
index 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.md
new file mode 100644
index 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.md
new file mode 100644
index 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.md
new file mode 100644
index 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.md
new file mode 100644
index 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.md
new file mode 100644
index 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 activation
diff --git a/.cursor/rules/i18n.mdc b/.agents/skills/i18n/SKILL.md
similarity index 57%
rename from .cursor/rules/i18n.mdc
rename to .agents/skills/i18n/SKILL.md
index 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
// โœ… Correct
export default {
'alert.cloud.action': '็ซ‹ๅณไฝ“้ชŒ',
- 'clientDB.error.desc': 'ๆ•ฐๆฎๅบ“ๅˆๅง‹ๅŒ–้‡ๅˆฐ้—ฎ้ข˜',
'sync.actions.sync': '็ซ‹ๅณๅŒๆญฅ',
'sync.status.ready': 'ๅทฒ่ฟžๆŽฅ',
};
-// โŒ Avoid: Nested objects
+// โŒ Avoid nested objects
export 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');
-// Basic
t('newFeature.title')
-// With parameters
t('alert.cloud.desc', { credit: '1000' })
+
// Multiple namespaces
const { 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, topic
diff --git a/.agents/skills/linear/SKILL.md b/.agents/skills/linear/SKILL.md
new file mode 100644
index 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.md
new file mode 100644
index 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.md
new file mode 100644
index 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.md
similarity index 54%
rename from .cursor/rules/project-structure.mdc
rename to .agents/skills/project-overview/SKILL.md
index 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.md
new file mode 100644
index 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.md
new file mode 100644
index 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 layouts
diff --git a/.agents/skills/recent-data/SKILL.md b/.agents/skills/recent-data/SKILL.md
new file mode 100644
index 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 optimization
diff --git a/.agents/skills/testing/SKILL.md b/.agents/skills/testing/SKILL.md
new file mode 100644
index 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 hooks
diff --git a/.agents/skills/testing/references/agent-runtime-e2e.md b/.agents/skills/testing/references/agent-runtime-e2e.md
new file mode 100644
index 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 logs
diff --git a/.agents/skills/testing/references/db-model-test.md b/.agents/skills/testing/references/db-model-test.md
new file mode 100644
index 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.md
new file mode 100644
index 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.md
new file mode 100644
index 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 correctly
diff --git a/.agents/skills/testing/references/zustand-store-action-test.md b/.agents/skills/testing/references/zustand-store-action-test.md
new file mode 100644
index 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.md
new file mode 100644
index 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 package
diff --git a/.agents/vercel-react-best-practices/AGENTS.md b/.agents/skills/vercel-react-best-practices/AGENTS.md
similarity index 100%
rename from .agents/vercel-react-best-practices/AGENTS.md
rename to .agents/skills/vercel-react-best-practices/AGENTS.md
diff --git a/.agents/vercel-react-best-practices/SKILL.md b/.agents/skills/vercel-react-best-practices/SKILL.md
similarity index 100%
rename from .agents/vercel-react-best-practices/SKILL.md
rename to .agents/skills/vercel-react-best-practices/SKILL.md
diff --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.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/advanced-event-handler-refs.md
rename to .agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md
diff --git a/.agents/vercel-react-best-practices/rules/advanced-use-latest.md b/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/advanced-use-latest.md
rename to .agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md
diff --git a/.agents/vercel-react-best-practices/rules/async-api-routes.md b/.agents/skills/vercel-react-best-practices/rules/async-api-routes.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/async-api-routes.md
rename to .agents/skills/vercel-react-best-practices/rules/async-api-routes.md
diff --git a/.agents/vercel-react-best-practices/rules/async-defer-await.md b/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/async-defer-await.md
rename to .agents/skills/vercel-react-best-practices/rules/async-defer-await.md
diff --git a/.agents/vercel-react-best-practices/rules/async-dependencies.md b/.agents/skills/vercel-react-best-practices/rules/async-dependencies.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/async-dependencies.md
rename to .agents/skills/vercel-react-best-practices/rules/async-dependencies.md
diff --git a/.agents/vercel-react-best-practices/rules/async-parallel.md b/.agents/skills/vercel-react-best-practices/rules/async-parallel.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/async-parallel.md
rename to .agents/skills/vercel-react-best-practices/rules/async-parallel.md
diff --git a/.agents/vercel-react-best-practices/rules/async-suspense-boundaries.md b/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/async-suspense-boundaries.md
rename to .agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md
diff --git a/.agents/vercel-react-best-practices/rules/bundle-barrel-imports.md b/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/bundle-barrel-imports.md
rename to .agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md
diff --git a/.agents/vercel-react-best-practices/rules/bundle-conditional.md b/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/bundle-conditional.md
rename to .agents/skills/vercel-react-best-practices/rules/bundle-conditional.md
diff --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.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/bundle-defer-third-party.md
rename to .agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md
diff --git a/.agents/vercel-react-best-practices/rules/bundle-dynamic-imports.md b/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/bundle-dynamic-imports.md
rename to .agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md
diff --git a/.agents/vercel-react-best-practices/rules/bundle-preload.md b/.agents/skills/vercel-react-best-practices/rules/bundle-preload.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/bundle-preload.md
rename to .agents/skills/vercel-react-best-practices/rules/bundle-preload.md
diff --git a/.agents/vercel-react-best-practices/rules/client-event-listeners.md b/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/client-event-listeners.md
rename to .agents/skills/vercel-react-best-practices/rules/client-event-listeners.md
diff --git a/.agents/vercel-react-best-practices/rules/client-localstorage-schema.md b/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/client-localstorage-schema.md
rename to .agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md
diff --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.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/client-passive-event-listeners.md
rename to .agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md
diff --git a/.agents/vercel-react-best-practices/rules/client-swr-dedup.md b/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/client-swr-dedup.md
rename to .agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md
diff --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.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/js-batch-dom-css.md
rename to .agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md
diff --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.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/js-cache-function-results.md
rename to .agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md
diff --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.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/js-cache-property-access.md
rename to .agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md
diff --git a/.agents/vercel-react-best-practices/rules/js-cache-storage.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/js-cache-storage.md
rename to .agents/skills/vercel-react-best-practices/rules/js-cache-storage.md
diff --git a/.agents/vercel-react-best-practices/rules/js-combine-iterations.md b/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/js-combine-iterations.md
rename to .agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md
diff --git a/.agents/vercel-react-best-practices/rules/js-early-exit.md b/.agents/skills/vercel-react-best-practices/rules/js-early-exit.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/js-early-exit.md
rename to .agents/skills/vercel-react-best-practices/rules/js-early-exit.md
diff --git a/.agents/vercel-react-best-practices/rules/js-hoist-regexp.md b/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/js-hoist-regexp.md
rename to .agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md
diff --git a/.agents/vercel-react-best-practices/rules/js-index-maps.md b/.agents/skills/vercel-react-best-practices/rules/js-index-maps.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/js-index-maps.md
rename to .agents/skills/vercel-react-best-practices/rules/js-index-maps.md
diff --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.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/js-length-check-first.md
rename to .agents/skills/vercel-react-best-practices/rules/js-length-check-first.md
diff --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.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/js-min-max-loop.md
rename to .agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md
diff --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.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/js-set-map-lookups.md
rename to .agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md
diff --git a/.agents/vercel-react-best-practices/rules/js-tosorted-immutable.md b/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/js-tosorted-immutable.md
rename to .agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md
diff --git a/.agents/vercel-react-best-practices/rules/rendering-activity.md b/.agents/skills/vercel-react-best-practices/rules/rendering-activity.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rendering-activity.md
rename to .agents/skills/vercel-react-best-practices/rules/rendering-activity.md
diff --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.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md
rename to .agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md
diff --git a/.agents/vercel-react-best-practices/rules/rendering-conditional-render.md b/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rendering-conditional-render.md
rename to .agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md
diff --git a/.agents/vercel-react-best-practices/rules/rendering-content-visibility.md b/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rendering-content-visibility.md
rename to .agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md
diff --git a/.agents/vercel-react-best-practices/rules/rendering-hoist-jsx.md b/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rendering-hoist-jsx.md
rename to .agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md
diff --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.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md
rename to .agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md
diff --git a/.agents/vercel-react-best-practices/rules/rendering-svg-precision.md b/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rendering-svg-precision.md
rename to .agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md
diff --git a/.agents/vercel-react-best-practices/rules/rerender-defer-reads.md b/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rerender-defer-reads.md
rename to .agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md
diff --git a/.agents/vercel-react-best-practices/rules/rerender-dependencies.md b/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rerender-dependencies.md
rename to .agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md
diff --git a/.agents/vercel-react-best-practices/rules/rerender-derived-state.md b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rerender-derived-state.md
rename to .agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md
diff --git a/.agents/vercel-react-best-practices/rules/rerender-functional-setstate.md b/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rerender-functional-setstate.md
rename to .agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md
diff --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.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rerender-lazy-state-init.md
rename to .agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md
diff --git a/.agents/vercel-react-best-practices/rules/rerender-memo.md b/.agents/skills/vercel-react-best-practices/rules/rerender-memo.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rerender-memo.md
rename to .agents/skills/vercel-react-best-practices/rules/rerender-memo.md
diff --git a/.agents/vercel-react-best-practices/rules/rerender-transitions.md b/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/rerender-transitions.md
rename to .agents/skills/vercel-react-best-practices/rules/rerender-transitions.md
diff --git a/.agents/vercel-react-best-practices/rules/server-after-nonblocking.md b/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/server-after-nonblocking.md
rename to .agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md
diff --git a/.agents/vercel-react-best-practices/rules/server-cache-lru.md b/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/server-cache-lru.md
rename to .agents/skills/vercel-react-best-practices/rules/server-cache-lru.md
diff --git a/.agents/vercel-react-best-practices/rules/server-cache-react.md b/.agents/skills/vercel-react-best-practices/rules/server-cache-react.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/server-cache-react.md
rename to .agents/skills/vercel-react-best-practices/rules/server-cache-react.md
diff --git a/.agents/vercel-react-best-practices/rules/server-parallel-fetching.md b/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/server-parallel-fetching.md
rename to .agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md
diff --git a/.agents/vercel-react-best-practices/rules/server-serialization.md b/.agents/skills/vercel-react-best-practices/rules/server-serialization.md
similarity index 100%
rename from .agents/vercel-react-best-practices/rules/server-serialization.md
rename to .agents/skills/vercel-react-best-practices/rules/server-serialization.md
diff --git a/.agents/skills/zustand/SKILL.md b/.agents/skills/zustand/SKILL.md
new file mode 100644
index 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.md
new file mode 100644
index 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.md
new file mode 100644
index 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 slice
diff --git a/.codex/skills b/.codex/skills
index 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 file
diff --git a/.cursor/rules/add-provider-doc.mdc b/.cursor/rules/add-provider-doc.mdc
deleted file mode 100644
index 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 file
diff --git a/.cursor/rules/add-setting-env.mdc b/.cursor/rules/add-setting-env.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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 testing
diff --git a/.cursor/rules/react.mdc b/.cursor/rules/react.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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 guide
diff --git a/.cursor/rules/testing-guide/agent-runtime-e2e.mdc b/.cursor/rules/testing-guide/agent-runtime-e2e.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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 environments
diff --git a/.cursor/rules/testing-guide/zustand-store-action-test.mdc b/.cursor/rules/testing-guide/zustand-store-action-test.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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.mdc
deleted file mode 100644
index 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/skills
index 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 file
diff --git a/AGENTS.md b/AGENTS.md
index 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.md
index 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 workflow
3. 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.md
index 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.md
index 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