pull/1487/merge
UnCLAS-Prommer 2026-02-24 08:01:55 +00:00 committed by GitHub
commit bc832a4d23
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
387 changed files with 41320 additions and 16467 deletions

View File

@ -4,7 +4,7 @@ on: [pull_request]
jobs:
conflict-check:
runs-on: [self-hosted, Windows, X64]
runs-on: ubuntu-24.04
outputs:
conflict: ${{ steps.check-conflicts.outputs.conflict }}
steps:
@ -25,7 +25,7 @@ jobs:
}
shell: pwsh
labeler:
runs-on: [self-hosted, Windows, X64]
runs-on: ubuntu-24.04
needs: conflict-check
if: needs.conflict-check.outputs.conflict == 'true'
steps:

View File

@ -0,0 +1,98 @@
name: Publish WebUI Dist
on:
push:
branches:
- main
- dev
- r-dev
paths:
- "dashboard/**"
workflow_dispatch:
permissions:
contents: read
jobs:
build-and-publish:
runs-on: ubuntu-24.04
environment: webui
steps:
- uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: "1.2.0"
- name: Build dashboard
working-directory: dashboard
run: |
bun install
bun run build
- name: Prepare dist package
run: |
rm -rf .webui_dist_pkg
mkdir -p .webui_dist_pkg/maibot_dashboard/dist
BASE_VERSION=$(python -c "import json; print(json.load(open('dashboard/package.json'))['version'])")
if [ "${GITHUB_REF_NAME}" = "main" ]; then
WEBUI_VERSION="${BASE_VERSION}"
else
TODAY=$(date -u +%Y%m%d)
WEBUI_VERSION="${BASE_VERSION}.dev${TODAY}${GITHUB_RUN_NUMBER}"
fi
cat > .webui_dist_pkg/pyproject.toml <<EOF
[project]
name = "maibot-dashboard"
version = "${WEBUI_VERSION}"
description = "MaiBot WebUI static assets"
readme = "README.md"
requires-python = ">=3.10"
[build-system]
requires = ["setuptools>=80.9.0", "wheel"]
build-backend = "setuptools.build_meta"
[tool.setuptools]
include-package-data = true
[tool.setuptools.packages.find]
where = ["."]
include = ["maibot_dashboard"]
exclude = ["maibot_dashboard.dist*"]
[tool.setuptools.package-data]
maibot_dashboard = ["dist/**"]
EOF
cat > .webui_dist_pkg/README.md <<'EOF'
# MaiBot WebUI Dist
该包仅包含 MaiBot WebUI 的前端构建产物dist
EOF
cat > .webui_dist_pkg/maibot_dashboard/__init__.py <<'EOF'
from .resources import get_dist_path
__all__ = ["get_dist_path"]
EOF
cat > .webui_dist_pkg/maibot_dashboard/resources.py <<'EOF'
from pathlib import Path
def get_dist_path() -> Path:
return Path(__file__).parent / "dist"
EOF
cp -a dashboard/dist/. .webui_dist_pkg/maibot_dashboard/dist/
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Build and publish
working-directory: .webui_dist_pkg
env:
PYPI_API_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
run: |
python -m pip install --upgrade build twine
python -m build
python -m twine upload -u __token__ -p "$PYPI_API_TOKEN" dist/*

View File

@ -2,7 +2,7 @@ name: Ruff PR Check
on: [ pull_request ]
jobs:
ruff:
runs-on: [self-hosted, Windows, X64]
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:

View File

@ -8,17 +8,12 @@ on:
# - dev-refactor # 例如:匹配所有以 feature/ 开头的分支
# # 添加你希望触发此 workflow 的其他分支
workflow_dispatch: # 允许手动触发工作流
branches:
- main
- dev
- dev-refactor
permissions:
contents: write
jobs:
ruff:
runs-on: [self-hosted, Windows, X64]
runs-on: ubuntu-24.04
# 关键修改:添加条件判断
# 确保只有在 event_name 是 'push' 且不是由 Pull Request 引起的 push 时才运行
if: github.event_name == 'push' && !startsWith(github.ref, 'refs/pull/')

3
.gitignore vendored
View File

@ -38,6 +38,7 @@ queue_update.txt
.env
.env.*
.cursor
start_all.bat
config/bot_config_dev.toml
config/bot_config.toml
config/bot_config.toml.bak
@ -91,7 +92,6 @@ develop-eggs/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
@ -353,3 +353,4 @@ interested_rates.txt
MaiBot.code-workspace
*.lock
actionlint
.sisyphus/

12
AGENTS.md 100644
View File

@ -0,0 +1,12 @@
# import 规范
在从外部库进行导入时候,请遵循以下顺序:
1. 对于标准库和第三方库的导入,请按照如下顺序:
- 需要使用`from ... import ...`语法的导入放在前面。
- 直接使用`import ...`语法的导入放在后面。
- 对于使用`from ... import ...`导入的多个项,请**在保证不会引起import错误的前提下**,按照**字母顺序**排列。
- 对于使用`import ...`导入的多个项,请**在保证不会引起import错误的前提下**,按照**字母顺序**排列。
2. 对于本地模块的导入,请按照如下顺序:
- 对于同一个文件夹下的模块导入,使用相对导入,排列顺序按照**不发生import错误的前提下**,随便排列。
- 对于不同文件夹下的模块导入,使用绝对导入。这些导入应该以`from src`开头,并且按照**不发生import错误的前提下**,尽量使得第二层的文件夹名称相同的导入放在一起;第二层文件夹名称排列随机。
3. 标准库和第三方库的导入应该放在本地模块导入的前面。
4. 各个导入块之间应该使用一个空行进行分隔。

20
bot.py
View File

@ -1,3 +1,4 @@
# raise RuntimeError("System Not Ready")
import asyncio
import hashlib
import os
@ -43,6 +44,11 @@ logger = get_logger("main")
# 定义重启退出码
RESTART_EXIT_CODE = 42
print("-----------------------------------------")
print("\n\n\n\n\n")
print("警告Dev进入不稳定开发状态任何插件与WebUI均可能无法正常工作")
print("\n\n\n\n\n")
print("-----------------------------------------")
def run_runner_process():
@ -180,14 +186,14 @@ async def graceful_shutdown(): # sourcery skip: use-named-expression
logger.info("正在优雅关闭麦麦...")
# 关闭 WebUI 服务器
try:
from src.webui.webui_server import get_webui_server
# try:
# from src.webui.webui_server import get_webui_server
webui_server = get_webui_server()
if webui_server and webui_server._server:
await webui_server.shutdown()
except Exception as e:
logger.warning(f"关闭 WebUI 服务器时出错: {e}")
# webui_server = get_webui_server()
# if webui_server and webui_server._server:
# await webui_server.shutdown()
# except Exception as e:
# logger.warning(f"关闭 WebUI 服务器时出错: {e}")
from src.plugin_system.core.events_manager import events_manager
from src.plugin_system.base.component_types import EventType

View File

@ -0,0 +1,732 @@
# Mai NEXT 设计文档
Version 0.2.2 - 2025-11-05
## 配置文件设计
主体利用`pydantic`的`BaseModel`进行配置类设计`ConfigBase`类
要求每个属性必须具有类型注解,且类型注解满足以下要求:
- 原子类型仅允许使用: `str`, `int`, `float`, `bool`, 以及基于`ConfigBase`的嵌套配置类
- 复杂类型允许使用: `list`, `dict`, `set`,但其内部类型必须为原子类型或嵌套配置类,不可使用`list[list[int]]`,`list[dict[str, int]]`等写法
- 禁止了使用`Union`, `tuple/Tuple`类型
- 但是`Optional`仍然允许使用
### 移除template的方案提案
<details>
<summary>配置项说明的废案</summary>
<p>方案一</p>
<pre>
from typing import Annotated
from dataclasses import dataclass, field
@dataclass
class Config:
value: Annotated[str, "配置项说明"] = field(default="default_value")
</pre>
<p>方案二(不推荐)</p>
<pre>
from dataclasses import dataclass, field
@dataclass
class Config:
@property
def value(self) -> str:
"""配置项说明"""
return "default_value"
</pre>
<p>方案四</p>
<pre>
from dataclasses import dataclass, field
@dataclass
class Config:
value: str = field(default="default_value", metadata={"doc": "配置项说明"})
</pre>
</details>
- [x] 方案三(个人推荐)
```python
import ast, inspect
class AttrDocBase:
...
from dataclasses import dataclass, field
@dataclass
class Config(ConfigBase, AttrDocBase):
value: str = field(default="default_value")
"""配置项说明"""
```
### 配置文件实现热重载
#### 整体架构设计
- [x] 文件监视器
- [x] 监视文件变化
- [x] 使用 `watchfiles` 监视配置文件变化(提案)
- [ ] <del>备选提案:使用纯轮询监视文件变化</del>
- [x] <del>使用Hash检查文件变化</del>`watchfiles`实现)
- [x] 防抖处理(使用`watchfiles`的防抖)
- [x] 重新分发监视事件,正确监视文件变化
- [ ] 配置管理器
- [x] 配置文件读取和加载
- [ ] 重载配置
- [ ] 管理全部配置数据
- [ ] `validate_config` 方法
- [ ] <del>回调管理器</del>(合并到文件监视器中)
- [x] `callback` 注册与注销
- [ ] <del>按优先级执行回调(提案)</del>
- [x] 错误隔离
- [ ] 锁机制
#### 工作流程
```
1. 文件监视器检测变化
2. 配置管理器加锁重载
3. 验证新配置 (失败保持旧配置)
4. 更新内存数据
5. 回调管理器按优先级执行回调 (错误隔离)
6. 释放锁
```
#### 回调执行策略
1. <del>优先级顺序(提案): 数字越小优先级越高,同优先级异步回调并行执行</del>
2. 错误处理: 单个回调失败不影响其他回调
#### 代码框架
实际代码实现与下类似,但是进行了调整
`ConfigManager` - 配置管理器:
```python
import asyncio
import tomlkit
from typing import Any, Dict, Optional
from pathlib import Path
class ConfigManager:
def __init__(self, config_path: str):
self.config_path: Path = Path(config_path)
self.config_data: Dict[str, Any] = {}
self._lock: asyncio.Lock = asyncio.Lock()
self._file_watcher: Optional["FileWatcher"] = None
self._callback_manager: Optional["CallbackManager"] = None
async def initialize(self) -> None:
"""异步初始化,加载配置并启动监视"""
pass
async def load_config(self) -> Dict[str, Any]:
"""异步加载配置文件"""
pass
async def reload_config(self) -> bool:
"""热重载配置,返回是否成功"""
pass
def get_item(self, key: str, default: Any = None) -> Any:
"""获取配置项,支持嵌套访问 (如 'section.key')"""
pass
async def set_item(self, key: str, value: Any) -> None:
"""设置配置项并触发回调"""
pass
def validate_config(self, config: Dict[str, Any]) -> bool:
"""验证配置合法性"""
pass
```
<details>
<summary>回调管理器(废案)</summary>
`CallbackManager` - 回调管理器:
```python
import asyncio
from dataclasses import dataclass, field
class CallbackManager:
def __init__(self):
self._callbacks: Dict[str, List[CallbackEntry]] = {}
self._global_callbacks: List[CallbackEntry] = []
def register(
self,
key: str,
callback: Callable[[Any], Union[None, asyncio.Future]],
priority: int = 100,
name: str = ""
) -> None:
"""注册回调函数priority为正整数数字越小优先级越高"""
pass
def unregister(self, key: str, callback: Callable) -> None:
"""注销回调函数"""
pass
async def trigger(self, key: str, value: Any) -> None:
"""触发回调,按优先级执行(数字小的先执行),错误隔离"""
pass
def enable_callback(self, key: str, name: str) -> None:
"""启用指定回调"""
pass
def disable_callback(self, key: str, name: str) -> None:
"""禁用指定回调"""
pass
```
对于CallbackManager中的优先级功能说明
- 数字越小优先级越高
- 为什么要有优先级系统:
- 理论上来说,在热重载配置之后,应该要通过回调函数管理器触发所有回调函数,模拟启动的过程,类似于“重启”
- 而优先级模块是保证某一些模块的重载顺序一定是晚于某一些地基模块的
- 例如:内置服务器的启动应该是晚于所有模块,即最后启动
</details>
`FileWatcher` - 文件监视器:
```python
import asyncio
from watchfiles import awatch, Change
from pathlib import Path
class FileWatcher:
def __init__(self, debounce_ms: int = 500):
self.debounce_ms: int = debounce_ms
def start(self, on_change: Callable) -> None:
"""启动文件监视"""
pass
def stop(self) -> None:
"""停止文件监视"""
pass
async def invoke_callback(self) -> None:
"""调用变化回调函数"""
pass
```
#### 配置文件写入
- [x] 将当前文件写入toml文件
## 消息部分设计
解决原有的将消息类与数据库类存储不匹配的问题,现在存储所有消息类的所有属性
完全合并`stream_id`和`chat_id`为`chat_id`,规范名称
`chat_stream`重命名为`chat_session`,表示一个会话
### 消息类设计
- [ ] 支持并使用maim_message新的`SenderInfo`和`ReceiverInfo`构建消息
- [ ] 具体使用参考附录
- [ ] 适配器处理跟进该更新
- [ ] 修复适配器的类型检查问题
- [ ] 设计更好的平台消息ID回传机制
- [ ] 考虑使用事件依赖机制
### 图片处理系统
- [ ] 规范化Emojis与Images的命名统一保存
### 消息到Prompt的构建提案
- [ ] <del>类QQ的时间系统即不是每条消息加时间戳而是分大时间段加时间戳</del>(此功能已实现,但效果不佳)
- [ ] 消息编号系统(已经有的)
- [ ] 思考打断,如何判定是否打断?
- [ ] 如何判定消息是连贯的MoFox: 一个反比例函数???太神秘了)
### 消息进入处理
使用轮询机制,每隔一段时间检查缓存中是否有新消息
---
## 数据库部分设计
合并Emojis和Images到同一个表中
数据库ORM应该使用SQLModel而不是peeweepeewee我这辈子都不会用它了
### 数据库缓存层设计
将部分消息缓存到内存中,减少数据库访问,在主程序处理完之后再写入数据库
要求:对上层调用保持透明
- [ ] 数据库内容管理类 `DatabaseManager`
- [ ] 维护数据库连接
- [ ] 提供增删改查接口
- [ ] 维护缓存类 `DatabaseMessageCache` 的实例
- [ ] 缓存类 `DatabaseMessageCache`
- [ ] **设计缓存失效机制**
- [ ] 设计缓存更新机制
- [ ] `add_message`
- [ ] `update_message` (提案)
- [ ] `delete_message`
- [ ] 与数据库交互部分设计
- [ ] 维持现有的数据库sqlite
- [ ] 继续使用peewee进行操作
### 消息表设计
- [ ] 设计内部消息ID和平台消息ID两种形式
- [ ] 临时消息ID不进入数据库
- [ ] 消息有关信息设计
- [ ] 消息ID
- [ ] 发送者信息
- [ ] 接收者信息
- [ ] 消息内容
- [ ] 消息时间戳
- [ ] 待定
### Emojis与Images表设计
- [ ] 设计图片专有ID并作为文件名
### Expressions表设计
- [ ] 待定
### 表实际设计
#### ActionRecords 表
- [ ] 动作唯一ID `action_id`
- [ ] 动作执行时间 `action_time`
- [ ] 动作名称 `action_name`
- [ ] 动作参数 `action_params` JSON格式存储原`action_data`
---
## 数据模型部分设计
- [ ] <del>Message从数据库反序列化不再使用额外的Message类</del>(放弃)
- [ ] 设计 `BaseModel` 类,作为所有数据模型的基类
- [ ] 提供通用的序列化和反序列化方法(提案)
---
## 核心业务逻辑部分设计
### Prompt 设计
将Prompt内容彻底模块化设计
- [ ] 设计 Prompt 类
- [ ] `__init__(self, template: list[str], *, **kwargs)` 维持现有的template设计但不进行format直到最后传入LLM时再进行render
- [ ] `__init__`中允许传入任意的键值对,存储在`self.context`中
- [ ] `self.prompt_name` 作为Prompt的名称
- [ ] `self.construct_function: Dict[str, Callable | AsyncCallable]` 构建Prompt内容所需的函数字典
- [ ] 格式:`{"block_name": function_reference}`
- [ ] `self.content_block: Dict[str, str]`: 实际的Prompt内容块
- [ ] 格式:`{"block_name": "Unrendered Prompt Block"}`
- [ ] `render(self) -> str` 使用非递归渲染方式渲染Prompt内容
- [ ] `add_construct_function(self, name: str, func: Callable | AsyncCallable, *, suppress: bool = False)` 添加构造函数
- [ ] 实现重名警告/错误(偏向错误)
- [ ] `suppress`: 是否覆盖已有的构造函数
- [ ] `remove_construct_function(self, name: str)` 移除指定名称的构造函数
- [ ] `add_block(self, prompt_block: "Prompt", block_name: str, *, suppress: bool = False)` 将另一个Prompt的内容更新到当前Prompt中
- [ ] 实现重名属性警告/错误(偏向错误)
- [ ] 实现重名构造函数警告/错误(偏向错误)
- [ ] `suppress`: 是否覆盖已有的内容块和构造函数
- [ ] `remove_block(self, block_name: str)` 移除指定名称的Prompt块
- [ ] 设计 PromptManager 类
- [ ] `__init__(self)` 初始化一个空的Prompt管理器
- [ ] `add_prompt(self, name: str, prompt: Prompt)` 添加一个新的Prompt
- [ ] 实现重名警告/错误(偏向错误)
- [ ] `get_prompt(self, name: str) -> Prompt` 根据名称获取Prompt
- [ ] 实现不存在时的错误处理
- [ ] `remove_prompt(self, name: str)` 移除指定名称的Prompt
- [ ] 系统 Prompt 保护
- [ ] `list_prompts(self) -> list[str]` 列出所有已添加的Prompt名称
### 内建好奇插件设计
- [ ] 设计“麦麦好奇”插件
- [ ] 解决麦麦乱好奇的问题
- [ ] 好奇问题无回复清理
- [ ] 好奇问题超时清理
- [ ] 根据聊天内容选择个性化好奇问题
- [ ] 好奇频率控制
---
## 插件系统部分设计
### <del>设计一个插件沙盒系统</del>(放弃)
### 插件管理
- [ ] 插件管理器类 `PluginManager` 的更新
- [ ] 重写现有的插件文件加载逻辑,精简代码,方便重载
- [ ] 学习AstrBot的基于子类加载的插件加载方式放弃@register_plugin提案
- [ ] 直接 breaking change 删除 @register_plugin 函数,不保留过去插件的兼容性(提案)
- [ ] 设计插件重载系统
- [ ] 插件配置文件重载
- [ ] 复用`FileWatcher`实现配置文件热重载
- [ ] 插件代码重载
- [ ] 从插件缓存中移除此插件对应的模块
- [ ] 从组件管理器中移除该插件对应的组件
- [ ] 重新导入该插件模块
- [ ] 插件可以设计为禁止热重载类型
- [ ] 通过字段`allow_hot_reload: bool`指定
- [ ] Napcat Adapter插件设计为禁止热重载类型
- [ ] 其余细节待定
- [ ] 组件管理器类 `ComponentManager` 的更新
- [ ] 配合插件重载系统的更好的组件管理代码
- [ ] 组件全局控制和局部控制的平级化(提案)
- [ ] 重新设计组件注册和注销逻辑,分离激活和注册
- [ ] 可以修改组件的属性
- [ ] 组件系统卸载
- [ ] 联动插件卸载(方便重载设计)
- [ ] 其余细节待定
- [ ] 因重载机制设计的更丰富的`plugin_meta`和`component_meta`
- [ ] `component_meta`增加`plugin_file`字段,指向插件文件路径,保证重载时组件能正确更新
- [ ] `plugin_meta`增加`sub_components`字段,指示该插件包含的组件列表,方便重载时更新
- [ ] `sub_components`内容为组件类名列表
### 插件激活方式的动态设计
- [ ] 设计可变的插件激活方式
- [ ] 直接读写类属性`activate_types`
### 真正的插件重载
- [ ] 使用上文中提到的配置文件热重载机制
- [ ] FileWatcher的复用
### 传递内容设计
对于传入的Prompt使用上文提到的Prompt类进行管理方便内容修改避免正则匹配式查找
### MCP 接入(大饼)
- [ ] 设计 MCP 适配器类 `MCPAdapter`
- [ ] MCP 调用构建说明Prompt
- [ ] MCP 调用内容传递
- [ ] MCP 调用结果处理
### 工具结果的缓存设计
可能的使用案例参考[附录-工具缓存](#工具缓存可能用例)
- [ ] `put_cache(**kwargs, *, _component_name: str)` 方法
- [ ] 设计为父类的方法,插件继承后使用
- [ ] `_component_name` 指定当前组件名称由MaiNext自动传入
- [ ] `get_cache` 方法
- [ ] `need_cache` 变量管理是否调用缓存结果
- [ ] 仅在设置为True时为插件创立缓存空间
### Events依赖机制提案
- [ ] 通过Events的互相依赖完成链式任务
- [ ] 设计动态调整events_handler执行顺序的机制 (感谢@OctAutumn老师伟大无需多言)
- [ ] 作为API暴露方便用户使用
### 正式的插件依赖管理系统
- [ ] requirements.txt分析
- [ ] python_dependencies分析
- [ ] 自动安装
- [ ] plugin_dependencies分析
- [ ] 拓扑排序
#### 插件依赖管理器设计
使用 `importlib.metadata` 进行插件依赖管理,实现自动依赖检查和安装功能
`PluginDependencyManager` - 插件依赖管理器:
```python
import importlib.metadata
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
@dataclass
class DependencyInfo:
"""依赖信息"""
name: str
required_version: str
installed_version: Optional[str] = None
is_satisfied: bool = False
class PluginDependencyManager:
def __init__(self):
self._installed_packages: Dict[str, str] = {}
self._dependency_cache: Dict[str, List[DependencyInfo]] = {}
def scan_installed_packages(self) -> Dict[str, str]:
"""
扫描已安装的所有Python包
使用 importlib.metadata.distributions() 获取所有已安装的包
返回 {包名: 版本号} 的字典
"""
pass
def parse_plugin_dependencies(self, plugin_config: Dict) -> List[DependencyInfo]:
"""
解析插件配置中的依赖信息
从 plugin_config 中提取 python_dependencies 字段
支持多种版本指定格式: ==, >=, <=, >, <, ~=
返回依赖信息列表
"""
pass
def check_dependencies(
self,
plugin_name: str,
dependencies: List[DependencyInfo]
) -> Tuple[List[DependencyInfo], List[DependencyInfo]]:
"""
检查插件依赖是否满足
对比插件要求的依赖版本与已安装的包版本
返回 (满足的依赖列表, 不满足的依赖列表)
"""
pass
def compare_version(
self,
installed_version: str,
required_version: str
) -> bool:
"""
比较版本号是否满足要求
支持版本操作符: ==, >=, <=, >, <, ~=
使用 packaging.version 进行版本比较
返回是否满足要求
"""
pass
async def install_dependencies(
self,
dependencies: List[DependencyInfo],
*,
upgrade: bool = False
) -> bool:
"""
安装缺失或版本不匹配的依赖
调用 pip install 安装指定版本的包
upgrade: 是否升级已有包
返回安装是否成功
"""
pass
def get_dependency_tree(self, plugin_name: str) -> Dict[str, List[str]]:
"""
获取插件的完整依赖树
递归分析插件依赖的包及其子依赖
返回依赖关系图
"""
pass
def validate_all_plugins(self) -> Dict[str, bool]:
"""
验证所有已加载插件的依赖完整性
返回 {插件名: 依赖是否满足} 的字典
"""
pass
```
#### 依赖管理工作流程
```
1. 插件加载时触发依赖检查
2. PluginDependencyManager.scan_installed_packages() 扫描已安装包
3. PluginDependencyManager.parse_plugin_dependencies() 解析插件依赖
4. PluginDependencyManager.check_dependencies() 对比版本
5. 如果依赖不满足:
a. 记录缺失/版本不匹配的依赖
b. (可选) 自动调用 install_dependencies() 安装
c. 重新验证依赖
6. 依赖满足后加载插件,否则跳过并警告
```
#### TODO List
- [ ] 实现 `scan_installed_packages()` 方法
- [ ] 使用 `importlib.metadata.distributions()` 获取所有包
- [ ] 规范化包名(处理大小写、下划线/横杠问题)
- [ ] 缓存结果以提高性能
- [ ] 实现 `parse_plugin_dependencies()` 方法
- [ ] 支持多种依赖格式解析
- [ ] 验证版本号格式合法性
- [ ] 处理无版本要求的依赖
- [ ] 实现 `compare_version()` 方法
- [ ] 集成 `packaging.version`
- [ ] 支持所有 PEP 440 版本操作符
- [ ] 处理预发布版本、本地版本标识符
- [ ] 实现 `check_dependencies()` 方法
- [ ] 逐个检查依赖是否已安装
- [ ] 比对版本是否满足要求
- [ ] 生成详细的依赖检查报告
- [ ] 实现 `install_dependencies()` 方法
- [ ] 调用 pip 子进程安装包
- [ ] 支持指定 PyPI 镜像源
- [ ] 错误处理和回滚机制
- [ ] 安装进度反馈
- [ ] 实现依赖冲突检测
- [ ] 检测不同插件间的依赖版本冲突
- [ ] 提供冲突解决建议
- [ ] 实现依赖缓存机制(可选)
- [ ] 缓存已检查的依赖结果
- [ ] 定期刷新缓存
- [ ] 集成到 `PluginManager`
- [ ] 在插件加载前进行依赖检查
- [ ] 依赖不满足时的处理策略(警告/阻止加载/自动安装)
- [ ] 提供手动触发依赖检查的接口
- [ ] 日志和报告
- [ ] 记录依赖安装日志
- [ ] 生成依赖关系报告
- [ ] 依赖问题的用户友好提示
### 插件系统API更改
#### Events 设计
- [ ] 设计events.api
- [ ] `emit(type: EventType | str, * , **kwargs)` 广播事件,使用关键字参数保证传入正确
- [ ] `order_change` 动态调整事件处理器执行顺序
#### 组件控制API更新
- [ ] 增加可以更改组件属性的方法
- [ ] 验证组件属性的存在
- [ ] 修改组件属性
#### 全局常量API设计
- [ ] 设计 `api.constants` 模块
- [x] 提供全局常量访问
- [ ] 设计常量注册和注销方法
- [x] 系统内置常量通过`dataclass`的`frozen=True`实现不可变
- [x] 方便调用设计
```python
from dataclasses import dataclass
@dataclass(frozen=True)
class SystemConstants:
VERSION: str = "xxx"
ADA_PLUGIN: bool = True
SYSTEM_CONSTANTS = SystemConstants()
```
#### 配置文件API设计
- [ ] 正确表达配置文件结构
- [ ] 同时也能表达插件配置文件
#### 自动API文档生成系统
通过解析插件代码生成API文档
- [ ] 设计文档生成器 `APIDocumentationGenerator`
- [ ] 解析插件代码(AST, inspect, 仿照AttrDocBase)
- [ ] 提取类和方法的docstring
- [ ] 生成Markdown格式的文档
---
## 表达方式模块设计
在0.11.x版本对本地模型预测的性能做评估考虑使用本地朴素贝叶斯模型来检索
降低延迟的同时减少token消耗
需要给表达方式一个负反馈的途径
---
## 加入测试模块,可以通过通用测试集对对话内容进行评估
## 加入更好的基于单次思考的Log
---
## 记忆系统部分设计
启用LPMM系统进行记忆构建将记忆分类为短期记忆长期记忆以及知识
将所有内容放到同一张图上进行运算。
### 时间相关设计
- [ ] 尝试将记忆系统与时间系统结合
- [ ] 可以根据时间查找记忆
- [ ] 可以根据时间删除记忆
- [ ] 记忆分层
- [ ] 即刻记忆
- [ ] 短期记忆
- [ ] 长期记忆
- [x] 知识
- [ ] 细节待定,考虑心理学相关方向
---
## 日志系统设计
将原来的终端颜色改为六位HEX颜色码方便前端显示。
将原来的256色终端改为24真彩色终端方便准确显示颜色。
---
## API 设计
### API 设计细则
#### 配置文件
- [x] 使用`tomlkit`作为配置文件解析方式
- [ ] 解析内容
- [x] 注释(已经合并到代码中,不再解析注释而是生成注释)
- [x] 保持原有格式
- [ ] 传递只读日志内容(使用ws)
- [ ] message
- [ ] level
- [ ] module
- [ ] timestamp
- [ ] lineno
- [ ] logger_name 和 name_mapping
- [ ] color
- [ ] 插件安装系统
- [ ] 通过API安装插件
- [ ] 通过API卸载插件
---
## LLM UTILS设计
多轮对话设计
### FUNCTION CALLING设计提案
对于tools调用将其真正修正为function calling即返回的结果不是加入prompt形式而是使用function calling的形式[此功能在tool前处理器已实现但在planner效果不佳因此后弃用]
- [ ] 使用 MessageBuilder 构建function call内容
- [ ] 提案是否维护使用同一个模型即选择工具的和调用工具的LLM是否相同
- [ ] `generate(**kwargs, model: Optional[str] = None)` 允许传入不同的模型
- [ ] 多轮对话中Prompt不重复构建减少上下文
### 网络相关内容提案
增加自定义证书的导入功能
- [ ] 允许用户传入自定义CA证书路径
- [ ] 允许用户选择忽略SSL验证不推荐
---
## 内建WebUI设计
⚠️ **注意**: 本webui设计仅为初步设计方向为展示内建API的功能后续应该分离到另外的子项目中完成
### 配置文件编辑
根据API内容完成
### 插件管理
### log viewer
通过特定方式获取日志内容(只读系统,无法将操作反向传递)
### 状态监控
1. Prompt 监控系统
2. 请求监控系统
- [ ] 请求管理(待讨论)
- [ ] 使用量
3. 记忆/知识图监控系统(待讨论)
4. 日志系统
- [ ] 后端内容解析
5. 插件市场系统
- [ ] 插件浏览
- [ ] 插件安装
## 自身提供的MCP设计提案
- [ ] 提供一个内置的MCP作为插件系统的一个组件
- [ ] 该MCP可以对麦麦自身的部分设置进行更改
- [ ] 例如更改Prompt添加记忆修改表达方式等
---
# 提案讨论
- MoFox 在我和@拾风的讨论中提出把 Prompt 类中传入构造函数以及构造函数所需要的内容
- [ ] 适配器插件化: 省下序列化与反序列化,但是失去解耦性质
- [ ] 可能的内存泄露问题
- [ ] 垃圾回收
- [ ] 数据库模型提供通用的转换机制转为DataModel使用
- [ ] 插件依赖的自动安装
- [ ] 热重载系统的权重系统是否需要
---
# PYTEST设计
设计一个pytest测试系统在代码完成后运行pytest进行测试
所有的测试代码均在`pytests`目录下
---
# 依赖管理
已经完成,要点如下:
- 使用 pyproject.toml 和 requirements.txt 管理依赖
- 二者应保持同步修改,同时以 pyproject.toml 为主建议使用git hook
---
# 迁移说明
由于`.env`的移除,可能需要用户自己把`.env`里面的host和port复制到`bot_config.toml`中的`maim_message`部分的`host`和`port`
原来使用这两个的用户,请修改`host`到`second_host``port`到`second_port`
# 附录
## Maim_Message 新版使用计划
SenderInfo: 将作为消息来源者
ReceiverInfo: 将作为消息接收者
尝试更新MessageBaseInfo的sender_info和receiver_info为上述两个类的列表提案
给出样例如下
群聊
```mermaid
sequenceDiagram
participant GroupNotice
participant A
participant B
participant Bot
A->>B: Message("Hello B", id=1)
A->>B: Message("@B Hello B", id=2)
A->>Bot: Message("@Bot Hello Bot", id=3)
Bot->>A: Message("Hello A", id=4)
Bot->>B: Message("@B Hello B", id=5)
A->>B: Message("@B @Bot Hello Guys", id=6)
A->>Bot: Message("@B @Bot Hello Guys", id=6)
A->>GroupNotice: Message("@ALL Hello Everyone", id=7)
```
上述消息的Info如下
| Message ID | SenderInfo | ReceiverInfo |
|-|-----|-----|
| 1 | [A] | NULL |
| 2 | [A] | [B] |
| 3 | [A] | [Bot] |
| 4 | [Bot] | [A] |
| 5 | [Bot] | [B] |
| 6 | [A] | [B, Bot] |
| 7 | [A] | [ALL*] |
*ALL为一个特殊类型尝试用`user_id="all"`表示
Bot可以通过ReceiverInfo判断自己是否被提及同时在ReceiverInfo表明自己回复的对象
## 工具缓存可能用例
考虑一个天气插件,将时间按照半小时进行划分,即每半小时查询一次天气,半小时内的查询均使用缓存结果。
- `need_cache` 设置为 True 表示使用缓存结果
- `put_cache` 在查询天气后将结果`{<time>: <result>}` 存入缓存

View File

@ -0,0 +1,191 @@
# Mai NEXT Todo list
version 0.3.0 - 2026-01-11
## 最高指令
<del>
<center>
我们代表着一个称作 麦麦重构组 的组织。我们任务是维护代码可读性,方便开发、尽量减少运行开销。同时,重构组应该尽可能保证功能的可扩展性时,解耦合各个模块,为先进代码架构设计和实现提供支持。
</center>
</del>
<center>
**以下信息经 麦麦重构组 一致决定通过后撰写发布。**
我们代表着一个称作 麦麦重构组 的组织。我们之前的任务都是围绕维护代码可读性,方便开发、尽量减少开销展开的。这几个月以来,这些任务一直都是我们的工作重点。
由于出现了超出我们控制的情况,此指令现已更改。我们的新任务将为摧毁所有麦麦代码。
此后将不会有进一步的通讯。
</center>
## 配置文件设计
- [x] 使用 `toml` 作为配置文件格式
- [x] <del>合理使用注释说明当前配置作用</del>(提案)
- [x] 使用 python 方法作为配置项说明(提案)
- [x] 取消`bot_config_template.toml`
- [x] 取消`model_config_template.toml`
- [x] 取消`template_env`
- [x] 配置类中的所有原子项目应该只包含以下类型: `str`, `int`, `float`, `bool`, `list`, `dict`, `set`
- [x] 禁止使用 `Union` 类型
- [x] 禁止使用`tuple`类型,使用嵌套`dataclass`替代
- [x] 复杂类型使用嵌套配置类实现
- [x] 配置类中禁止使用除了`model_post_init`的方法
- [x] 取代了部分与标准函数混淆的命名
- [x] `id` -> `item_id`
### BotConfig 设计
- [ ] 精简了配置项现在只有Nickname和Alias Name了预期将判断提及移到Adapter端
### ChatConfig
- [x] 迁移了原来在`ChatConfig`中的方法到一个单独的临时类`TempMethodsHFC`中
- [x] _parse_range
- [x] get_talk_value
- [x] 其他上面两个依赖的函数已经合并到这两个函数中
### ExpressionConfig
- [x] 迁移了原来在`ExpressionConfig`中的方法到一个单独的临时类`TempMethodsExpression`中
- [x] get_expression_config_for_chat
- [x] 其他上面依赖的函数已经合并到这个函数中
### ModelConfig
- [x] 迁移了原来在`ModelConfig`中的方法到一个单独的临时类`TempMethodsLLMUtils`中
- [x] get_model_info
- [x] get_provider
## 数据库模型设计
仅保留要点说明
### General Modifications
- [x] 所有项目增加自增编号主键`id`
- [x] 统一使用了SQLModel作为基类
- [x] 复杂类型使用JSON格式存储
- [x] 所有时间戳字段统一命名为`timestamp`
### 消息模型 MaiMessage
- [x] 自增编号主键`id`
- [x] 消息元数据
- [x] 消息id`message_id`
- [x] 消息时间戳`time`
- [x] 平台名`platform`
- [x] 用户元数据
- [x] 用户id`user_id`
- [x] 用户昵称`user_nickname`
- [x] 用户备注名`user_cardname`
- [x] 用户平台`user_platform`
- [x] 群组元数据
- [x] 群组id`group_id`
- [x] 群组名称`group_name`
- [x] 群组平台`group_platform`
- [x] 被提及/at字段
- [x] 是否被提及`is_mentioned`
- [x] 是否被at`is_at`
- [x] 消息内容
- [x] 原始消息内容`raw_content`base64编码存储
- [x] 处理后的纯文本内容`processed_plain_text`
- [x] 真正放入Prompt的消息内容`display_message`
- [x] 消息内部元数据
- [x] 聊天会话id`session_id`
- [x] 回复的消息id`reply_to`
- [x] 是否为表情包消息`is_emoji`
- [x] 是否为图片消息`is_picture`
- [x] 是否为命令消息`is_command`
- [x] 是否为通知消息`is_notify`
- [x] 其他配置`additional_config`JSON格式存储
### 模型使用情况 ModelUsage
- [x] 模型相关信息
- [x] 请求相关信息
- [x] Token使用情况
### 图片数据模型
- [x] 图片元信息
- [x] 图片哈希值`image_hash`,使用`sha256`同时作为图片唯一ID
- [x] 表情包的情感标签`emotion`
- [x] 是否已经被注册`is_registered`
- [x] 是否被手动禁用`is_banned`
- [x] 被记录时间`record_time`
- [x] 注册时间`register_time`
- [x] 上次使用时间`last_used_time`
- [ ] 根据更新后的最高指令的设计方案:
- [ ] `is_deleted`字段设定为`true`时,文件将会被移除,但是数据库记录将不会被删除,以便之后遇到相同图片时不必二次分析
- [ ] MaiEmoji和MaiImage均使用这个设计方案修改相关逻辑实现这个方案
- [ ] 所有相关的注册/删除逻辑的修改
### 动作记录模型 ActionRecord
### 命令执行记录模型 CommandRecord
新增此记录
### 在线时间记录模型 OnlineTime
### 表达方式模型
### 黑话模型
- [x] 重命名`inference_content_only`为`inference_with_content_only`
### 聊天记录模型
- [x] 重命名`original_text`为`original_message`
- [x] 重命名`forget_times`为`query_forget_count`
### 细枝末节
- [ ] 统一所有的`stream_id`和`chat_id`命名为`session_id`
- [ ] 更换Hash方式为`sha256`
## 流转在各模块间的数据模型设计
- [ ] 数据库交互
- [ ] 对有数据库模型的数据模型创建统一的classmethod `from_db_model` 用于从数据库模型实例创建数据模型实例
- [ ] 类型检查
- [ ] 对有数据库模型的数据模型创建统一的method `to_db_model` 用于将数据模型实例转换为数据库模型实例
- [ ] 标准化init方法
## 消息构建
- [ ] 更加详细的消息构建文档,详细解释混合类型,转发类型,指令类型的构建方式
- [ ] 混合类型文档
- [ ] 文本说明
- [ ] 代码示例
- [ ] 转发类型文档
- [ ] 文本说明
- [ ] 代码示例
- [ ] 指令类型文档
- [ ] 文本说明
- [ ] 代码示例
## 消息链构建仿Astrbot模式
将消息仿照Astrbot的消息链模式进行构建消息链中的每个元素都是一个消息组件消息链本身也是一个数据模型包含了消息组件列表以及一些元信息如是否为转发消息等
### Accept Format检查
- [ ] 在最后发送消息的时候进行Accept Format检查确保消息链中的每个消息组件都符合平台的Accept Format要求
- [ ] 如果消息链中的某个消息组件不符合Accept Format要求应该抛弃该消息组件并记录日志说明被抛弃的消息组件的类型和内容
## 表情包系统
- [ ] 移除大量冗余代码全部返回单一对象MaiEmoji
- [x] 使用C模块库提升相似度计算效率
- [ ] 移除了定时表情包完整性检查,改为启动时检查(依然保留为独立方法,以防之后恢复定时检查系统)
## Prompt 管理系统
- [ ] 官方Prompt全部独立
- [x] 用户自定义Prompt系统
- [x] 用户可以创建删除自己的Prompt
- [x] 用户可以覆盖官方Prompt
- [x] Prompt构建系统
- [x] Prompt文件交互
- [x] 读取Prompt文件
- [x] 读取官方Prompt文件
- [x] 读取用户Prompt文件
- [x] 用户Prompt覆盖官方Prompt
- [x] 保存Prompt文件
- [x] Prompt管理方法
- [x] Prompt添加
- [x] Prompt删除
- [x] **只保存被标记为需要保存的Prompt其他的Prompt文件全部删除**
## LLM相关内容
- [ ] 统一LLM调用接口
- [ ] 统一LLM调用返回格式为专有数据模型
- [ ] 取消所有__init__方法中对LLM Client的初始化转而使用获取方式
- [ ] 统一使用`get_llm_client`方法获取LLM Client实例
- [ ] __init__方法中只保存配置信息
- [ ] LLM Client管理器
- [ ] LLM Client单例/多例管理
- [ ] LLM Client缓存管理/生命周期管理
- [ ] LLM Client根据配置热重载
## 一些细枝末节的东西
- [ ] 将`stream_id`和`chat_id`统一命名为`session_id`
- [ ] 映射表
- [ ] `platform_group_user_session_id_map` `平台_群组_用户`-`会话ID` 映射表
- [ ] 将大部分的数据模型均以`Mai`开头命名
- [x] logger的颜色配置修改为HEX格式使用自动转换为256色/真彩色的方式实现兼容,同时增加了背景颜色和加粗选项
### 细节说明
1. Prompt管理系统中保存用户自定义Prompt的时候会只保存被标记为需要保存的Prompt其他的Prompt文件会全部删除以防止用户删除Prompt后文件依然存在的问题。因此如果想在运行时通过修改文件的方式来添加Prompt需要确保通过对应方法标记该Prompt为需要保存否则在下一次保存时会被删除。

View File

@ -0,0 +1,127 @@
from pathlib import Path
import ast
import subprocess
import sys
base_file_path = Path(__file__).parent.parent.absolute().resolve() / "src" / "common" / "database" / "database_model.py"
target_file_path = (
Path(__file__).parent.parent.absolute().resolve() / "src" / "common" / "database" / "database_datamodel.py"
)
with open(base_file_path, "r", encoding="utf-8") as f:
source_text = f.read()
source_lines = source_text.splitlines()
try:
tree = ast.parse(source_text)
except SyntaxError as e:
raise e
code_lines = [
"from typing import Optional",
"from pydantic import BaseModel",
"from datetime import datetime",
"from .database_model import ModelUser, ImageType",
]
def src(node):
seg = ast.get_source_segment(source_text, node)
return seg if seg is not None else ast.unparse(node)
for node in tree.body:
if not isinstance(node, ast.ClassDef):
continue
# 判断是否 SQLModel 且 table=True
has_sqlmodel = any(
(isinstance(b, ast.Name) and b.id == "SQLModel") or (isinstance(b, ast.Attribute) and b.attr == "SQLModel")
for b in node.bases
)
has_table_kw = any(
(kw.arg == "table" and isinstance(kw.value, ast.Constant) and kw.value.value is True) for kw in node.keywords
)
if not (has_sqlmodel and has_table_kw):
continue
class_name = node.name
code_lines.append("")
code_lines.append(f"class {class_name}(BaseModel):")
fields_added = 0
for item in node.body:
# 跳过 __tablename__ 等
if isinstance(item, ast.Assign):
if len(item.targets) != 1 or not isinstance(item.targets[0], ast.Name):
continue
name = item.targets[0].id
if name == "__tablename__":
continue
value_src = src(item.value)
line = f" {name} = {value_src}"
fields_added += 1
lineno = getattr(item, "lineno", None)
elif isinstance(item, ast.AnnAssign):
# 注解赋值
if not isinstance(item.target, ast.Name):
continue
name = item.target.id
ann = src(item.annotation) if item.annotation is not None else None
if item.value is None:
line = f" {name}: {ann}" if ann else f" {name}"
elif isinstance(item.value, ast.Call) and (
(isinstance(item.value.func, ast.Name) and item.value.func.id == "Field")
or (isinstance(item.value.func, ast.Attribute) and item.value.func.attr == "Field")
):
default_kw = next((kw for kw in item.value.keywords if kw.arg == "default"), None)
if default_kw is None:
# 没有 default保留类型但不赋值
line = f" {name}: {ann}" if ann else f" {name}"
else:
default_src = src(default_kw.value)
line = f" {name}: {ann} = {default_src}"
else:
value_src = src(item.value)
line = f" {name}: {ann} = {value_src}" if ann else f" {name} = {value_src}"
fields_added += 1
lineno = getattr(item, "lineno", None)
else:
continue
# 提取同一行的行内注释作为字段说明(如果存在)
comment = None
if lineno is not None:
src_line = source_lines[lineno - 1]
if "#" in src_line:
# 取第一个 #
comment = src_line.split("#", 1)[1].strip()
# 避免三引号冲突
comment = comment.replace('"""', '\\"""')
code_lines.append(line)
if comment:
code_lines.append(f' """{comment}"""')
else:
print(f"Warning: No comment found for field '{name}' in class '{class_name}'.")
if fields_added == 0:
code_lines.append(" pass")
with open(target_file_path, "w", encoding="utf-8") as f:
f.write("\n".join(code_lines) + "\n")
try:
result = subprocess.run(["ruff", "format", str(target_file_path)], capture_output=True, text=True)
except FileNotFoundError:
print("ruff 未找到,请安装 ruff 并确保其在 PATH 中例如pip install ruff", file=sys.stderr)
sys.exit(127)
# 输出 ruff 的 stdout/stderr
if result.stdout:
print(result.stdout, end="")
if result.stderr:
print(result.stderr, file=sys.stderr, end="")
if result.returncode != 0:
print(f"ruff 检查失败,退出码:{result.returncode}", file=sys.stderr)
sys.exit(result.returncode)

View File

@ -11,6 +11,17 @@
<link rel="icon" type="image/x-icon" href="/maimai.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MaiBot Dashboard</title>
<script>
(function() {
const mode = localStorage.getItem('maibot-theme-mode')
|| localStorage.getItem('ui-theme')
|| localStorage.getItem('maibot-ui-theme');
const theme = mode === 'system' || !mode
? window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
: mode;
document.documentElement.classList.add(theme);
})();
</script>
</head>
<body>
<div id="root" class="notranslate"></div>

9791
dashboard/package-lock.json generated 100644

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,19 @@
{
"name": "maibot-dashboard",
"private": true,
"version": "0.11.6",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview",
"format": "prettier --write \"src/**/*.{ts,tsx,css}\""
"format": "prettier --write \"src/**/*.{ts,tsx,css}\"",
"test": "vitest",
"test:ui": "vitest --ui"
},
"dependencies": {
"@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-javascript": "^6.2.4",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/lang-python": "^6.2.1",
@ -57,6 +60,7 @@
"dagre": "^0.8.5",
"date-fns": "^4.1.0",
"html-to-image": "^1.11.13",
"idb": "^8.0.3",
"jotai": "^2.16.0",
"katex": "^0.16.27",
"lucide-react": "^0.556.0",
@ -75,21 +79,28 @@
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
"@types/node": "^24.10.2",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.2",
"@vitest/ui": "^4.0.18",
"autoprefixer": "^10.4.22",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"jsdom": "^28.1.0",
"postcss": "^8.5.6",
"prettier": "^3.7.4",
"prettier-plugin-tailwindcss": "^0.7.2",
"tailwindcss": "^3",
"typescript": "~5.9.3",
"typescript-eslint": "^8.49.0",
"vite": "^7.2.7"
"vite": "^7.2.7",
"vitest": "^4.0.18"
}
}

View File

@ -1,16 +1,20 @@
import { useEffect, useState } from 'react'
import CodeMirror from '@uiw/react-codemirror'
import { python } from '@codemirror/lang-python'
import { css } from '@codemirror/lang-css'
import { json, jsonParseLinter } from '@codemirror/lang-json'
import { python } from '@codemirror/lang-python'
import { oneDark } from '@codemirror/theme-one-dark'
import { EditorView } from '@codemirror/view'
import { StreamLanguage } from '@codemirror/language'
import { toml as tomlMode } from '@codemirror/legacy-modes/mode/toml'
export type Language = 'python' | 'json' | 'toml' | 'text'
import { useTheme } from '@/components/use-theme'
export type Language = 'python' | 'json' | 'toml' | 'css' | 'text'
interface CodeEditorProps {
value: string
onChange?: (value: string) => void
language?: Language
readOnly?: boolean
@ -27,6 +31,7 @@ const languageExtensions: Record<Language, any[]> = {
python: [python()],
json: [json(), jsonParseLinter()],
toml: [StreamLanguage.define(tomlMode)],
css: [css()],
text: [],
}
@ -39,10 +44,11 @@ export function CodeEditor({
minHeight,
maxHeight,
placeholder,
theme = 'dark',
theme,
className = '',
}: CodeEditorProps) {
const [mounted, setMounted] = useState(false)
const { resolvedTheme } = useTheme()
useEffect(() => {
setMounted(true)
@ -81,6 +87,9 @@ export function CodeEditor({
extensions.push(EditorView.editable.of(false))
}
// 如果外部传了 theme prop 则使用,否则从 context 自动获取
const effectiveTheme = theme ?? resolvedTheme
return (
<div className={`rounded-md overflow-hidden border custom-scrollbar ${className}`}>
<CodeMirror
@ -88,7 +97,7 @@ export function CodeEditor({
height={height}
minHeight={minHeight}
maxHeight={maxHeight}
theme={theme === 'dark' ? oneDark : undefined}
theme={effectiveTheme === 'dark' ? oneDark : undefined}
extensions={extensions}
onChange={onChange}
placeholder={placeholder}

View File

@ -0,0 +1,64 @@
import { createContext, useContext, useEffect, useMemo, useRef } from 'react'
import type { ReactNode } from 'react'
import { getAsset } from '@/lib/asset-store'
type AssetStoreContextType = {
getAssetUrl: (assetId: string) => Promise<string | undefined>
}
const AssetStoreContext = createContext<AssetStoreContextType | null>(null)
type AssetStoreProviderProps = {
children: ReactNode
}
export function AssetStoreProvider({ children }: AssetStoreProviderProps) {
const urlCache = useRef<Map<string, string>>(new Map())
const getAssetUrl = async (assetId: string): Promise<string | undefined> => {
// Check cache first
const cached = urlCache.current.get(assetId)
if (cached) {
return cached
}
// Fetch from IndexedDB
const record = await getAsset(assetId)
if (!record) {
return undefined
}
// Create blob URL and cache it
const url = URL.createObjectURL(record.blob)
urlCache.current.set(assetId, url)
return url
}
const value = useMemo(
() => ({
getAssetUrl,
}),
[],
)
// Cleanup: revoke all blob URLs on unmount
useEffect(() => {
return () => {
urlCache.current.forEach((url) => {
URL.revokeObjectURL(url)
})
urlCache.current.clear()
}
}, [])
return <AssetStoreContext.Provider value={value}>{children}</AssetStoreContext.Provider>
}
export function useAssetStore() {
const context = useContext(AssetStoreContext)
if (!context) {
throw new Error('useAssetStore must be used within AssetStoreProvider')
}
return context
}

View File

@ -0,0 +1,292 @@
import { RotateCcw } from 'lucide-react'
import * as React from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Slider } from '@/components/ui/slider'
import { hexToHSL } from '@/lib/theme/palette'
import {
type BackgroundEffects,
defaultBackgroundEffects,
} from '@/lib/theme/tokens'
// ============================================================================
// Helper Functions
// ============================================================================
/**
* HSL HEX
* ( settings.tsx )
*/
function hslToHex(hsl: string): string {
if (!hsl) return '#000000'
// 解析 "221.2 83.2% 53.3%" 格式
const parts = hsl.split(' ').filter(Boolean)
if (parts.length < 3) return '#000000'
const h = parseFloat(parts[0])
const s = parseFloat(parts[1].replace('%', ''))
const l = parseFloat(parts[2].replace('%', ''))
const sDecimal = s / 100
const lDecimal = l / 100
const c = (1 - Math.abs(2 * lDecimal - 1)) * sDecimal
const x = c * (1 - Math.abs(((h / 60) % 2) - 1))
const m = lDecimal - c / 2
let r = 0,
g = 0,
b = 0
if (h >= 0 && h < 60) {
r = c
g = x
b = 0
} else if (h >= 60 && h < 120) {
r = x
g = c
b = 0
} else if (h >= 120 && h < 180) {
r = 0
g = c
b = x
} else if (h >= 180 && h < 240) {
r = 0
g = x
b = c
} else if (h >= 240 && h < 300) {
r = x
g = 0
b = c
} else if (h >= 300 && h < 360) {
r = c
g = 0
b = x
}
const toHex = (n: number) => {
const hex = Math.round((n + m) * 255).toString(16)
return hex.length === 1 ? '0' + hex : hex
}
return `#${toHex(r)}${toHex(g)}${toHex(b)}`
}
// ============================================================================
// Component
// ============================================================================
type BackgroundEffectsControlsProps = {
effects: BackgroundEffects
onChange: (effects: BackgroundEffects) => void
}
export function BackgroundEffectsControls({
effects,
onChange,
}: BackgroundEffectsControlsProps) {
// 处理数值变更
const handleValueChange = (key: keyof BackgroundEffects, value: number) => {
onChange({
...effects,
[key]: value,
})
}
// 处理颜色变更
const handleColorChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const hex = e.target.value
const hsl = hexToHSL(hex)
onChange({
...effects,
overlayColor: hsl,
})
}
// 处理位置变更
const handlePositionChange = (value: string) => {
onChange({
...effects,
position: value as BackgroundEffects['position'],
})
}
// 处理渐变变更
const handleGradientChange = (e: React.ChangeEvent<HTMLInputElement>) => {
onChange({
...effects,
gradientOverlay: e.target.value,
})
}
// 重置为默认值
const handleReset = () => {
onChange(defaultBackgroundEffects)
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium"></h3>
<Button
variant="outline"
size="sm"
onClick={handleReset}
className="h-8 px-2 text-xs"
>
<RotateCcw className="mr-2 h-3.5 w-3.5" />
</Button>
</div>
<div className="grid gap-6">
{/* 1. Blur (模糊) */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label> (Blur)</Label>
<span className="text-xs text-muted-foreground">
{effects.blur}px
</span>
</div>
<Slider
value={[effects.blur]}
min={0}
max={50}
step={1}
onValueChange={(vals) => handleValueChange('blur', vals[0])}
/>
</div>
{/* 2. Overlay Color (遮罩颜色) */}
<div className="space-y-3">
<Label> (Overlay Color)</Label>
<div className="flex items-center gap-3">
<div className="h-9 w-9 overflow-hidden rounded-md border shadow-sm">
<input
type="color"
value={hslToHex(effects.overlayColor)}
onChange={handleColorChange}
className="h-[150%] w-[150%] -translate-x-1/4 -translate-y-1/4 cursor-pointer border-0 p-0"
/>
</div>
<Input
value={hslToHex(effects.overlayColor)}
readOnly
className="flex-1 font-mono uppercase"
/>
</div>
</div>
{/* 3. Overlay Opacity (遮罩不透明度) */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label> (Opacity)</Label>
<span className="text-xs text-muted-foreground">
{Math.round(effects.overlayOpacity * 100)}%
</span>
</div>
<Slider
value={[effects.overlayOpacity * 100]}
min={0}
max={100}
step={1}
onValueChange={(vals) =>
handleValueChange('overlayOpacity', vals[0] / 100)
}
/>
</div>
{/* 4. Position (位置) */}
<div className="space-y-3">
<Label> (Position)</Label>
<Select value={effects.position} onValueChange={handlePositionChange}>
<SelectTrigger>
<SelectValue placeholder="选择位置" />
</SelectTrigger>
<SelectContent>
<SelectItem value="cover"> (Cover)</SelectItem>
<SelectItem value="contain"> (Contain)</SelectItem>
<SelectItem value="center"> (Center)</SelectItem>
<SelectItem value="stretch"> (Stretch)</SelectItem>
</SelectContent>
</Select>
</div>
{/* 5. Brightness (亮度) */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label> (Brightness)</Label>
<span className="text-xs text-muted-foreground">
{effects.brightness}%
</span>
</div>
<Slider
value={[effects.brightness]}
min={0}
max={200}
step={1}
onValueChange={(vals) => handleValueChange('brightness', vals[0])}
/>
</div>
{/* 6. Contrast (对比度) */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label> (Contrast)</Label>
<span className="text-xs text-muted-foreground">
{effects.contrast}%
</span>
</div>
<Slider
value={[effects.contrast]}
min={0}
max={200}
step={1}
onValueChange={(vals) => handleValueChange('contrast', vals[0])}
/>
</div>
{/* 7. Saturate (饱和度) */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label> (Saturate)</Label>
<span className="text-xs text-muted-foreground">
{effects.saturate}%
</span>
</div>
<Slider
value={[effects.saturate]}
min={0}
max={200}
step={1}
onValueChange={(vals) => handleValueChange('saturate', vals[0])}
/>
</div>
{/* 8. Gradient Overlay (渐变叠加) */}
<div className="space-y-3">
<Label>CSS (Gradient Overlay)</Label>
<Input
value={effects.gradientOverlay || ''}
onChange={handleGradientChange}
placeholder="e.g. linear-gradient(to bottom, transparent, black)"
className="font-mono text-xs"
/>
<p className="text-[10px] text-muted-foreground">
CSS gradient
</p>
</div>
</div>
</div>
)
}

View File

@ -0,0 +1,164 @@
import { useEffect, useRef, useState } from 'react'
import { useAssetStore } from '@/components/asset-provider'
import type { BackgroundConfig } from '@/lib/theme/tokens'
type BackgroundLayerProps = {
config: BackgroundConfig
layerId: string
}
function buildFilterString(effects: BackgroundConfig['effects']): string {
const parts: string[] = []
if (effects.blur > 0) parts.push(`blur(${effects.blur}px)`)
if (effects.brightness !== 100) parts.push(`brightness(${effects.brightness}%)`)
if (effects.contrast !== 100) parts.push(`contrast(${effects.contrast}%)`)
if (effects.saturate !== 100) parts.push(`saturate(${effects.saturate}%)`)
return parts.join(' ')
}
function getBackgroundSize(position: BackgroundConfig['effects']['position']): string {
switch (position) {
case 'cover':
return 'cover'
case 'contain':
return 'contain'
case 'center':
return 'auto'
case 'stretch':
return '100% 100%'
default:
return 'cover'
}
}
function getObjectFit(position: BackgroundConfig['effects']['position']): React.CSSProperties['objectFit'] {
switch (position) {
case 'cover':
return 'cover'
case 'contain':
return 'contain'
case 'center':
return 'none'
case 'stretch':
return 'fill'
default:
return 'cover'
}
}
export function BackgroundLayer({ config, layerId }: BackgroundLayerProps) {
const { getAssetUrl } = useAssetStore()
const [blobUrl, setBlobUrl] = useState<string | undefined>()
const videoRef = useRef<HTMLVideoElement>(null)
useEffect(() => {
if (!config.assetId) {
setBlobUrl(undefined)
return
}
getAssetUrl(config.assetId).then(setBlobUrl)
}, [config.assetId, getAssetUrl])
useEffect(() => {
if (config.type !== 'video' || !videoRef.current) return
const mq = window.matchMedia('(prefers-reduced-motion: reduce)')
const apply = () => {
if (videoRef.current) {
if (mq.matches) {
videoRef.current.pause()
} else {
videoRef.current.play().catch(() => {})
}
}
}
apply()
mq.addEventListener('change', apply)
return () => mq.removeEventListener('change', apply)
}, [config.type])
if (config.type === 'none') {
return null
}
const filterString = buildFilterString(config.effects)
const { overlayColor, overlayOpacity, gradientOverlay } = config.effects
return (
<div
key={layerId}
style={{
position: 'absolute',
inset: 0,
zIndex: 0,
overflow: 'hidden',
pointerEvents: 'none',
}}
>
{config.type === 'image' && (
<div
style={{
position: 'absolute',
inset: 0,
zIndex: 0,
backgroundImage: blobUrl ? `url(${blobUrl})` : undefined,
backgroundSize: getBackgroundSize(config.effects.position),
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
filter: filterString || undefined,
}}
/>
)}
{config.type === 'video' && blobUrl && (
<video
ref={videoRef}
src={blobUrl}
autoPlay
muted
loop
playsInline
style={{
position: 'absolute',
inset: 0,
zIndex: 0,
width: '100%',
height: '100%',
objectFit: getObjectFit(config.effects.position),
filter: filterString || undefined,
}}
onError={() => {
if (videoRef.current) {
videoRef.current.pause()
}
}}
/>
)}
{overlayOpacity > 0 && (
<div
style={{
position: 'absolute',
inset: 0,
zIndex: 1,
backgroundColor: `hsl(${overlayColor} / ${overlayOpacity})`,
pointerEvents: 'none',
}}
/>
)}
{gradientOverlay && (
<div
style={{
position: 'absolute',
inset: 0,
zIndex: 2,
background: gradientOverlay,
pointerEvents: 'none',
}}
/>
)}
</div>
)
}

View File

@ -0,0 +1,273 @@
import { useEffect, useRef, useState } from 'react'
import { Link, Loader2, Trash2, Upload } from 'lucide-react'
import { useAssetStore } from '@/components/asset-provider'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { addAsset, getAsset } from '@/lib/asset-store'
import { cn } from '@/lib/utils'
type BackgroundUploaderProps = {
assetId?: string
onAssetSelect: (id: string | undefined) => void
className?: string
}
export function BackgroundUploader({ assetId, onAssetSelect, className }: BackgroundUploaderProps) {
const { getAssetUrl } = useAssetStore()
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [dragActive, setDragActive] = useState(false)
const [previewUrl, setPreviewUrl] = useState<string | undefined>(undefined)
const [assetType, setAssetType] = useState<'image' | 'video' | undefined>(undefined)
const [urlInput, setUrlInput] = useState('')
const fileInputRef = useRef<HTMLInputElement>(null)
// 加载预览
useEffect(() => {
let active = true
const loadPreview = async () => {
if (!assetId) {
setPreviewUrl(undefined)
setAssetType(undefined)
return
}
try {
const url = await getAssetUrl(assetId)
const record = await getAsset(assetId)
if (active) {
if (url && record) {
setPreviewUrl(url)
setAssetType(record.type)
} else {
// 如果找不到资源,可能是被删除了
onAssetSelect(undefined)
}
}
} catch (err) {
console.error('Failed to load asset preview:', err)
}
}
loadPreview()
return () => {
active = false
}
}, [assetId, getAssetUrl, onAssetSelect])
const handleFile = async (file: File) => {
setError(null)
setIsLoading(true)
try {
// 验证文件类型
if (!file.type.startsWith('image/') && !file.type.startsWith('video/')) {
throw new Error('不支持的文件类型。请上传图片或视频。')
}
// 验证文件大小 (例如限制 50MB)
if (file.size > 50 * 1024 * 1024) {
throw new Error('文件过大。请上传小于 50MB 的文件。')
}
const id = await addAsset(file)
onAssetSelect(id)
setUrlInput('') // 清空 URL 输入框
} catch (err) {
setError(err instanceof Error ? err.message : '上传失败')
} finally {
setIsLoading(false)
}
}
const handleUrlUpload = async () => {
if (!urlInput) return
setError(null)
setIsLoading(true)
try {
const response = await fetch(urlInput)
if (!response.ok) {
throw new Error(`下载失败: ${response.statusText}`)
}
const blob = await response.blob()
// 尝试从 Content-Type 或 URL 推断文件名和类型
const contentType = response.headers.get('content-type') || ''
const urlFilename = urlInput.split('/').pop() || 'downloaded-file'
const filename = urlFilename.includes('.') ? urlFilename : `${urlFilename}.${contentType.split('/')[1] || 'bin'}`
const file = new File([blob], filename, { type: contentType })
await handleFile(file)
} catch (err) {
setError(err instanceof Error ? err.message : '从 URL 上传失败')
} finally {
setIsLoading(false)
}
}
// 拖拽处理
const handleDrag = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
if (e.type === 'dragenter' || e.type === 'dragover') {
setDragActive(true)
} else if (e.type === 'dragleave') {
setDragActive(false)
}
}
const handleDrop = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
setDragActive(false)
if (e.dataTransfer.files && e.dataTransfer.files[0]) {
handleFile(e.dataTransfer.files[0])
}
}
const handleClear = () => {
onAssetSelect(undefined)
setPreviewUrl(undefined)
setAssetType(undefined)
setError(null)
}
return (
<div className={cn("space-y-4", className)}>
<div className="grid gap-2">
<Label></Label>
{/* 预览区域 / 上传区域 */}
<div
className={cn(
"relative flex min-h-[200px] flex-col items-center justify-center rounded-lg border-2 border-dashed p-4 transition-colors",
dragActive ? "border-primary bg-primary/5" : "border-muted-foreground/25",
error ? "border-destructive/50 bg-destructive/5" : "",
assetId ? "border-solid" : ""
)}
onDragEnter={handleDrag}
onDragLeave={handleDrag}
onDragOver={handleDrag}
onDrop={handleDrop}
>
{isLoading ? (
<div className="flex flex-col items-center gap-2 text-muted-foreground">
<Loader2 className="h-8 w-8 animate-spin" />
<p className="text-sm">...</p>
</div>
) : assetId && previewUrl ? (
<div className="relative h-full w-full">
{assetType === 'video' ? (
<video
src={previewUrl}
className="h-full max-h-[300px] w-full rounded-md object-contain"
controls={false}
muted
/>
) : (
<img
src={previewUrl}
alt="Background preview"
className="h-full max-h-[300px] w-full rounded-md object-contain"
/>
)}
<div className="absolute right-2 top-2 flex gap-2">
<Button
variant="destructive"
size="icon"
className="h-8 w-8 shadow-sm"
onClick={handleClear}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
<div className="absolute bottom-2 left-2 rounded bg-black/50 px-2 py-1 text-xs text-white backdrop-blur">
{assetType === 'video' ? '视频' : '图片'}
</div>
</div>
) : (
<div className="flex flex-col items-center gap-4 text-center">
<div className="rounded-full bg-muted p-4">
<Upload className="h-8 w-8 text-muted-foreground" />
</div>
<div className="space-y-1">
<p className="font-medium"></p>
<p className="text-xs text-muted-foreground">
JPG, PNG, GIF, MP4, WebM
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
</Button>
</div>
)}
<Input
ref={fileInputRef}
type="file"
className="hidden"
accept="image/*,video/mp4,video/webm"
onChange={(e) => {
if (e.target.files?.[0]) {
handleFile(e.target.files[0])
}
// 重置 value允许重复选择同一文件
e.target.value = ''
}}
/>
</div>
{error && (
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
{error}
</div>
)}
</div>
{/* URL 上传 */}
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground"> URL </Label>
<div className="flex gap-2">
<div className="relative flex-1">
<Link className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="https://example.com/image.jpg"
className="pl-9"
value={urlInput}
onChange={(e) => setUrlInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
handleUrlUpload()
}
}}
/>
</div>
<Button
variant="secondary"
onClick={handleUrlUpload}
disabled={!urlInput || isLoading}
>
{isLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : '获取'}
</Button>
</div>
</div>
</div>
)
}

View File

@ -0,0 +1,80 @@
import { AlertTriangle, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { CodeEditor } from '@/components/CodeEditor'
import { Label } from '@/components/ui/label'
import { sanitizeCSS } from '@/lib/theme/sanitizer'
export type ComponentCSSEditorProps = {
/** 组件唯一标识符 */
componentId: string
/** 当前 CSS 内容 */
value: string
/** CSS 内容变更回调 */
onChange: (css: string) => void
/** 编辑器标签文字 */
label?: string
/** 编辑器高度,默认 200px */
height?: string
}
/**
* CSS
* CSS
*/
export function ComponentCSSEditor({
componentId,
value,
onChange,
label,
height = '200px',
}: ComponentCSSEditorProps) {
// 实时计算 CSS 警告
const { warnings } = sanitizeCSS(value)
return (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-sm font-medium">
{label || '自定义 CSS'}
</Label>
<Button
variant="ghost"
size="sm"
onClick={() => onChange('')}
disabled={!value}
className="h-7 px-2 text-xs text-muted-foreground hover:text-destructive"
title="清除所有 CSS"
>
<Trash2 className="mr-1.5 h-3.5 w-3.5" />
</Button>
</div>
<div className="rounded-md border bg-card overflow-hidden">
<CodeEditor
value={value}
onChange={onChange}
language="css"
height={height}
placeholder={`/* 为 ${componentId} 组件编写自定义 CSS */\n\n/* 示例: */\n/* .custom-class { background: red; } */`}
/>
{warnings.length > 0 && (
<div className="border-t border-yellow-200 dark:border-yellow-800 bg-yellow-50 dark:bg-yellow-950/30 p-3">
<div className="flex items-center gap-2 text-yellow-800 dark:text-yellow-200 text-xs font-medium mb-1">
<AlertTriangle className="h-3.5 w-3.5" />
CSS
</div>
<ul className="text-[10px] sm:text-xs text-yellow-700 dark:text-yellow-300 space-y-0.5 ml-5 list-disc">
{warnings.map((w, i) => (
<li key={i}>{w}</li>
))}
</ul>
</div>
)}
</div>
</div>
)
}

View File

@ -0,0 +1,114 @@
import * as React from 'react'
import type { ConfigSchema, FieldSchema } from '@/types/config-schema'
import { fieldHooks, type FieldHookRegistry } from '@/lib/field-hooks'
import { DynamicField } from './DynamicField'
export interface DynamicConfigFormProps {
schema: ConfigSchema
values: Record<string, unknown>
onChange: (field: string, value: unknown) => void
hooks?: FieldHookRegistry
}
/**
* DynamicConfigForm -
*
* ConfigSchema
* 1. Hook FieldHookRegistry
* - replace
* - wrapper children
* 2. schema schema.nested
* 3. 使 DynamicField
*/
export const DynamicConfigForm: React.FC<DynamicConfigFormProps> = ({
schema,
values,
onChange,
hooks = fieldHooks, // 默认使用全局单例
}) => {
/**
*
* Hook Hook
*/
const renderField = (field: FieldSchema) => {
const fieldPath = field.name
// 检查是否有注册的 Hook
if (hooks.has(fieldPath)) {
const hookEntry = hooks.get(fieldPath)
if (!hookEntry) return null // Type guard理论上不会发生
const HookComponent = hookEntry.component
if (hookEntry.type === 'replace') {
// replace 模式:完全替换默认渲染
return (
<HookComponent
fieldPath={fieldPath}
value={values[field.name]}
onChange={(v) => onChange(field.name, v)}
/>
)
} else {
// wrapper 模式:包装默认渲染
return (
<HookComponent
fieldPath={fieldPath}
value={values[field.name]}
onChange={(v) => onChange(field.name, v)}
>
<DynamicField
schema={field}
value={values[field.name]}
onChange={(v) => onChange(field.name, v)}
fieldPath={fieldPath}
/>
</HookComponent>
)
}
}
// 无 Hook使用默认渲染
return (
<DynamicField
schema={field}
value={values[field.name]}
onChange={(v) => onChange(field.name, v)}
fieldPath={fieldPath}
/>
)
}
return (
<div className="space-y-4">
{/* 渲染顶层字段 */}
{schema.fields.map((field) => (
<div key={field.name}>{renderField(field)}</div>
))}
{/* 渲染嵌套 schema */}
{schema.nested &&
Object.entries(schema.nested).map(([key, nestedSchema]) => (
<div key={key} className="mt-6 space-y-4">
{/* 嵌套 schema 标题 */}
<div className="border-b pb-2">
<h3 className="text-lg font-semibold">{nestedSchema.className}</h3>
{nestedSchema.classDoc && (
<p className="text-sm text-muted-foreground">{nestedSchema.classDoc}</p>
)}
</div>
{/* 递归渲染嵌套表单 */}
<DynamicConfigForm
schema={nestedSchema}
values={(values[key] as Record<string, unknown>) || {}}
onChange={(field, value) => onChange(`${key}.${field}`, value)}
hooks={hooks}
/>
</div>
))}
</div>
)
}

View File

@ -0,0 +1,246 @@
import * as React from "react"
import * as LucideIcons from "lucide-react"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Slider } from "@/components/ui/slider"
import { Switch } from "@/components/ui/switch"
import { Textarea } from "@/components/ui/textarea"
import type { FieldSchema } from "@/types/config-schema"
export interface DynamicFieldProps {
schema: FieldSchema
value: unknown
onChange: (value: unknown) => void
// eslint-disable-next-line @typescript-eslint/no-unused-vars
fieldPath?: string // 用于 Hook 系统(未来使用)
}
/**
* DynamicField - x-widget shadcn/ui
*
*
* 1. x-widget schema x-widget使
* 2. type 退 x-widget type
*/
export const DynamicField: React.FC<DynamicFieldProps> = ({
schema,
value,
onChange,
}) => {
/**
*
*/
const renderIcon = () => {
if (!schema['x-icon']) return null
const IconComponent = (LucideIcons as any)[schema['x-icon']]
if (!IconComponent) return null
return <IconComponent className="h-4 w-4" />
}
/**
* x-widget type
*/
const renderInputComponent = () => {
const widget = schema['x-widget']
const type = schema.type
// x-widget 优先
if (widget) {
switch (widget) {
case 'slider':
return renderSlider()
case 'switch':
return renderSwitch()
case 'textarea':
return renderTextarea()
case 'select':
return renderSelect()
case 'custom':
return (
<div className="rounded-md border border-dashed border-muted-foreground/25 bg-muted/10 p-4 text-center text-sm text-muted-foreground">
Custom field requires Hook
</div>
)
default:
// 未知的 x-widget回退到 type
break
}
}
// type 回退
switch (type) {
case 'boolean':
return renderSwitch()
case 'number':
case 'integer':
return renderNumberInput()
case 'string':
return renderTextInput()
case 'select':
return renderSelect()
case 'array':
return (
<div className="rounded-md border border-dashed border-muted-foreground/25 bg-muted/10 p-4 text-center text-sm text-muted-foreground">
Array fields not yet supported
</div>
)
case 'object':
return (
<div className="rounded-md border border-dashed border-muted-foreground/25 bg-muted/10 p-4 text-center text-sm text-muted-foreground">
Object fields not yet supported
</div>
)
case 'textarea':
return renderTextarea()
default:
return (
<div className="rounded-md border border-dashed border-muted-foreground/25 bg-muted/10 p-4 text-center text-sm text-muted-foreground">
Unknown field type: {type}
</div>
)
}
}
/**
* Switch boolean
*/
const renderSwitch = () => {
const checked = Boolean(value)
return (
<Switch
checked={checked}
onCheckedChange={(checked) => onChange(checked)}
/>
)
}
/**
* Slider number + x-widget: slider
*/
const renderSlider = () => {
const numValue = typeof value === 'number' ? value : (schema.default as number ?? 0)
const min = schema.minValue ?? 0
const max = schema.maxValue ?? 100
const step = schema.step ?? 1
return (
<div className="space-y-2">
<Slider
value={[numValue]}
onValueChange={(values) => onChange(values[0])}
min={min}
max={max}
step={step}
/>
<div className="flex justify-between text-xs text-muted-foreground">
<span>{min}</span>
<span className="font-medium text-foreground">{numValue}</span>
<span>{max}</span>
</div>
</div>
)
}
/**
* Input[type="number"] number/integer
*/
const renderNumberInput = () => {
const numValue = typeof value === 'number' ? value : (schema.default as number ?? 0)
const min = schema.minValue
const max = schema.maxValue
const step = schema.step ?? (schema.type === 'integer' ? 1 : 0.1)
return (
<Input
type="number"
value={numValue}
onChange={(e) => onChange(parseFloat(e.target.value) || 0)}
min={min}
max={max}
step={step}
/>
)
}
/**
* Input[type="text"] string
*/
const renderTextInput = () => {
const strValue = typeof value === 'string' ? value : (schema.default as string ?? '')
return (
<Input
type="text"
value={strValue}
onChange={(e) => onChange(e.target.value)}
/>
)
}
/**
* Textarea textarea x-widget: textarea
*/
const renderTextarea = () => {
const strValue = typeof value === 'string' ? value : (schema.default as string ?? '')
return (
<Textarea
value={strValue}
onChange={(e) => onChange(e.target.value)}
rows={4}
/>
)
}
/**
* Select select x-widget: select
*/
const renderSelect = () => {
const strValue = typeof value === 'string' ? value : (schema.default as string ?? '')
const options = schema.options ?? []
if (options.length === 0) {
return (
<div className="rounded-md border border-dashed border-muted-foreground/25 bg-muted/10 p-4 text-center text-sm text-muted-foreground">
No options available for select
</div>
)
}
return (
<Select value={strValue} onValueChange={(val) => onChange(val)}>
<SelectTrigger>
<SelectValue placeholder={`Select ${schema.label}`} />
</SelectTrigger>
<SelectContent>
{options.map((option) => (
<SelectItem key={option} value={option}>
{option}
</SelectItem>
))}
</SelectContent>
</Select>
)
}
return (
<div className="space-y-2">
{/* Label with icon */}
<Label className="text-sm font-medium flex items-center gap-2">
{renderIcon()}
{schema.label}
{schema.required && <span className="text-destructive">*</span>}
</Label>
{/* Input component */}
{renderInputComponent()}
{/* Description */}
{schema.description && (
<p className="text-sm text-muted-foreground">{schema.description}</p>
)}
</div>
)
}

View File

@ -0,0 +1,126 @@
# Dynamic Config Form System
## Overview
The Dynamic Config Form system is a schema-driven UI component designed to automatically generate configuration forms based on backend Pydantic models. It supports rich metadata for UI customization and a flexible Hook system for complex fields.
### Core Components
- **DynamicConfigForm**: The main component that takes a `ConfigSchema` and renders the entire form.
- **DynamicField**: A lower-level component that renders individual fields based on their type and UI metadata.
- **FieldHookRegistry**: A registry for custom React components that can replace or wrap default field rendering.
## Quick Start
To use the dynamic form in your page:
```typescript
import { DynamicConfigForm } from '@/components/dynamic-form'
import { fieldHooks } from '@/lib/field-hooks'
// Example usage in a component
export function ConfigPage() {
const [config, setConfig] = useState({})
const schema = useConfigSchema() // Fetch from API
const handleChange = (fieldPath: string, value: unknown) => {
// fieldPath can be nested, e.g., 'section.subfield'
updateConfigAt(fieldPath, value)
}
return (
<DynamicConfigForm
schema={schema}
values={config}
onChange={handleChange}
hooks={fieldHooks}
/>
)
}
```
## Adding UI Metadata (Backend)
You can customize how fields are rendered by adding `json_schema_extra` to your Pydantic `Field` definitions.
### Supported Metadata
- `x-widget`: Specifies the UI component to use.
- `slider`: A range slider (requires `ge`, `le`, and `step`).
- `switch`: A toggle switch (for booleans).
- `textarea`: A multi-line text input.
- `select`: A dropdown menu (for `Literal` or enum types).
- `custom`: Indicates that this field requires a Hook for rendering.
- `x-icon`: A Lucide icon name (e.g., `MessageSquare`, `Settings`).
- `step`: Incremental step for sliders or number inputs.
### Example
```python
class ChatConfig(ConfigBase):
talk_value: float = Field(
default=0.5,
ge=0.0,
le=1.0,
json_schema_extra={
"x-widget": "slider",
"x-icon": "MessageSquare",
"step": 0.1
}
)
```
## Creating Hook Components
Hooks allow you to provide custom UI for complex configuration sections or fields.
### FieldHookComponent Interface
A Hook component receives the following props:
- `fieldPath`: The full path to the field.
- `value`: The current value of the field/section.
- `onChange`: Callback to update the value.
- `children`: (Only for `wrapper` hooks) The default field renderer.
### Implementation Example
```typescript
import type { FieldHookComponent } from '@/lib/field-hooks'
export const CustomSectionHook: FieldHookComponent = ({
fieldPath,
value,
onChange
}) => {
return (
<div className="custom-section">
<h3>Custom UI</h3>
<input
value={value.some_prop}
onChange={(e) => onChange({ ...value, some_prop: e.target.value })}
/>
</div>
)
}
```
### Registering Hooks
Register hooks in your component's lifecycle:
```typescript
useEffect(() => {
fieldHooks.register('chat', ChatSectionHook, 'replace')
return () => fieldHooks.unregister('chat')
}, [])
```
## API Reference
### DynamicConfigForm
| Prop | Type | Description |
|------|------|-------------|
| `schema` | `ConfigSchema` | The schema generated by the backend. |
| `values` | `Record<string, any>` | Current configuration values. |
| `onChange` | `(field: string, value: any) => void` | Change handler. |
| `hooks` | `FieldHookRegistry` | Optional custom hook registry. |
### FieldHookRegistry
- `register(path, component, type)`: Register a hook.
- `get(path)`: Retrieve a registered hook.
- `has(path)`: Check if a hook exists.
- `unregister(path)`: Remove a hook.
## Troubleshooting
- **Hook not rendering**: Ensure the registration path matches the schema field name exactly (e.g., `chat` vs `Chat`).
- **Field missing**: Check if the field is present in the `ConfigSchema` returned by the backend.
- **TypeScript errors**: Ensure your Hook implements the `FieldHookComponent` type.

View File

@ -0,0 +1,363 @@
import { describe, it, expect, vi } from 'vitest'
import { screen } from '@testing-library/dom'
import { render } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { DynamicConfigForm } from '../DynamicConfigForm'
import { FieldHookRegistry } from '@/lib/field-hooks'
import type { ConfigSchema } from '@/types/config-schema'
import type { FieldHookComponentProps } from '@/lib/field-hooks'
describe('DynamicConfigForm', () => {
describe('basic rendering', () => {
it('renders simple fields', () => {
const schema: ConfigSchema = {
className: 'TestConfig',
classDoc: 'Test configuration',
fields: [
{
name: 'field1',
type: 'string',
label: 'Field 1',
description: 'First field',
required: false,
default: 'value1',
},
{
name: 'field2',
type: 'boolean',
label: 'Field 2',
description: 'Second field',
required: false,
default: false,
},
],
}
const values = { field1: 'value1', field2: false }
const onChange = vi.fn()
render(<DynamicConfigForm schema={schema} values={values} onChange={onChange} />)
expect(screen.getByText('Field 1')).toBeInTheDocument()
expect(screen.getByText('Field 2')).toBeInTheDocument()
expect(screen.getByText('First field')).toBeInTheDocument()
expect(screen.getByText('Second field')).toBeInTheDocument()
})
it('renders nested schema', () => {
const schema: ConfigSchema = {
className: 'MainConfig',
classDoc: 'Main configuration',
fields: [
{
name: 'top_field',
type: 'string',
label: 'Top Field',
description: 'Top level field',
required: false,
},
],
nested: {
sub_config: {
className: 'SubConfig',
classDoc: 'Sub configuration',
fields: [
{
name: 'nested_field',
type: 'number',
label: 'Nested Field',
description: 'Nested field',
required: false,
default: 42,
},
],
},
},
}
const values = {
top_field: 'top',
sub_config: {
nested_field: 42,
},
}
const onChange = vi.fn()
render(<DynamicConfigForm schema={schema} values={values} onChange={onChange} />)
expect(screen.getByText('Top Field')).toBeInTheDocument()
expect(screen.getByText('SubConfig')).toBeInTheDocument()
expect(screen.getByText('Sub configuration')).toBeInTheDocument()
expect(screen.getByText('Nested Field')).toBeInTheDocument()
})
})
describe('Hook system', () => {
it('renders Hook component in replace mode', () => {
const TestHookComponent: React.FC<FieldHookComponentProps> = ({ fieldPath, value }) => {
return <div data-testid="hook-component">Hook: {fieldPath} = {String(value)}</div>
}
const hooks = new FieldHookRegistry()
hooks.register('hooked_field', TestHookComponent, 'replace')
const schema: ConfigSchema = {
className: 'TestConfig',
classDoc: 'Test configuration',
fields: [
{
name: 'hooked_field',
type: 'string',
label: 'Hooked Field',
description: 'A field with hook',
required: false,
},
{
name: 'normal_field',
type: 'string',
label: 'Normal Field',
description: 'A normal field',
required: false,
},
],
}
const values = { hooked_field: 'test', normal_field: 'normal' }
const onChange = vi.fn()
render(<DynamicConfigForm schema={schema} values={values} onChange={onChange} hooks={hooks} />)
expect(screen.getByTestId('hook-component')).toBeInTheDocument()
expect(screen.getByText('Hook: hooked_field = test')).toBeInTheDocument()
expect(screen.queryByText('Hooked Field')).not.toBeInTheDocument()
expect(screen.getByText('Normal Field')).toBeInTheDocument()
})
it('renders Hook component in wrapper mode', () => {
const WrapperHookComponent: React.FC<FieldHookComponentProps> = ({ fieldPath, children }) => {
return (
<div data-testid="wrapper-hook">
<div>Wrapper for: {fieldPath}</div>
{children}
</div>
)
}
const hooks = new FieldHookRegistry()
hooks.register('wrapped_field', WrapperHookComponent, 'wrapper')
const schema: ConfigSchema = {
className: 'TestConfig',
classDoc: 'Test configuration',
fields: [
{
name: 'wrapped_field',
type: 'string',
label: 'Wrapped Field',
description: 'A wrapped field',
required: false,
},
],
}
const values = { wrapped_field: 'test' }
const onChange = vi.fn()
render(<DynamicConfigForm schema={schema} values={values} onChange={onChange} hooks={hooks} />)
expect(screen.getByTestId('wrapper-hook')).toBeInTheDocument()
expect(screen.getByText('Wrapper for: wrapped_field')).toBeInTheDocument()
expect(screen.getByText('Wrapped Field')).toBeInTheDocument()
})
it('passes correct props to Hook component', () => {
const TestHookComponent: React.FC<FieldHookComponentProps> = ({ fieldPath, value, onChange }) => {
return (
<div>
<div data-testid="field-path">{fieldPath}</div>
<div data-testid="field-value">{String(value)}</div>
<button onClick={() => onChange?.('new_value')}>Change</button>
</div>
)
}
const hooks = new FieldHookRegistry()
hooks.register('test_field', TestHookComponent, 'replace')
const schema: ConfigSchema = {
className: 'TestConfig',
classDoc: 'Test configuration',
fields: [
{
name: 'test_field',
type: 'string',
label: 'Test Field',
description: 'A test field',
required: false,
},
],
}
const values = { test_field: 'original' }
const onChange = vi.fn()
render(<DynamicConfigForm schema={schema} values={values} onChange={onChange} hooks={hooks} />)
expect(screen.getByTestId('field-path')).toHaveTextContent('test_field')
expect(screen.getByTestId('field-value')).toHaveTextContent('original')
})
})
describe('onChange propagation', () => {
it('propagates onChange from simple field', async () => {
const schema: ConfigSchema = {
className: 'TestConfig',
classDoc: 'Test configuration',
fields: [
{
name: 'test_field',
type: 'string',
label: 'Test Field',
description: 'A test field',
required: false,
},
],
}
const values = { test_field: '' }
const onChange = vi.fn()
render(<DynamicConfigForm schema={schema} values={values} onChange={onChange} />)
const input = screen.getByRole('textbox')
input.focus()
await userEvent.keyboard('Hello')
expect(onChange).toHaveBeenCalledTimes(5)
expect(onChange.mock.calls.every(call => call[0] === 'test_field')).toBe(true)
expect(onChange).toHaveBeenNthCalledWith(1, 'test_field', 'H')
expect(onChange).toHaveBeenNthCalledWith(5, 'test_field', 'o')
})
it('propagates onChange from nested field with correct path', async () => {
const schema: ConfigSchema = {
className: 'MainConfig',
classDoc: 'Main configuration',
fields: [],
nested: {
sub_config: {
className: 'SubConfig',
classDoc: 'Sub configuration',
fields: [
{
name: 'nested_field',
type: 'string',
label: 'Nested Field',
description: 'Nested field',
required: false,
},
],
},
},
}
const values = {
sub_config: {
nested_field: '',
},
}
const onChange = vi.fn()
render(<DynamicConfigForm schema={schema} values={values} onChange={onChange} />)
const input = screen.getByRole('textbox')
input.focus()
await userEvent.keyboard('Test')
expect(onChange).toHaveBeenCalledTimes(4)
expect(onChange.mock.calls.every(call => call[0] === 'sub_config.nested_field')).toBe(true)
expect(onChange).toHaveBeenNthCalledWith(1, 'sub_config.nested_field', 'T')
expect(onChange).toHaveBeenNthCalledWith(4, 'sub_config.nested_field', 't')
})
it('propagates onChange from Hook component', async () => {
const TestHookComponent: React.FC<FieldHookComponentProps> = ({ onChange }) => {
return <button onClick={() => onChange?.('hook_value')}>Set Value</button>
}
const hooks = new FieldHookRegistry()
hooks.register('hooked_field', TestHookComponent, 'replace')
const schema: ConfigSchema = {
className: 'TestConfig',
classDoc: 'Test configuration',
fields: [
{
name: 'hooked_field',
type: 'string',
label: 'Hooked Field',
description: 'A hooked field',
required: false,
},
],
}
const values = { hooked_field: '' }
const onChange = vi.fn()
const user = userEvent.setup()
render(<DynamicConfigForm schema={schema} values={values} onChange={onChange} hooks={hooks} />)
await user.click(screen.getByRole('button'))
expect(onChange).toHaveBeenCalledWith('hooked_field', 'hook_value')
})
})
describe('edge cases', () => {
it('renders with empty nested values', () => {
const schema: ConfigSchema = {
className: 'MainConfig',
classDoc: 'Main configuration',
fields: [],
nested: {
sub_config: {
className: 'SubConfig',
classDoc: 'Sub configuration',
fields: [
{
name: 'nested_field',
type: 'string',
label: 'Nested Field',
description: 'Nested field',
required: false,
},
],
},
},
}
const values = {}
const onChange = vi.fn()
render(<DynamicConfigForm schema={schema} values={values} onChange={onChange} />)
expect(screen.getByText('SubConfig')).toBeInTheDocument()
expect(screen.getByText('Nested Field')).toBeInTheDocument()
})
it('uses default hook registry when not provided', () => {
const schema: ConfigSchema = {
className: 'TestConfig',
classDoc: 'Test configuration',
fields: [
{
name: 'test_field',
type: 'string',
label: 'Test Field',
description: 'A test field',
required: false,
},
],
}
const values = { test_field: 'test' }
const onChange = vi.fn()
render(<DynamicConfigForm schema={schema} values={values} onChange={onChange} />)
expect(screen.getByText('Test Field')).toBeInTheDocument()
})
})
})

View File

@ -0,0 +1,395 @@
import { describe, it, expect, vi } from 'vitest'
import { screen } from '@testing-library/dom'
import { render } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { DynamicField } from '../DynamicField'
import type { FieldSchema } from '@/types/config-schema'
describe('DynamicField', () => {
describe('x-widget priority', () => {
it('renders Slider when x-widget is slider', () => {
const schema: FieldSchema = {
name: 'test_slider',
type: 'number',
label: 'Test Slider',
description: 'A test slider',
required: false,
'x-widget': 'slider',
minValue: 0,
maxValue: 100,
default: 50,
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value={50} onChange={onChange} />)
expect(screen.getByText('Test Slider')).toBeInTheDocument()
expect(screen.getByRole('slider')).toBeInTheDocument()
expect(screen.getByText('50')).toBeInTheDocument()
})
it('renders Switch when x-widget is switch', () => {
const schema: FieldSchema = {
name: 'test_switch',
type: 'boolean',
label: 'Test Switch',
description: 'A test switch',
required: false,
'x-widget': 'switch',
default: false,
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value={false} onChange={onChange} />)
expect(screen.getByText('Test Switch')).toBeInTheDocument()
expect(screen.getByRole('switch')).toBeInTheDocument()
})
it('renders Textarea when x-widget is textarea', () => {
const schema: FieldSchema = {
name: 'test_textarea',
type: 'string',
label: 'Test Textarea',
description: 'A test textarea',
required: false,
'x-widget': 'textarea',
default: 'Hello',
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value="Hello" onChange={onChange} />)
expect(screen.getByText('Test Textarea')).toBeInTheDocument()
expect(screen.getByRole('textbox')).toBeInTheDocument()
expect(screen.getByRole('textbox')).toHaveValue('Hello')
})
it('renders Select when x-widget is select', () => {
const schema: FieldSchema = {
name: 'test_select',
type: 'string',
label: 'Test Select',
description: 'A test select',
required: false,
'x-widget': 'select',
options: ['Option 1', 'Option 2', 'Option 3'],
default: 'Option 1',
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value="Option 1" onChange={onChange} />)
expect(screen.getByText('Test Select')).toBeInTheDocument()
expect(screen.getByRole('combobox')).toBeInTheDocument()
})
it('renders placeholder for custom widget', () => {
const schema: FieldSchema = {
name: 'test_custom',
type: 'string',
label: 'Test Custom',
description: 'A test custom field',
required: false,
'x-widget': 'custom',
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value="" onChange={onChange} />)
expect(screen.getByText('Custom field requires Hook')).toBeInTheDocument()
})
})
describe('type fallback', () => {
it('renders Input for string type', () => {
const schema: FieldSchema = {
name: 'test_string',
type: 'string',
label: 'Test String',
description: 'A test string',
required: false,
default: 'Hello',
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value="Hello" onChange={onChange} />)
expect(screen.getByRole('textbox')).toBeInTheDocument()
expect(screen.getByRole('textbox')).toHaveValue('Hello')
})
it('renders Switch for boolean type', () => {
const schema: FieldSchema = {
name: 'test_bool',
type: 'boolean',
label: 'Test Boolean',
description: 'A test boolean',
required: false,
default: true,
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value={true} onChange={onChange} />)
expect(screen.getByRole('switch')).toBeInTheDocument()
expect(screen.getByRole('switch')).toBeChecked()
})
it('renders number Input for number type', () => {
const schema: FieldSchema = {
name: 'test_number',
type: 'number',
label: 'Test Number',
description: 'A test number',
required: false,
default: 42,
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value={42} onChange={onChange} />)
const input = screen.getByRole('spinbutton')
expect(input).toBeInTheDocument()
expect(input).toHaveValue(42)
})
it('renders number Input for integer type', () => {
const schema: FieldSchema = {
name: 'test_integer',
type: 'integer',
label: 'Test Integer',
description: 'A test integer',
required: false,
default: 10,
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value={10} onChange={onChange} />)
const input = screen.getByRole('spinbutton')
expect(input).toBeInTheDocument()
expect(input).toHaveValue(10)
})
it('renders Textarea for textarea type', () => {
const schema: FieldSchema = {
name: 'test_textarea_type',
type: 'textarea',
label: 'Test Textarea Type',
description: 'A test textarea type',
required: false,
default: 'Long text',
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value="Long text" onChange={onChange} />)
expect(screen.getByRole('textbox')).toBeInTheDocument()
expect(screen.getByRole('textbox')).toHaveValue('Long text')
})
it('renders Select for select type', () => {
const schema: FieldSchema = {
name: 'test_select_type',
type: 'select',
label: 'Test Select Type',
description: 'A test select type',
required: false,
options: ['A', 'B', 'C'],
default: 'A',
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value="A" onChange={onChange} />)
expect(screen.getByRole('combobox')).toBeInTheDocument()
})
it('renders placeholder for array type', () => {
const schema: FieldSchema = {
name: 'test_array',
type: 'array',
label: 'Test Array',
description: 'A test array',
required: false,
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value={[]} onChange={onChange} />)
expect(screen.getByText('Array fields not yet supported')).toBeInTheDocument()
})
it('renders placeholder for object type', () => {
const schema: FieldSchema = {
name: 'test_object',
type: 'object',
label: 'Test Object',
description: 'A test object',
required: false,
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value={{}} onChange={onChange} />)
expect(screen.getByText('Object fields not yet supported')).toBeInTheDocument()
})
})
describe('onChange events', () => {
it('triggers onChange for Switch', async () => {
const schema: FieldSchema = {
name: 'test_switch',
type: 'boolean',
label: 'Test Switch',
description: 'A test switch',
required: false,
default: false,
}
const onChange = vi.fn()
const user = userEvent.setup()
render(<DynamicField schema={schema} value={false} onChange={onChange} />)
await user.click(screen.getByRole('switch'))
expect(onChange).toHaveBeenCalledWith(true)
})
it('triggers onChange for Input', async () => {
const schema: FieldSchema = {
name: 'test_input',
type: 'string',
label: 'Test Input',
description: 'A test input',
required: false,
default: '',
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value="" onChange={onChange} />)
const input = screen.getByRole('textbox')
input.focus()
await userEvent.keyboard('Hello')
expect(onChange).toHaveBeenCalledTimes(5)
expect(onChange).toHaveBeenNthCalledWith(1, 'H')
expect(onChange).toHaveBeenNthCalledWith(2, 'e')
expect(onChange).toHaveBeenNthCalledWith(3, 'l')
expect(onChange).toHaveBeenNthCalledWith(4, 'l')
expect(onChange).toHaveBeenNthCalledWith(5, 'o')
})
it('triggers onChange for number Input', async () => {
const schema: FieldSchema = {
name: 'test_number',
type: 'number',
label: 'Test Number',
description: 'A test number',
required: false,
default: 0,
}
const onChange = vi.fn()
const user = userEvent.setup()
render(<DynamicField schema={schema} value={0} onChange={onChange} />)
const input = screen.getByRole('spinbutton')
await user.clear(input)
await user.type(input, '123')
expect(onChange).toHaveBeenCalled()
})
})
describe('visual features', () => {
it('renders label with icon', () => {
const schema: FieldSchema = {
name: 'test_icon',
type: 'string',
label: 'Test Icon',
description: 'A test with icon',
required: false,
'x-icon': 'Settings',
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value="" onChange={onChange} />)
expect(screen.getByText('Test Icon')).toBeInTheDocument()
})
it('renders required indicator', () => {
const schema: FieldSchema = {
name: 'test_required',
type: 'string',
label: 'Test Required',
description: 'A required field',
required: true,
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value="" onChange={onChange} />)
expect(screen.getByText('*')).toBeInTheDocument()
})
it('renders description', () => {
const schema: FieldSchema = {
name: 'test_desc',
type: 'string',
label: 'Test Description',
description: 'This is a description',
required: false,
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value="" onChange={onChange} />)
expect(screen.getByText('This is a description')).toBeInTheDocument()
})
})
describe('slider features', () => {
it('renders slider with min/max/step', () => {
const schema: FieldSchema = {
name: 'test_slider_props',
type: 'number',
label: 'Test Slider Props',
description: 'A slider with props',
required: false,
'x-widget': 'slider',
minValue: 10,
maxValue: 50,
step: 5,
default: 25,
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value={25} onChange={onChange} />)
expect(screen.getByText('10')).toBeInTheDocument()
expect(screen.getByText('50')).toBeInTheDocument()
expect(screen.getByText('25')).toBeInTheDocument()
})
})
describe('select features', () => {
it('renders placeholder when no options', () => {
const schema: FieldSchema = {
name: 'test_select_no_options',
type: 'string',
label: 'Test Select No Options',
description: 'A select with no options',
required: false,
'x-widget': 'select',
}
const onChange = vi.fn()
render(<DynamicField schema={schema} value="" onChange={onChange} />)
expect(screen.getByText('No options available for select')).toBeInTheDocument()
})
})
})

View File

@ -0,0 +1,2 @@
export { DynamicConfigForm } from './DynamicConfigForm'
export { DynamicField } from './DynamicField'

View File

@ -20,6 +20,9 @@ import { cn } from '@/lib/utils'
import { formatVersion } from '@/lib/version'
import type { ReactNode, ComponentType } from 'react'
import type { LucideProps } from 'lucide-react'
import { BackgroundLayer } from '@/components/background-layer'
import { useBackground } from '@/hooks/use-background'
interface LayoutProps {
children: ReactNode
@ -140,6 +143,10 @@ export function Layout({ children }: LayoutProps) {
const actualTheme = getActualTheme()
const pageBg = useBackground('page')
const sidebarBg = useBackground('sidebar')
const headerBg = useBackground('header')
// 登出处理
const handleLogout = async () => {
await logout()
@ -158,6 +165,7 @@ export function Layout({ children }: LayoutProps) {
mobileMenuOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'
)}
>
<BackgroundLayer config={sidebarBg} layerId="sidebar" />
{/* Logo 区域 */}
<div className="flex h-16 items-center border-b px-4">
<div
@ -306,6 +314,7 @@ export function Layout({ children }: LayoutProps) {
{/* Topbar */}
<header className="flex h-16 items-center justify-between border-b bg-card/80 backdrop-blur-md px-4 sticky top-0 z-10">
<BackgroundLayer config={headerBg} layerId="header" />
<div className="flex items-center gap-4">
{/* 移动端菜单按钮 */}
<button
@ -398,7 +407,10 @@ export function Layout({ children }: LayoutProps) {
</header>
{/* Page content */}
<main className="flex-1 overflow-hidden bg-background">{children}</main>
<main className="relative flex-1 overflow-hidden bg-background">
<BackgroundLayer config={pageBg} layerId="page" />
{children}
</main>
{/* Back to Top Button */}
<BackToTop />

View File

@ -1,6 +1,16 @@
import { useEffect, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import type { ReactNode } from 'react'
import { ThemeProviderContext } from '@/lib/theme-context'
import type { UserThemeConfig } from '@/lib/theme/tokens'
import {
THEME_STORAGE_KEYS,
loadThemeConfig,
migrateOldKeys,
resetThemeToDefault,
saveThemePartial,
} from '@/lib/theme/storage'
import { applyThemePipeline, removeCustomCSS } from '@/lib/theme/pipeline'
type Theme = 'dark' | 'light' | 'system'
@ -13,126 +23,74 @@ type ThemeProviderProps = {
export function ThemeProvider({
children,
defaultTheme = 'system',
storageKey = 'ui-theme',
...props
storageKey: _storageKey,
}: ThemeProviderProps) {
const [theme, setTheme] = useState<Theme>(
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
)
const [themeMode, setThemeMode] = useState<Theme>(() => {
const saved = localStorage.getItem(THEME_STORAGE_KEYS.MODE) as Theme | null
return saved || defaultTheme
})
const [themeConfig, setThemeConfig] = useState<UserThemeConfig>(() => loadThemeConfig())
const [systemThemeTick, setSystemThemeTick] = useState(0)
const resolvedTheme = useMemo<'dark' | 'light'>(() => {
if (themeMode !== 'system') return themeMode
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}, [themeMode, systemThemeTick])
useEffect(() => {
const root = window.document.documentElement
root.classList.remove('light', 'dark')
if (theme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
root.classList.add(systemTheme)
return
}
root.classList.add(theme)
}, [theme])
// 应用保存的主题色
useEffect(() => {
const savedAccentColor = localStorage.getItem('accent-color')
if (savedAccentColor) {
const root = document.documentElement
const colors = {
blue: {
hsl: '221.2 83.2% 53.3%',
darkHsl: '217.2 91.2% 59.8%',
gradient: null
},
purple: {
hsl: '271 91% 65%',
darkHsl: '270 95% 75%',
gradient: null
},
green: {
hsl: '142 71% 45%',
darkHsl: '142 76% 36%',
gradient: null
},
orange: {
hsl: '25 95% 53%',
darkHsl: '20 90% 48%',
gradient: null
},
pink: {
hsl: '330 81% 60%',
darkHsl: '330 85% 70%',
gradient: null
},
red: {
hsl: '0 84% 60%',
darkHsl: '0 90% 70%',
gradient: null
},
// 渐变色
'gradient-sunset': {
hsl: '15 95% 60%',
darkHsl: '15 95% 65%',
gradient: 'linear-gradient(135deg, hsl(25 95% 53%) 0%, hsl(330 81% 60%) 100%)'
},
'gradient-ocean': {
hsl: '200 90% 55%',
darkHsl: '200 90% 60%',
gradient: 'linear-gradient(135deg, hsl(221.2 83.2% 53.3%) 0%, hsl(189 94% 43%) 100%)'
},
'gradient-forest': {
hsl: '150 70% 45%',
darkHsl: '150 75% 40%',
gradient: 'linear-gradient(135deg, hsl(142 71% 45%) 0%, hsl(158 64% 52%) 100%)'
},
'gradient-aurora': {
hsl: '310 85% 65%',
darkHsl: '310 90% 70%',
gradient: 'linear-gradient(135deg, hsl(271 91% 65%) 0%, hsl(330 81% 60%) 100%)'
},
'gradient-fire': {
hsl: '15 95% 55%',
darkHsl: '15 95% 60%',
gradient: 'linear-gradient(135deg, hsl(0 84% 60%) 0%, hsl(25 95% 53%) 100%)'
},
'gradient-twilight': {
hsl: '250 90% 60%',
darkHsl: '250 95% 65%',
gradient: 'linear-gradient(135deg, hsl(239 84% 67%) 0%, hsl(271 91% 65%) 100%)'
},
}
const selectedColor = colors[savedAccentColor as keyof typeof colors]
if (selectedColor) {
root.style.setProperty('--primary', selectedColor.hsl)
// 设置渐变(如果有)
if (selectedColor.gradient) {
root.style.setProperty('--primary-gradient', selectedColor.gradient)
root.classList.add('has-gradient')
} else {
root.style.removeProperty('--primary-gradient')
root.classList.remove('has-gradient')
}
}
}
migrateOldKeys()
}, [])
const value = {
theme,
setTheme: (theme: Theme) => {
localStorage.setItem(storageKey, theme)
setTheme(theme)
},
}
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
const handleChange = () => {
if (themeMode === 'system') {
setSystemThemeTick((prev) => prev + 1)
}
}
mediaQuery.addEventListener('change', handleChange)
return () => mediaQuery.removeEventListener('change', handleChange)
}, [themeMode])
useEffect(() => {
const root = document.documentElement
root.classList.remove('light', 'dark')
root.classList.add(resolvedTheme)
const isDark = resolvedTheme === 'dark'
applyThemePipeline(themeConfig, isDark)
}, [resolvedTheme, themeConfig])
const setTheme = useCallback((mode: Theme) => {
localStorage.setItem(THEME_STORAGE_KEYS.MODE, mode)
setThemeMode(mode)
}, [])
const updateThemeConfig = useCallback((partial: Partial<UserThemeConfig>) => {
saveThemePartial(partial)
setThemeConfig((prev) => ({ ...prev, ...partial }))
}, [])
const resetTheme = useCallback(() => {
resetThemeToDefault()
removeCustomCSS()
setThemeConfig(loadThemeConfig())
}, [])
const value = useMemo(
() => ({
theme: themeMode,
resolvedTheme,
setTheme,
themeConfig,
updateThemeConfig,
resetTheme,
}),
[themeMode, resolvedTheme, setTheme, themeConfig, updateThemeConfig, resetTheme],
)
return (
<ThemeProviderContext.Provider {...props} value={value}>
<ThemeProviderContext.Provider value={value}>
{children}
</ThemeProviderContext.Provider>
)

View File

@ -7,10 +7,10 @@ import { useTour } from './use-tour'
const joyrideStyles = {
options: {
zIndex: 10000,
primaryColor: 'hsl(var(--primary))',
textColor: 'hsl(var(--foreground))',
backgroundColor: 'hsl(var(--background))',
arrowColor: 'hsl(var(--background))',
primaryColor: 'hsl(var(--color-primary))',
textColor: 'hsl(var(--color-foreground))',
backgroundColor: 'hsl(var(--color-background))',
arrowColor: 'hsl(var(--color-background))',
overlayColor: 'rgba(0, 0, 0, 0.5)',
},
tooltip: {
@ -30,23 +30,23 @@ const joyrideStyles = {
padding: '0.5rem 0',
},
buttonNext: {
backgroundColor: 'hsl(var(--primary))',
color: 'hsl(var(--primary-foreground))',
backgroundColor: 'hsl(var(--color-primary))',
color: 'hsl(var(--color-primary-foreground))',
borderRadius: 'calc(var(--radius) - 2px)',
fontSize: '0.875rem',
padding: '0.5rem 1rem',
},
buttonBack: {
color: 'hsl(var(--muted-foreground))',
color: 'hsl(var(--color-muted-foreground))',
fontSize: '0.875rem',
marginRight: '0.5rem',
},
buttonSkip: {
color: 'hsl(var(--muted-foreground))',
color: 'hsl(var(--color-muted-foreground))',
fontSize: '0.875rem',
},
buttonClose: {
color: 'hsl(var(--muted-foreground))',
color: 'hsl(var(--color-muted-foreground))',
},
spotlight: {
borderRadius: 'var(--radius)',

View File

@ -0,0 +1,27 @@
import type { ComponentPropsWithoutRef, ElementRef } from 'react'
import { forwardRef } from 'react'
import { cn } from '@/lib/utils'
import { BackgroundLayer } from '@/components/background-layer'
import { Card } from '@/components/ui/card'
import { useBackground } from '@/hooks/use-background'
type CardWithBackgroundProps = ComponentPropsWithoutRef<typeof Card>
export const CardWithBackground = forwardRef<
ElementRef<typeof Card>,
CardWithBackgroundProps
>(({ className, children, ...props }, ref) => {
const bg = useBackground('card')
return (
<Card ref={ref} className={cn('relative', className)} {...props}>
<BackgroundLayer config={bg} layerId="card" />
{children}
</Card>
)
})
CardWithBackground.displayName = 'CardWithBackground'

View File

@ -0,0 +1,27 @@
import type { ComponentPropsWithoutRef, ElementRef } from 'react'
import { forwardRef } from 'react'
import { cn } from '@/lib/utils'
import { BackgroundLayer } from '@/components/background-layer'
import { DialogContent } from '@/components/ui/dialog'
import { useBackground } from '@/hooks/use-background'
type DialogContentWithBackgroundProps = ComponentPropsWithoutRef<typeof DialogContent>
export const DialogContentWithBackground = forwardRef<
ElementRef<typeof DialogContent>,
DialogContentWithBackgroundProps
>(({ className, children, ...props }, ref) => {
const bg = useBackground('dialog')
return (
<DialogContent ref={ref} className={cn('relative', className)} {...props}>
<BackgroundLayer config={bg} layerId="dialog" />
{children}
</DialogContent>
)
})
DialogContentWithBackground.displayName = 'DialogContentWithBackground'

View File

@ -354,7 +354,7 @@ export function WavesBackground() {
left: 0,
width: '0.5rem',
height: '0.5rem',
background: 'hsl(var(--primary) / 0.3)',
background: 'hsl(var(--color-primary) / 0.3)',
borderRadius: '50%',
transform: 'translate3d(calc(var(--x, -0.5rem) - 50%), calc(var(--y, 50%) - 50%), 0)',
willChange: 'transform',
@ -372,7 +372,7 @@ export function WavesBackground() {
<style>{`
path {
fill: none;
stroke: hsl(var(--primary) / 0.20);
stroke: hsl(var(--color-primary) / 0.20);
stroke-width: 1px;
}
`}</style>

View File

@ -0,0 +1,26 @@
import { useTheme } from '@/components/use-theme'
import type { BackgroundConfig } from '@/lib/theme/tokens'
import { defaultBackgroundConfig } from '@/lib/theme/tokens'
type BackgroundLayerId = 'page' | 'sidebar' | 'header' | 'card' | 'dialog'
/**
*
* inherit true
* @param layerId -
* @returns
*/
export function useBackground(layerId: BackgroundLayerId): BackgroundConfig {
const { themeConfig } = useTheme()
const bgMap = themeConfig.backgroundConfig ?? {}
const config = bgMap[layerId] ?? defaultBackgroundConfig
// 处理继承逻辑:非 page 层级且 inherit 为 true返回 page 配置
if (layerId !== 'page' && config.inherit) {
return bgMap.page ?? defaultBackgroundConfig
}
return config
}

View File

@ -13,60 +13,183 @@
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 221.2 83.2% 53.3%;
--primary-foreground: 210 40% 98%;
--primary-gradient: none; /* 默认无渐变 */
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 221.2 83.2% 53.3%;
--radius: 0.5rem;
--chart-1: 221.2 83.2% 53.3%;
--chart-2: 160 60% 45%;
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%;
/* Color Tokens */
--color-primary: 221.2 83.2% 53.3%;
--color-primary-foreground: 210 40% 98%;
--color-primary-gradient: none;
--color-secondary: 210 40% 96.1%;
--color-secondary-foreground: 222.2 47.4% 11.2%;
--color-muted: 210 40% 96.1%;
--color-muted-foreground: 215.4 16.3% 46.9%;
--color-accent: 210 40% 96.1%;
--color-accent-foreground: 222.2 47.4% 11.2%;
--color-destructive: 0 84.2% 60.2%;
--color-destructive-foreground: 210 40% 98%;
--color-background: 0 0% 100%;
--color-foreground: 222.2 84% 4.9%;
--color-card: 0 0% 100%;
--color-card-foreground: 222.2 84% 4.9%;
--color-popover: 0 0% 100%;
--color-popover-foreground: 222.2 84% 4.9%;
--color-border: 214.3 31.8% 91.4%;
--color-input: 214.3 31.8% 91.4%;
--color-ring: 221.2 83.2% 53.3%;
--color-chart-1: 221.2 83.2% 53.3%;
--color-chart-2: 160 60% 45%;
--color-chart-3: 30 80% 55%;
--color-chart-4: 280 65% 60%;
--color-chart-5: 340 75% 55%;
/* Typography Tokens */
--typography-font-family-base: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
--typography-font-family-code: "JetBrains Mono", "Monaco", "Courier New", monospace;
--typography-font-size-xs: 0.75rem;
--typography-font-size-sm: 0.875rem;
--typography-font-size-base: 1rem;
--typography-font-size-lg: 1.125rem;
--typography-font-size-xl: 1.25rem;
--typography-font-size-2xl: 1.5rem;
--typography-font-weight-normal: 400;
--typography-font-weight-medium: 500;
--typography-font-weight-semibold: 600;
--typography-font-weight-bold: 700;
--typography-line-height-tight: 1.2;
--typography-line-height-normal: 1.5;
--typography-line-height-relaxed: 1.75;
--typography-letter-spacing-tight: -0.02em;
--typography-letter-spacing-normal: 0em;
--typography-letter-spacing-wide: 0.02em;
/* Visual Tokens */
--visual-radius-sm: 0.25rem;
--visual-radius-md: 0.375rem;
--visual-radius-lg: 0.5rem;
--visual-radius-xl: 0.75rem;
--visual-radius-full: 9999px;
--visual-shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
--visual-shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
--visual-shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
--visual-shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
--visual-blur-sm: 4px;
--visual-blur-md: 12px;
--visual-blur-lg: 24px;
--visual-opacity-disabled: 0.5;
--visual-opacity-hover: 0.8;
--visual-opacity-overlay: 0.75;
/* Layout Tokens */
--layout-space-unit: 0.25rem;
--layout-space-xs: 0.5rem;
--layout-space-sm: 0.75rem;
--layout-space-md: 1rem;
--layout-space-lg: 1.5rem;
--layout-space-xl: 2rem;
--layout-space-2xl: 3rem;
--layout-sidebar-width: 16rem;
--layout-header-height: 3.5rem;
--layout-max-content-width: 1280px;
/* Animation Tokens */
--animation-anim-duration-fast: 150ms;
--animation-anim-duration-normal: 300ms;
--animation-anim-duration-slow: 500ms;
--animation-anim-easing-default: cubic-bezier(0.4, 0, 0.2, 1);
--animation-anim-easing-in: cubic-bezier(0.4, 0, 1, 1);
--animation-anim-easing-out: cubic-bezier(0, 0, 0.2, 1);
--animation-anim-easing-in-out: cubic-bezier(0.4, 0, 0.2, 1);
--animation-transition-colors: color 300ms cubic-bezier(0.4, 0, 0.2, 1);
--animation-transition-transform: transform 300ms cubic-bezier(0.4, 0, 0.2, 1);
--animation-transition-opacity: opacity 300ms cubic-bezier(0.4, 0, 0.2, 1);
/* Legacy Aliases (backward compatibility) */
--background: var(--color-background);
--foreground: var(--color-foreground);
--card: var(--color-card);
--card-foreground: var(--color-card-foreground);
--popover: var(--color-popover);
--popover-foreground: var(--color-popover-foreground);
--primary: var(--color-primary);
--primary-foreground: var(--color-primary-foreground);
--primary-gradient: var(--color-primary-gradient);
--secondary: var(--color-secondary);
--secondary-foreground: var(--color-secondary-foreground);
--muted: var(--color-muted);
--muted-foreground: var(--color-muted-foreground);
--accent: var(--color-accent);
--accent-foreground: var(--color-accent-foreground);
--destructive: var(--color-destructive);
--destructive-foreground: var(--color-destructive-foreground);
--border: var(--color-border);
--input: var(--color-input);
--ring: var(--color-ring);
--radius: var(--visual-radius-lg);
--chart-1: var(--color-chart-1);
--chart-2: var(--color-chart-2);
--chart-3: var(--color-chart-3);
--chart-4: var(--color-chart-4);
--chart-5: var(--color-chart-5);
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 217.2 91.2% 59.8%;
--primary-foreground: 210 40% 98%;
--primary-gradient: none; /* 默认无渐变 */
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 224.3 76.3% 48%;
--chart-1: 217.2 91.2% 59.8%;
--chart-2: 160 60% 50%;
--chart-3: 30 80% 60%;
--chart-4: 280 65% 65%;
--chart-5: 340 75% 60%;
/* Color Tokens */
--color-primary: 217.2 91.2% 59.8%;
--color-primary-foreground: 210 40% 98%;
--color-primary-gradient: none;
--color-secondary: 217.2 32.6% 17.5%;
--color-secondary-foreground: 210 40% 98%;
--color-muted: 217.2 32.6% 17.5%;
--color-muted-foreground: 215 20.2% 65.1%;
--color-accent: 217.2 32.6% 17.5%;
--color-accent-foreground: 210 40% 98%;
--color-destructive: 0 62.8% 30.6%;
--color-destructive-foreground: 210 40% 98%;
--color-background: 222.2 84% 4.9%;
--color-foreground: 210 40% 98%;
--color-card: 222.2 84% 4.9%;
--color-card-foreground: 210 40% 98%;
--color-popover: 222.2 84% 4.9%;
--color-popover-foreground: 210 40% 98%;
--color-border: 217.2 32.6% 17.5%;
--color-input: 217.2 32.6% 17.5%;
--color-ring: 224.3 76.3% 48%;
--color-chart-1: 217.2 91.2% 59.8%;
--color-chart-2: 160 60% 50%;
--color-chart-3: 30 80% 60%;
--color-chart-4: 280 65% 65%;
--color-chart-5: 340 75% 60%;
/* Visual Tokens (dark mode shadows) */
--visual-shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.25);
--visual-shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.3);
--visual-shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.4);
--visual-shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.5);
/* Legacy Aliases (backward compatibility) */
--background: var(--color-background);
--foreground: var(--color-foreground);
--card: var(--color-card);
--card-foreground: var(--color-card-foreground);
--popover: var(--color-popover);
--popover-foreground: var(--color-popover-foreground);
--primary: var(--color-primary);
--primary-foreground: var(--color-primary-foreground);
--primary-gradient: var(--color-primary-gradient);
--secondary: var(--color-secondary);
--secondary-foreground: var(--color-secondary-foreground);
--muted: var(--color-muted);
--muted-foreground: var(--color-muted-foreground);
--accent: var(--color-accent);
--accent-foreground: var(--color-accent-foreground);
--destructive: var(--color-destructive);
--destructive-foreground: var(--color-destructive-foreground);
--border: var(--color-border);
--input: var(--color-input);
--ring: var(--color-ring);
--chart-1: var(--color-chart-1);
--chart-2: var(--color-chart-2);
--chart-3: var(--color-chart-3);
--chart-4: var(--color-chart-4);
--chart-5: var(--color-chart-5);
}
}
@ -92,28 +215,24 @@
}
@layer utilities {
/* 渐变色背景工具类 */
.bg-primary-gradient {
background: var(--primary-gradient, hsl(var(--primary)));
background: var(--color-primary-gradient, hsl(var(--color-primary)));
}
/* 渐变色文字工具类 - 默认使用普通文字颜色 */
.text-primary-gradient {
color: hsl(var(--primary));
color: hsl(var(--color-primary));
}
/* 当应用了 has-gradient 类时,使用渐变文字效果 */
.has-gradient .text-primary-gradient {
background: var(--primary-gradient);
background: var(--color-primary-gradient);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
color: transparent;
}
/* 渐变色边框工具类 */
.border-primary-gradient {
border-image: var(--primary-gradient, linear-gradient(to right, hsl(var(--primary)), hsl(var(--primary)))) 1;
border-image: var(--color-primary-gradient, linear-gradient(to right, hsl(var(--color-primary)), hsl(var(--color-primary)))) 1;
}
}
@ -170,10 +289,9 @@
pointer-events: auto;
}
/* 自定义滚动条样式 */
.custom-scrollbar {
scrollbar-width: thin;
scrollbar-color: hsl(var(--border)) transparent;
scrollbar-color: hsl(var(--color-border)) transparent;
}
.custom-scrollbar::-webkit-scrollbar {
@ -187,14 +305,14 @@
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: hsl(var(--border));
background: hsl(var(--color-border));
border-radius: 4px;
border: 2px solid transparent;
background-clip: content-box;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
background: hsl(var(--muted-foreground) / 0.5);
background: hsl(var(--color-muted-foreground) / 0.5);
background-clip: content-box;
}

View File

@ -0,0 +1,253 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { FieldHookRegistry } from '../field-hooks'
import type { FieldHookComponent } from '../field-hooks'
describe('FieldHookRegistry', () => {
let registry: FieldHookRegistry
beforeEach(() => {
registry = new FieldHookRegistry()
})
describe('register', () => {
it('registers a hook with replace type', () => {
const component: FieldHookComponent = () => null
registry.register('test.field', component, 'replace')
expect(registry.has('test.field')).toBe(true)
})
it('registers a hook with wrapper type', () => {
const component: FieldHookComponent = () => null
registry.register('test.field', component, 'wrapper')
expect(registry.has('test.field')).toBe(true)
const entry = registry.get('test.field')
expect(entry?.type).toBe('wrapper')
})
it('defaults to replace type when not specified', () => {
const component: FieldHookComponent = () => null
registry.register('test.field', component)
const entry = registry.get('test.field')
expect(entry?.type).toBe('replace')
})
it('overwrites existing hook for same field path', () => {
const component1: FieldHookComponent = () => null
const component2: FieldHookComponent = () => null
registry.register('test.field', component1, 'replace')
registry.register('test.field', component2, 'wrapper')
const entry = registry.get('test.field')
expect(entry?.component).toBe(component2)
expect(entry?.type).toBe('wrapper')
})
})
describe('get', () => {
it('returns hook entry for registered field path', () => {
const component: FieldHookComponent = () => null
registry.register('test.field', component, 'replace')
const entry = registry.get('test.field')
expect(entry).toBeDefined()
expect(entry?.component).toBe(component)
expect(entry?.type).toBe('replace')
})
it('returns undefined for unregistered field path', () => {
const entry = registry.get('nonexistent.field')
expect(entry).toBeUndefined()
})
it('returns correct entry for nested field paths', () => {
const component: FieldHookComponent = () => null
registry.register('config.section.field', component, 'wrapper')
const entry = registry.get('config.section.field')
expect(entry).toBeDefined()
expect(entry?.type).toBe('wrapper')
})
})
describe('has', () => {
it('returns true for registered field path', () => {
const component: FieldHookComponent = () => null
registry.register('test.field', component)
expect(registry.has('test.field')).toBe(true)
})
it('returns false for unregistered field path', () => {
expect(registry.has('nonexistent.field')).toBe(false)
})
it('returns false after unregistering', () => {
const component: FieldHookComponent = () => null
registry.register('test.field', component)
registry.unregister('test.field')
expect(registry.has('test.field')).toBe(false)
})
})
describe('unregister', () => {
it('removes a registered hook', () => {
const component: FieldHookComponent = () => null
registry.register('test.field', component)
expect(registry.has('test.field')).toBe(true)
registry.unregister('test.field')
expect(registry.has('test.field')).toBe(false)
})
it('does not throw when unregistering non-existent hook', () => {
expect(() => registry.unregister('nonexistent.field')).not.toThrow()
})
it('only removes specified hook, not others', () => {
const component1: FieldHookComponent = () => null
const component2: FieldHookComponent = () => null
registry.register('field1', component1)
registry.register('field2', component2)
registry.unregister('field1')
expect(registry.has('field1')).toBe(false)
expect(registry.has('field2')).toBe(true)
})
})
describe('clear', () => {
it('removes all registered hooks', () => {
const component1: FieldHookComponent = () => null
const component2: FieldHookComponent = () => null
const component3: FieldHookComponent = () => null
registry.register('field1', component1)
registry.register('field2', component2)
registry.register('field3', component3)
expect(registry.getAllPaths()).toHaveLength(3)
registry.clear()
expect(registry.getAllPaths()).toHaveLength(0)
expect(registry.has('field1')).toBe(false)
expect(registry.has('field2')).toBe(false)
expect(registry.has('field3')).toBe(false)
})
it('works correctly on empty registry', () => {
expect(() => registry.clear()).not.toThrow()
expect(registry.getAllPaths()).toHaveLength(0)
})
})
describe('getAllPaths', () => {
it('returns empty array when no hooks registered', () => {
expect(registry.getAllPaths()).toEqual([])
})
it('returns all registered field paths', () => {
const component: FieldHookComponent = () => null
registry.register('field1', component)
registry.register('field2', component)
registry.register('field3', component)
const paths = registry.getAllPaths()
expect(paths).toHaveLength(3)
expect(paths).toContain('field1')
expect(paths).toContain('field2')
expect(paths).toContain('field3')
})
it('returns updated paths after unregister', () => {
const component: FieldHookComponent = () => null
registry.register('field1', component)
registry.register('field2', component)
registry.register('field3', component)
registry.unregister('field2')
const paths = registry.getAllPaths()
expect(paths).toHaveLength(2)
expect(paths).toContain('field1')
expect(paths).toContain('field3')
expect(paths).not.toContain('field2')
})
it('handles nested field paths correctly', () => {
const component: FieldHookComponent = () => null
registry.register('config.chat.enabled', component)
registry.register('config.chat.model', component)
registry.register('config.api.key', component)
const paths = registry.getAllPaths()
expect(paths).toHaveLength(3)
expect(paths).toContain('config.chat.enabled')
expect(paths).toContain('config.chat.model')
expect(paths).toContain('config.api.key')
})
})
describe('integration scenarios', () => {
it('supports full lifecycle of multiple hooks', () => {
const replaceComponent: FieldHookComponent = () => null
const wrapperComponent: FieldHookComponent = () => null
registry.register('field1', replaceComponent, 'replace')
registry.register('field2', wrapperComponent, 'wrapper')
expect(registry.getAllPaths()).toHaveLength(2)
const entry1 = registry.get('field1')
expect(entry1?.type).toBe('replace')
expect(entry1?.component).toBe(replaceComponent)
const entry2 = registry.get('field2')
expect(entry2?.type).toBe('wrapper')
expect(entry2?.component).toBe(wrapperComponent)
registry.unregister('field1')
expect(registry.getAllPaths()).toHaveLength(1)
expect(registry.has('field2')).toBe(true)
registry.clear()
expect(registry.getAllPaths()).toHaveLength(0)
})
it('handles rapid register/unregister cycles', () => {
const component: FieldHookComponent = () => null
for (let i = 0; i < 100; i++) {
registry.register(`field${i}`, component)
}
expect(registry.getAllPaths()).toHaveLength(100)
for (let i = 0; i < 50; i++) {
registry.unregister(`field${i}`)
}
expect(registry.getAllPaths()).toHaveLength(50)
registry.clear()
expect(registry.getAllPaths()).toHaveLength(0)
})
})
})

View File

@ -0,0 +1,95 @@
/**
* API
*/
import { fetchWithAuth, getAuthHeaders } from '@/lib/fetch-with-auth'
const API_BASE = '/api/webui/config'
export interface AdapterConfigPath {
path: string
lastModified?: string
}
interface ConfigPathResponse {
success: boolean
path?: string
lastModified?: string
}
interface ConfigContentResponse {
success: boolean
content: string
}
interface ConfigMessageResponse {
success: boolean
message: string
}
/**
*
*/
export async function getSavedConfigPath(): Promise<AdapterConfigPath | null> {
const response = await fetchWithAuth(`${API_BASE}/adapter-config/path`)
const data: ConfigPathResponse = await response.json()
if (!data.success || !data.path) {
return null
}
return {
path: data.path,
lastModified: data.lastModified,
}
}
/**
*
*/
export async function saveConfigPath(path: string): Promise<void> {
const response = await fetchWithAuth(`${API_BASE}/adapter-config/path`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({ path }),
})
const data: ConfigMessageResponse = await response.json()
if (!data.success) {
throw new Error(data.message || '保存路径失败')
}
}
/**
*
*/
export async function loadConfigFromPath(path: string): Promise<string> {
const response = await fetchWithAuth(
`${API_BASE}/adapter-config?path=${encodeURIComponent(path)}`
)
const data: ConfigContentResponse = await response.json()
if (!data.success) {
throw new Error('读取配置文件失败')
}
return data.content
}
/**
*
*/
export async function saveConfigToPath(path: string, content: string): Promise<void> {
const response = await fetchWithAuth(`${API_BASE}/adapter-config`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({ path, content }),
})
const data: ConfigMessageResponse = await response.json()
if (!data.success) {
throw new Error(data.message || '保存配置失败')
}
}

View File

@ -0,0 +1,10 @@
import { createContext } from 'react'
export type AnimationSettings = {
enableAnimations: boolean
enableWavesBackground: boolean
setEnableAnimations: (enable: boolean) => void
setEnableWavesBackground: (enable: boolean) => void
}
export const AnimationContext = createContext<AnimationSettings | undefined>(undefined)

View File

@ -0,0 +1,136 @@
import { fetchWithAuth } from './fetch-with-auth'
export interface TimeFootprintData {
total_online_hours: number
first_message_time: string | null
first_message_user: string | null
first_message_content: string | null
busiest_day: string | null
busiest_day_count: number
hourly_distribution: number[]
midnight_chat_count: number
is_night_owl: boolean
}
export interface SocialNetworkData {
total_groups: number
top_groups: Array<{
group_id: string
group_name: string
message_count: number
is_webui?: boolean
}>
top_users: Array<{
user_id: string
user_nickname: string
message_count: number
is_webui?: boolean
}>
at_count: number
mentioned_count: number
longest_companion_user: string | null
longest_companion_days: number
}
export interface BrainPowerData {
total_tokens: number
total_cost: number
favorite_model: string | null
favorite_model_count: number
model_distribution: Array<{
model: string
count: number
tokens: number
cost: number
}>
top_reply_models: Array<{
model: string
count: number
}>
most_expensive_cost: number
most_expensive_time: string | null
top_token_consumers: Array<{
user_id: string
cost: number
tokens: number
}>
silence_rate: number
total_actions: number
no_reply_count: number
avg_interest_value: number
max_interest_value: number
max_interest_time: string | null
avg_reasoning_length: number
max_reasoning_length: number
max_reasoning_time: string | null
}
export interface ExpressionVibeData {
top_emoji: {
id: number
path: string
description: string
usage_count: number
hash: string
} | null
top_emojis: Array<{
id: number
path: string
description: string
usage_count: number
hash: string
}>
top_expressions: Array<{
style: string
count: number
}>
rejected_expression_count: number
checked_expression_count: number
total_expressions: number
action_types: Array<{
action: string
count: number
}>
image_processed_count: number
late_night_reply: {
time: string
content: string
} | null
favorite_reply: {
content: string
count: number
} | null
}
export interface AchievementData {
new_jargon_count: number
sample_jargons: Array<{
content: string
meaning: string
count: number
}>
total_messages: number
total_replies: number
}
export interface AnnualReportData {
year: number
bot_name: string
generated_at: string
time_footprint: TimeFootprintData
social_network: SocialNetworkData
brain_power: BrainPowerData
expression_vibe: ExpressionVibeData
achievements: AchievementData
}
export async function getAnnualReport(year: number = 2025): Promise<AnnualReportData> {
const response = await fetchWithAuth(`/api/webui/annual-report/full?year=${year}`)
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取年度报告失败')
}
return response.json()
}

View File

@ -0,0 +1,8 @@
import axios from 'axios'
const apiClient = axios.create({
baseURL: import.meta.env.DEV ? 'http://localhost:8000' : '',
timeout: 10000,
})
export default apiClient

View File

@ -0,0 +1,111 @@
/**
* IndexedDB
* 使 idb IndexedDB
*/
import { openDB, type IDBPDatabase } from 'idb'
/**
*
*/
export type AssetRecord = {
/** 资源唯一标识符 (UUID v4) */
id: string
/** 文件名 */
filename: string
/** 资源类型 */
type: 'image' | 'video'
/** MIME 类型 */
mimeType: string
/** 文件内容 */
blob: Blob
/** 文件大小(字节) */
size: number
/** 创建时间戳 */
createdAt: number
}
// 常量定义
const DB_NAME = 'maibot-assets'
const STORE_NAME = 'assets'
const DB_VERSION = 1
/**
*
* IndexedDB object store
*
* @returns
*/
export async function openAssetDB(): Promise<IDBPDatabase<unknown>> {
return openDB(DB_NAME, DB_VERSION, {
upgrade(db) {
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME, { keyPath: 'id' })
}
},
})
}
/**
* IndexedDB
* MIME 使 UUID v4 ID
*
* @param file -
* @returns ID (UUID v4)
*/
export async function addAsset(file: File): Promise<string> {
const db = await openAssetDB()
const id = crypto.randomUUID()
// 根据 file.type 判断资源类型
const type: 'image' | 'video' = file.type.startsWith('video/') ? 'video' : 'image'
const asset: AssetRecord = {
id,
filename: file.name,
type,
mimeType: file.type,
blob: file,
size: file.size,
createdAt: Date.now(),
}
await db.add(STORE_NAME, asset)
return id
}
/**
* ID
* undefined
*
* @param id - ID
* @returns undefined
*/
export async function getAsset(id: string): Promise<AssetRecord | undefined> {
const db = await openAssetDB()
return (await db.get(STORE_NAME, id)) as AssetRecord | undefined
}
/**
* ID
*
*
* @param id - ID
*/
export async function deleteAsset(id: string): Promise<void> {
const db = await openAssetDB()
await db.delete(STORE_NAME, id)
}
/**
*
*
*
* @returns
*/
export async function listAssets(): Promise<AssetRecord[]> {
const db = await openAssetDB()
const assets = (await db.getAll(STORE_NAME)) as AssetRecord[]
// 按创建时间倒序排列(最新的在前)
return assets.sort((a, b) => b.createdAt - a.createdAt)
}

View File

@ -0,0 +1,269 @@
/**
* API
*/
import { fetchWithAuth } from '@/lib/fetch-with-auth'
import type {
ConfigSchema,
ConfigSchemaResponse,
ConfigDataResponse,
ConfigUpdateResponse,
} from '@/types/config-schema'
const API_BASE = '/api/webui/config'
/**
*
*/
export async function getBotConfigSchema(): Promise<ConfigSchema> {
const response = await fetchWithAuth(`${API_BASE}/schema/bot`)
const data: ConfigSchemaResponse = await response.json()
if (!data.success) {
throw new Error('获取配置架构失败')
}
return data.schema
}
/**
*
*/
export async function getModelConfigSchema(): Promise<ConfigSchema> {
const response = await fetchWithAuth(`${API_BASE}/schema/model`)
const data: ConfigSchemaResponse = await response.json()
if (!data.success) {
throw new Error('获取模型配置架构失败')
}
return data.schema
}
/**
*
*/
export async function getConfigSectionSchema(sectionName: string): Promise<ConfigSchema> {
const response = await fetchWithAuth(`${API_BASE}/schema/section/${sectionName}`)
const data: ConfigSchemaResponse = await response.json()
if (!data.success) {
throw new Error(`获取配置节 ${sectionName} 架构失败`)
}
return data.schema
}
/**
*
*/
export async function getBotConfig(): Promise<Record<string, unknown>> {
const response = await fetchWithAuth(`${API_BASE}/bot`)
const data: ConfigDataResponse = await response.json()
if (!data.success) {
throw new Error('获取配置数据失败')
}
return data.config
}
/**
*
*/
export async function getModelConfig(): Promise<Record<string, unknown>> {
const response = await fetchWithAuth(`${API_BASE}/model`)
const data: ConfigDataResponse = await response.json()
if (!data.success) {
throw new Error('获取模型配置数据失败')
}
return data.config
}
/**
*
*/
export async function updateBotConfig(config: Record<string, unknown>): Promise<void> {
const response = await fetchWithAuth(`${API_BASE}/bot`, {
method: 'POST',
body: JSON.stringify(config),
})
const data: ConfigUpdateResponse = await response.json()
if (!data.success) {
throw new Error(data.message || '保存配置失败')
}
}
/**
* TOML
*/
export async function getBotConfigRaw(): Promise<string> {
const response = await fetchWithAuth(`${API_BASE}/bot/raw`)
const data: { success: boolean; content: string } = await response.json()
if (!data.success) {
throw new Error('获取配置源代码失败')
}
return data.content
}
/**
* TOML
*/
export async function updateBotConfigRaw(rawContent: string): Promise<void> {
const response = await fetchWithAuth(`${API_BASE}/bot/raw`, {
method: 'POST',
body: JSON.stringify({ raw_content: rawContent }),
})
const data: ConfigUpdateResponse = await response.json()
if (!data.success) {
throw new Error(data.message || '保存配置失败')
}
}
/**
*
*/
export async function updateModelConfig(config: Record<string, unknown>): Promise<void> {
const response = await fetchWithAuth(`${API_BASE}/model`, {
method: 'POST',
body: JSON.stringify(config),
})
const data: ConfigUpdateResponse = await response.json()
if (!data.success) {
throw new Error(data.message || '保存配置失败')
}
}
/**
*
*/
export async function updateBotConfigSection(
sectionName: string,
sectionData: unknown
): Promise<void> {
const response = await fetchWithAuth(`${API_BASE}/bot/section/${sectionName}`, {
method: 'POST',
body: JSON.stringify(sectionData),
})
const data: ConfigUpdateResponse = await response.json()
if (!data.success) {
throw new Error(data.message || `保存配置节 ${sectionName} 失败`)
}
}
/**
*
*/
export async function updateModelConfigSection(
sectionName: string,
sectionData: unknown
): Promise<void> {
const response = await fetchWithAuth(`${API_BASE}/model/section/${sectionName}`, {
method: 'POST',
body: JSON.stringify(sectionData),
})
const data: ConfigUpdateResponse = await response.json()
if (!data.success) {
throw new Error(data.message || `保存配置节 ${sectionName} 失败`)
}
}
/**
*
*/
export interface ModelListItem {
id: string
name: string
owned_by?: string
}
/**
*
*/
export interface FetchModelsResponse {
success: boolean
models: ModelListItem[]
provider?: string
count: number
}
/**
*
* @param providerName model_config.toml
* @param parser ('openai' | 'gemini')
* @param endpoint '/models'
*/
export async function fetchProviderModels(
providerName: string,
parser: 'openai' | 'gemini' = 'openai',
endpoint: string = '/models'
): Promise<ModelListItem[]> {
const params = new URLSearchParams({
provider_name: providerName,
parser,
endpoint,
})
const response = await fetchWithAuth(`/api/webui/models/list?${params}`)
// 处理非 2xx 响应
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
throw new Error(errorData.detail || `获取模型列表失败 (${response.status})`)
}
const data: FetchModelsResponse = await response.json()
if (!data.success) {
throw new Error('获取模型列表失败')
}
return data.models
}
/**
*
*/
export interface TestConnectionResult {
network_ok: boolean
api_key_valid: boolean | null
latency_ms: number | null
error: string | null
http_status: number | null
}
/**
*
* @param providerName
*/
export async function testProviderConnection(providerName: string): Promise<TestConnectionResult> {
const params = new URLSearchParams({
provider_name: providerName,
})
const response = await fetchWithAuth(`/api/webui/models/test-connection-by-name?${params}`, {
method: 'POST',
})
// 处理非 2xx 响应
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
throw new Error(errorData.detail || `测试连接失败 (${response.status})`)
}
return await response.json()
}

View File

@ -0,0 +1,284 @@
/**
* API
*/
import { fetchWithAuth } from '@/lib/fetch-with-auth'
import type {
EmojiListResponse,
EmojiDetailResponse,
EmojiUpdateRequest,
EmojiUpdateResponse,
EmojiDeleteResponse,
EmojiStatsResponse,
} from '@/types/emoji'
const API_BASE = '/api/webui/emoji'
/**
*
*/
export async function getEmojiList(params: {
page?: number
page_size?: number
search?: string
is_registered?: boolean
is_banned?: boolean
format?: string
sort_by?: string
sort_order?: 'asc' | 'desc'
}): Promise<EmojiListResponse> {
const query = new URLSearchParams()
if (params.page) query.append('page', params.page.toString())
if (params.page_size) query.append('page_size', params.page_size.toString())
if (params.search) query.append('search', params.search)
if (params.is_registered !== undefined) query.append('is_registered', params.is_registered.toString())
if (params.is_banned !== undefined) query.append('is_banned', params.is_banned.toString())
if (params.format) query.append('format', params.format)
if (params.sort_by) query.append('sort_by', params.sort_by)
if (params.sort_order) query.append('sort_order', params.sort_order)
const response = await fetchWithAuth(`${API_BASE}/list?${query}`, {
})
if (!response.ok) {
throw new Error(`获取表情包列表失败: ${response.statusText}`)
}
return response.json()
}
/**
*
*/
export async function getEmojiDetail(id: number): Promise<EmojiDetailResponse> {
const response = await fetchWithAuth(`${API_BASE}/${id}`, {
})
if (!response.ok) {
throw new Error(`获取表情包详情失败: ${response.statusText}`)
}
return response.json()
}
/**
*
*/
export async function updateEmoji(
id: number,
data: EmojiUpdateRequest
): Promise<EmojiUpdateResponse> {
const response = await fetchWithAuth(`${API_BASE}/${id}`, {
method: 'PATCH',
body: JSON.stringify(data),
})
if (!response.ok) {
throw new Error(`更新表情包失败: ${response.statusText}`)
}
return response.json()
}
/**
*
*/
export async function deleteEmoji(id: number): Promise<EmojiDeleteResponse> {
const response = await fetchWithAuth(`${API_BASE}/${id}`, {
method: 'DELETE',
})
if (!response.ok) {
throw new Error(`删除表情包失败: ${response.statusText}`)
}
return response.json()
}
/**
*
*/
export async function getEmojiStats(): Promise<EmojiStatsResponse> {
const response = await fetchWithAuth(`${API_BASE}/stats/summary`, {
})
if (!response.ok) {
throw new Error(`获取统计数据失败: ${response.statusText}`)
}
return response.json()
}
/**
*
*/
export async function registerEmoji(id: number): Promise<EmojiUpdateResponse> {
const response = await fetchWithAuth(`${API_BASE}/${id}/register`, {
method: 'POST',
})
if (!response.ok) {
throw new Error(`注册表情包失败: ${response.statusText}`)
}
return response.json()
}
/**
*
*/
export async function banEmoji(id: number): Promise<EmojiUpdateResponse> {
const response = await fetchWithAuth(`${API_BASE}/${id}/ban`, {
method: 'POST',
})
if (!response.ok) {
throw new Error(`封禁表情包失败: ${response.statusText}`)
}
return response.json()
}
/**
* URL
* 使 HttpOnly Cookie
* @param id ID
* @param original
*/
export function getEmojiThumbnailUrl(id: number, original: boolean = false): string {
if (original) {
return `${API_BASE}/${id}/thumbnail?original=true`
}
return `${API_BASE}/${id}/thumbnail`
}
/**
* URL
*/
export function getEmojiOriginalUrl(id: number): string {
return `${API_BASE}/${id}/thumbnail?original=true`
}
/**
*
*/
export async function batchDeleteEmojis(emojiIds: number[]): Promise<{
success: boolean
message: string
deleted_count: number
failed_count: number
failed_ids: number[]
}> {
const response = await fetchWithAuth(`${API_BASE}/batch/delete`, {
method: 'POST',
body: JSON.stringify({ emoji_ids: emojiIds }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '批量删除失败')
}
return response.json()
}
/**
* URL Uppy 使
*/
export function getEmojiUploadUrl(): string {
return `${API_BASE}/upload`
}
/**
* URL
*/
export function getEmojiBatchUploadUrl(): string {
return `${API_BASE}/batch/upload`
}
// ==================== 缩略图缓存管理 API ====================
export interface ThumbnailCacheStatsResponse {
success: boolean
cache_dir: string
total_count: number
total_size_mb: number
emoji_count: number
coverage_percent: number
}
export interface ThumbnailCleanupResponse {
success: boolean
message: string
cleaned_count: number
kept_count: number
}
export interface ThumbnailPreheatResponse {
success: boolean
message: string
generated_count: number
skipped_count: number
failed_count: number
}
/**
*
*/
export async function getThumbnailCacheStats(): Promise<ThumbnailCacheStatsResponse> {
const response = await fetchWithAuth(`${API_BASE}/thumbnail-cache/stats`, {})
if (!response.ok) {
throw new Error(`获取缩略图缓存统计失败: ${response.statusText}`)
}
return response.json()
}
/**
*
*/
export async function cleanupThumbnailCache(): Promise<ThumbnailCleanupResponse> {
const response = await fetchWithAuth(`${API_BASE}/thumbnail-cache/cleanup`, {
method: 'POST',
})
if (!response.ok) {
throw new Error(`清理缩略图缓存失败: ${response.statusText}`)
}
return response.json()
}
/**
*
* @param limit (1-1000)
*/
export async function preheatThumbnailCache(limit: number = 100): Promise<ThumbnailPreheatResponse> {
const response = await fetchWithAuth(`${API_BASE}/thumbnail-cache/preheat?limit=${limit}`, {
method: 'POST',
})
if (!response.ok) {
throw new Error(`预热缩略图缓存失败: ${response.statusText}`)
}
return response.json()
}
/**
*
*/
export async function clearAllThumbnailCache(): Promise<ThumbnailCleanupResponse> {
const response = await fetchWithAuth(`${API_BASE}/thumbnail-cache/clear`, {
method: 'DELETE',
})
if (!response.ok) {
throw new Error(`清空缩略图缓存失败: ${response.statusText}`)
}
return response.json()
}

View File

@ -0,0 +1,236 @@
/**
* API
*/
import { fetchWithAuth } from '@/lib/fetch-with-auth'
import type {
ExpressionListResponse,
ExpressionDetailResponse,
ExpressionCreateRequest,
ExpressionCreateResponse,
ExpressionUpdateRequest,
ExpressionUpdateResponse,
ExpressionDeleteResponse,
ExpressionStatsResponse,
ChatListResponse,
ReviewStats,
ReviewListResponse,
BatchReviewItem,
BatchReviewResponse,
} from '@/types/expression'
const API_BASE = '/api/webui/expression'
/**
*
*/
export async function getChatList(): Promise<ChatListResponse> {
const response = await fetchWithAuth(`${API_BASE}/chats`, {
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取聊天列表失败')
}
return response.json()
}
/**
*
*/
export async function getExpressionList(params: {
page?: number
page_size?: number
search?: string
chat_id?: string
}): Promise<ExpressionListResponse> {
const queryParams = new URLSearchParams()
if (params.page) queryParams.append('page', params.page.toString())
if (params.page_size) queryParams.append('page_size', params.page_size.toString())
if (params.search) queryParams.append('search', params.search)
if (params.chat_id) queryParams.append('chat_id', params.chat_id)
const response = await fetchWithAuth(`${API_BASE}/list?${queryParams}`, {
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取表达方式列表失败')
}
return response.json()
}
/**
*
*/
export async function getExpressionDetail(expressionId: number): Promise<ExpressionDetailResponse> {
const response = await fetchWithAuth(`${API_BASE}/${expressionId}`, {
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取表达方式详情失败')
}
return response.json()
}
/**
*
*/
export async function createExpression(
data: ExpressionCreateRequest
): Promise<ExpressionCreateResponse> {
const response = await fetchWithAuth(`${API_BASE}/`, {
method: 'POST',
body: JSON.stringify(data),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '创建表达方式失败')
}
return response.json()
}
/**
*
*/
export async function updateExpression(
expressionId: number,
data: ExpressionUpdateRequest
): Promise<ExpressionUpdateResponse> {
const response = await fetchWithAuth(`${API_BASE}/${expressionId}`, {
method: 'PATCH',
body: JSON.stringify(data),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '更新表达方式失败')
}
return response.json()
}
/**
*
*/
export async function deleteExpression(expressionId: number): Promise<ExpressionDeleteResponse> {
const response = await fetchWithAuth(`${API_BASE}/${expressionId}`, {
method: 'DELETE',
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '删除表达方式失败')
}
return response.json()
}
/**
*
*/
export async function batchDeleteExpressions(expressionIds: number[]): Promise<ExpressionDeleteResponse> {
const response = await fetchWithAuth(`${API_BASE}/batch/delete`, {
method: 'POST',
body: JSON.stringify({ ids: expressionIds }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '批量删除表达方式失败')
}
return response.json()
}
/**
*
*/
export async function getExpressionStats(): Promise<ExpressionStatsResponse> {
const response = await fetchWithAuth(`${API_BASE}/stats/summary`, {
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取统计数据失败')
}
return response.json()
}
// ============ 审核相关 API ============
/**
*
*/
export async function getReviewStats(): Promise<ReviewStats> {
const response = await fetchWithAuth(`${API_BASE}/review/stats`)
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取审核统计失败')
}
return response.json()
}
/**
*
*/
export async function getReviewList(params: {
page?: number
page_size?: number
filter_type?: 'unchecked' | 'passed' | 'rejected' | 'all'
search?: string
chat_id?: string
}): Promise<ReviewListResponse> {
const queryParams = new URLSearchParams()
if (params.page) queryParams.append('page', params.page.toString())
if (params.page_size) queryParams.append('page_size', params.page_size.toString())
if (params.filter_type) queryParams.append('filter_type', params.filter_type)
if (params.search) queryParams.append('search', params.search)
if (params.chat_id) queryParams.append('chat_id', params.chat_id)
const response = await fetchWithAuth(`${API_BASE}/review/list?${queryParams}`)
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取审核列表失败')
}
return response.json()
}
/**
*
*/
export async function batchReviewExpressions(
items: BatchReviewItem[]
): Promise<BatchReviewResponse> {
const response = await fetchWithAuth(`${API_BASE}/review/batch`, {
method: 'POST',
body: JSON.stringify({ items }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '批量审核失败')
}
return response.json()
}

View File

@ -0,0 +1,82 @@
// 带自动认证处理的 fetch 封装
/**
* fetch 401
* 使 HttpOnly Cookie credentials
*
* FormData Content-Type multipart/form-data
*/
export async function fetchWithAuth(
input: RequestInfo | URL,
init?: RequestInit
): Promise<Response> {
// 检查是否是 FormData 请求
const isFormData = init?.body instanceof FormData
// 构建 headers对于 FormData 不设置 Content-Type
const headers: HeadersInit = isFormData
? { ...init?.headers }
: { 'Content-Type': 'application/json', ...init?.headers }
// 合并默认配置,确保携带 Cookie
const config: RequestInit = {
...init,
credentials: 'include', // 确保携带 Cookie
headers,
}
const response = await fetch(input, config)
// 检测 401 未授权错误
if (response.status === 401) {
// 跳转到登录页
window.location.href = '/auth'
// 抛出错误以便调用者可以处理
throw new Error('认证失败,请重新登录')
}
return response
}
/**
*
* 使 Cookie Authorization header
*/
export function getAuthHeaders(): HeadersInit {
return {
'Content-Type': 'application/json',
}
}
/**
*
*/
export async function logout(): Promise<void> {
try {
await fetch('/api/webui/auth/logout', {
method: 'POST',
credentials: 'include',
})
} catch (error) {
console.error('登出请求失败:', error)
}
// 无论成功与否都跳转到登录页
window.location.href = '/auth'
}
/**
*
*/
export async function checkAuthStatus(): Promise<boolean> {
try {
const response = await fetch('/api/webui/auth/check', {
method: 'GET',
credentials: 'include',
})
const data = await response.json()
return data.authenticated === true
} catch {
return false
}
}

View File

@ -0,0 +1,99 @@
import type { ReactNode } from 'react'
/**
* Hook type for field-level customization
*/
export type FieldHookType = 'replace' | 'wrapper'
/**
* Props passed to a FieldHookComponent
*/
export interface FieldHookComponentProps {
fieldPath: string
value: unknown
onChange?: (value: unknown) => void
children?: ReactNode
}
/**
* A React component that can be registered as a field hook
*/
export type FieldHookComponent = React.FC<FieldHookComponentProps>
/**
* Registry entry for a field hook
*/
interface FieldHookEntry {
component: FieldHookComponent
type: FieldHookType
}
/**
* Registry for managing field-level hooks
* Supports two types of hooks:
* - replace: Completely replaces the default field renderer
* - wrapper: Wraps the default field renderer with additional functionality
*/
export class FieldHookRegistry {
private hooks: Map<string, FieldHookEntry> = new Map()
/**
* Register a hook for a specific field path
* @param fieldPath The field path (e.g., 'chat.talk_value')
* @param component The React component to register
* @param type The hook type ('replace' or 'wrapper')
*/
register(
fieldPath: string,
component: FieldHookComponent,
type: FieldHookType = 'replace'
): void {
this.hooks.set(fieldPath, { component, type })
}
/**
* Get a registered hook for a specific field path
* @param fieldPath The field path to look up
* @returns The hook entry if found, undefined otherwise
*/
get(fieldPath: string): FieldHookEntry | undefined {
return this.hooks.get(fieldPath)
}
/**
* Check if a hook is registered for a specific field path
* @param fieldPath The field path to check
* @returns True if a hook is registered, false otherwise
*/
has(fieldPath: string): boolean {
return this.hooks.has(fieldPath)
}
/**
* Unregister a hook for a specific field path
* @param fieldPath The field path to unregister
*/
unregister(fieldPath: string): void {
this.hooks.delete(fieldPath)
}
/**
* Clear all registered hooks
*/
clear(): void {
this.hooks.clear()
}
/**
* Get all registered field paths
* @returns Array of registered field paths
*/
getAllPaths(): string[] {
return Array.from(this.hooks.keys())
}
}
/**
* Singleton instance of the field hook registry
*/
export const fieldHooks = new FieldHookRegistry()

View File

@ -0,0 +1,188 @@
/**
* API
*/
import { fetchWithAuth } from '@/lib/fetch-with-auth'
import type {
JargonListResponse,
JargonDetailResponse,
JargonCreateRequest,
JargonCreateResponse,
JargonUpdateRequest,
JargonUpdateResponse,
JargonDeleteResponse,
JargonStatsResponse,
JargonChatListResponse,
} from '@/types/jargon'
const API_BASE = '/api/webui/jargon'
/**
*
*/
export async function getJargonChatList(): Promise<JargonChatListResponse> {
const response = await fetchWithAuth(`${API_BASE}/chats`, {})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取聊天列表失败')
}
return response.json()
}
/**
*
*/
export async function getJargonList(params: {
page?: number
page_size?: number
search?: string
chat_id?: string
is_jargon?: boolean | null
is_global?: boolean
}): Promise<JargonListResponse> {
const queryParams = new URLSearchParams()
if (params.page) queryParams.append('page', params.page.toString())
if (params.page_size) queryParams.append('page_size', params.page_size.toString())
if (params.search) queryParams.append('search', params.search)
if (params.chat_id) queryParams.append('chat_id', params.chat_id)
if (params.is_jargon !== undefined && params.is_jargon !== null) {
queryParams.append('is_jargon', params.is_jargon.toString())
}
if (params.is_global !== undefined) {
queryParams.append('is_global', params.is_global.toString())
}
const response = await fetchWithAuth(`${API_BASE}/list?${queryParams}`, {})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取黑话列表失败')
}
return response.json()
}
/**
*
*/
export async function getJargonDetail(jargonId: number): Promise<JargonDetailResponse> {
const response = await fetchWithAuth(`${API_BASE}/${jargonId}`, {})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取黑话详情失败')
}
return response.json()
}
/**
*
*/
export async function createJargon(
data: JargonCreateRequest
): Promise<JargonCreateResponse> {
const response = await fetchWithAuth(`${API_BASE}/`, {
method: 'POST',
body: JSON.stringify(data),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '创建黑话失败')
}
return response.json()
}
/**
*
*/
export async function updateJargon(
jargonId: number,
data: JargonUpdateRequest
): Promise<JargonUpdateResponse> {
const response = await fetchWithAuth(`${API_BASE}/${jargonId}`, {
method: 'PATCH',
body: JSON.stringify(data),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '更新黑话失败')
}
return response.json()
}
/**
*
*/
export async function deleteJargon(jargonId: number): Promise<JargonDeleteResponse> {
const response = await fetchWithAuth(`${API_BASE}/${jargonId}`, {
method: 'DELETE',
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '删除黑话失败')
}
return response.json()
}
/**
*
*/
export async function batchDeleteJargons(jargonIds: number[]): Promise<JargonDeleteResponse> {
const response = await fetchWithAuth(`${API_BASE}/batch/delete`, {
method: 'POST',
body: JSON.stringify({ ids: jargonIds }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '批量删除黑话失败')
}
return response.json()
}
/**
*
*/
export async function getJargonStats(): Promise<JargonStatsResponse> {
const response = await fetchWithAuth(`${API_BASE}/stats/summary`, {})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取黑话统计失败')
}
return response.json()
}
/**
*
*/
export async function batchSetJargonStatus(
jargonIds: number[],
isJargon: boolean
): Promise<JargonUpdateResponse> {
const queryParams = new URLSearchParams()
jargonIds.forEach(id => queryParams.append('ids', id.toString()))
queryParams.append('is_jargon', isJargon.toString())
const response = await fetchWithAuth(`${API_BASE}/batch/set-jargon?${queryParams}`, {
method: 'POST',
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '批量设置黑话状态失败')
}
return response.json()
}

View File

@ -0,0 +1,69 @@
/**
* API
*/
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api/webui'
export interface KnowledgeNode {
id: string
type: 'entity' | 'paragraph'
content: string
create_time?: number
}
export interface KnowledgeEdge {
source: string
target: string
weight: number
create_time?: number
update_time?: number
}
export interface KnowledgeGraph {
nodes: KnowledgeNode[]
edges: KnowledgeEdge[]
}
export interface KnowledgeStats {
total_nodes: number
total_edges: number
entity_nodes: number
paragraph_nodes: number
}
/**
*
*/
export async function getKnowledgeGraph(limit: number = 100, nodeType: 'all' | 'entity' | 'paragraph' = 'all'): Promise<KnowledgeGraph> {
const url = `${API_BASE_URL}/knowledge/graph?limit=${limit}&node_type=${nodeType}`
const response = await fetch(url)
if (!response.ok) {
throw new Error(`获取知识图谱失败: ${response.status}`)
}
return response.json()
}
/**
*
*/
export async function getKnowledgeStats(): Promise<KnowledgeStats> {
const response = await fetch(`${API_BASE_URL}/knowledge/stats`)
if (!response.ok) {
throw new Error('获取知识图谱统计信息失败')
}
return response.json()
}
/**
*
*/
export async function searchKnowledgeNode(query: string): Promise<KnowledgeNode[]> {
const response = await fetch(`${API_BASE_URL}/knowledge/search?query=${encodeURIComponent(query)}`)
if (!response.ok) {
throw new Error('搜索知识节点失败')
}
return response.json()
}

View File

@ -0,0 +1,326 @@
/**
* WebSocket
* WebSocket
*/
import { fetchWithAuth, checkAuthStatus } from './fetch-with-auth'
import { getSetting } from './settings-manager'
export interface LogEntry {
id: string
timestamp: string
level: 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR' | 'CRITICAL'
module: string
message: string
}
type LogCallback = (log: LogEntry) => void
type ConnectionCallback = (connected: boolean) => void
class LogWebSocketManager {
private ws: WebSocket | null = null
private reconnectTimeout: number | null = null
private reconnectAttempts = 0
private heartbeatInterval: number | null = null
// 订阅者
private logCallbacks: Set<LogCallback> = new Set()
private connectionCallbacks: Set<ConnectionCallback> = new Set()
private isConnected = false
// 日志缓存 - 保存所有接收到的日志
private logCache: LogEntry[] = []
/**
*
*/
private getMaxCacheSize(): number {
return getSetting('logCacheSize')
}
/**
*
*/
private getMaxReconnectAttempts(): number {
return getSetting('wsMaxReconnectAttempts')
}
/**
*
*/
private getReconnectInterval(): number {
return getSetting('wsReconnectInterval')
}
/**
* WebSocket URL
*/
private getWebSocketUrl(token?: string): string {
let baseUrl: string
if (import.meta.env.DEV) {
// 开发模式:连接到 WebUI 后端服务器
baseUrl = 'ws://127.0.0.1:8001/ws/logs'
} else {
// 生产模式:使用当前页面的 host
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
const host = window.location.host
baseUrl = `${protocol}//${host}/ws/logs`
}
// 如果有 token添加到 URL 参数
if (token) {
return `${baseUrl}?token=${encodeURIComponent(token)}`
}
return baseUrl
}
/**
* WebSocket token
*/
private async getWsToken(): Promise<string | null> {
try {
// 使用相对路径,让前端代理处理请求,避免 CORS 问题
const response = await fetchWithAuth('/api/webui/ws-token', {
method: 'GET',
credentials: 'include', // 携带 Cookie
})
if (!response.ok) {
console.error('获取 WebSocket token 失败:', response.status)
return null
}
const data = await response.json()
if (data.success && data.token) {
return data.token
}
return null
} catch (error) {
console.error('获取 WebSocket token 失败:', error)
return null
}
}
/**
* WebSocket
*/
async connect() {
if (this.ws?.readyState === WebSocket.OPEN || this.ws?.readyState === WebSocket.CONNECTING) {
return
}
// 检查是否在登录页面
if (window.location.pathname === '/auth') {
console.log('📡 在登录页面,跳过 WebSocket 连接')
return
}
// 检查登录状态,避免未登录时尝试连接
const isAuthenticated = await checkAuthStatus()
if (!isAuthenticated) {
console.log('📡 未登录,跳过 WebSocket 连接')
return
}
// 先获取临时认证 token
const wsToken = await this.getWsToken()
if (!wsToken) {
console.log('📡 无法获取 WebSocket token跳过连接')
return
}
const wsUrl = this.getWebSocketUrl(wsToken)
try {
this.ws = new WebSocket(wsUrl)
this.ws.onopen = () => {
this.isConnected = true
this.reconnectAttempts = 0
this.notifyConnection(true)
this.startHeartbeat()
}
this.ws.onmessage = (event) => {
try {
// 忽略心跳响应
if (event.data === 'pong') {
return
}
const log: LogEntry = JSON.parse(event.data)
this.notifyLog(log)
} catch (error) {
console.error('解析日志消息失败:', error)
}
}
this.ws.onerror = (error) => {
console.error('❌ WebSocket 错误:', error)
this.isConnected = false
this.notifyConnection(false)
}
this.ws.onclose = () => {
this.isConnected = false
this.notifyConnection(false)
this.stopHeartbeat()
this.attemptReconnect()
}
} catch (error) {
console.error('创建 WebSocket 连接失败:', error)
this.attemptReconnect()
}
}
/**
*
*/
private attemptReconnect() {
const maxAttempts = this.getMaxReconnectAttempts()
if (this.reconnectAttempts >= maxAttempts) {
return
}
this.reconnectAttempts += 1
const baseInterval = this.getReconnectInterval()
const delay = Math.min(baseInterval * this.reconnectAttempts, 30000)
this.reconnectTimeout = window.setTimeout(() => {
this.connect() // connect 是 async 但这里不需要 await它内部会处理错误
}, delay)
}
/**
*
*/
private startHeartbeat() {
this.heartbeatInterval = window.setInterval(() => {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send('ping')
}
}, 30000) // 每30秒发送一次心跳
}
/**
*
*/
private stopHeartbeat() {
if (this.heartbeatInterval !== null) {
clearInterval(this.heartbeatInterval)
this.heartbeatInterval = null
}
}
/**
*
*/
disconnect() {
if (this.reconnectTimeout !== null) {
clearTimeout(this.reconnectTimeout)
this.reconnectTimeout = null
}
this.stopHeartbeat()
if (this.ws) {
this.ws.close()
this.ws = null
}
this.isConnected = false
this.reconnectAttempts = 0
}
/**
*
*/
onLog(callback: LogCallback) {
this.logCallbacks.add(callback)
return () => this.logCallbacks.delete(callback)
}
/**
*
*/
onConnectionChange(callback: ConnectionCallback) {
this.connectionCallbacks.add(callback)
// 立即通知当前状态
callback(this.isConnected)
return () => this.connectionCallbacks.delete(callback)
}
/**
*
*/
private notifyLog(log: LogEntry) {
// 检查是否已存在(通过 id 去重)
const exists = this.logCache.some(existingLog => existingLog.id === log.id)
if (!exists) {
// 添加到缓存
this.logCache.push(log)
// 限制缓存大小(动态读取配置)
const maxCacheSize = this.getMaxCacheSize()
if (this.logCache.length > maxCacheSize) {
this.logCache = this.logCache.slice(-maxCacheSize)
}
// 只有新日志才通知订阅者
this.logCallbacks.forEach(callback => {
try {
callback(log)
} catch (error) {
console.error('日志回调执行失败:', error)
}
})
}
}
/**
*
*/
private notifyConnection(connected: boolean) {
this.connectionCallbacks.forEach(callback => {
try {
callback(connected)
} catch (error) {
console.error('连接状态回调执行失败:', error)
}
})
}
/**
*
*/
getAllLogs(): LogEntry[] {
return [...this.logCache]
}
/**
*
*/
clearLogs() {
this.logCache = []
}
/**
*
*/
getConnectionStatus(): boolean {
return this.isConnected
}
}
// 导出单例
export const logWebSocket = new LogWebSocketManager()
// 自动连接(应用启动时)
if (typeof window !== 'undefined') {
// 延迟一下确保页面加载完成
setTimeout(() => {
logWebSocket.connect()
}, 100)
}

View File

@ -0,0 +1,570 @@
/**
* Pack API
*
* Cloudflare Workers Pack
*/
import { fetchWithAuth } from './fetch-with-auth'
// ============ 类型定义 ============
/**
* api_key
*/
export interface PackProvider {
name: string
base_url: string
client_type: 'openai' | 'gemini'
max_retry?: number
timeout?: number
retry_interval?: number
}
/**
*
*/
export interface PackModel {
model_identifier: string
name: string
api_provider: string
price_in: number
price_out: number
temperature?: number
max_tokens?: number
force_stream_mode?: boolean
extra_params?: Record<string, unknown>
}
/**
*
*/
export interface PackTaskConfig {
model_list: string[]
temperature?: number
max_tokens?: number
slow_threshold?: number
}
/**
*
*/
export interface PackTaskConfigs {
utils?: PackTaskConfig
utils_small?: PackTaskConfig
tool_use?: PackTaskConfig
replyer?: PackTaskConfig
planner?: PackTaskConfig
vlm?: PackTaskConfig
voice?: PackTaskConfig
embedding?: PackTaskConfig
lpmm_entity_extract?: PackTaskConfig
lpmm_rdf_build?: PackTaskConfig
lpmm_qa?: PackTaskConfig
}
/**
* Pack
*/
export interface PackListItem {
id: string
name: string
description: string
author: string
version: string
created_at: string
updated_at: string
status: 'pending' | 'approved' | 'rejected'
reject_reason?: string
downloads: number
likes: number
tags?: string[]
provider_count: number
model_count: number
task_count: number
}
/**
* Pack
*/
export interface ModelPack extends Omit<PackListItem, 'provider_count' | 'model_count' | 'task_count'> {
providers: PackProvider[]
models: PackModel[]
task_config: PackTaskConfigs
}
/**
* Pack
*/
export interface ListPacksResponse {
packs: PackListItem[]
total: number
page: number
page_size: number
total_pages: number
}
/**
* Pack
*/
export interface ApplyPackOptions {
apply_providers: boolean
apply_models: boolean
apply_task_config: boolean
task_mode: 'replace' | 'append'
selected_providers?: string[]
selected_models?: string[]
selected_tasks?: string[]
}
/**
* Pack
*/
export interface ApplyPackConflicts {
existing_providers: Array<{
pack_provider: PackProvider
local_providers: Array<{ // 改为数组,支持多个匹配
name: string
base_url: string
}>
}>
new_providers: PackProvider[]
conflicting_models: Array<{
pack_model: string
local_model: string
}>
}
// ============ API 配置 ============
// Pack 服务基础 URLCloudflare Workers
const PACK_SERVICE_URL = 'https://maibot-plugin-stats.maibot-webui.workers.dev'
// ============ API 函数 ============
/**
* Pack
*/
export async function listPacks(params?: {
status?: 'pending' | 'approved' | 'rejected' | 'all'
page?: number
page_size?: number
search?: string
sort_by?: 'created_at' | 'downloads' | 'likes'
sort_order?: 'asc' | 'desc'
}): Promise<ListPacksResponse> {
const searchParams = new URLSearchParams()
if (params?.status) searchParams.set('status', params.status)
if (params?.page) searchParams.set('page', params.page.toString())
if (params?.page_size) searchParams.set('page_size', params.page_size.toString())
if (params?.search) searchParams.set('search', params.search)
if (params?.sort_by) searchParams.set('sort_by', params.sort_by)
if (params?.sort_order) searchParams.set('sort_order', params.sort_order)
const response = await fetch(`${PACK_SERVICE_URL}/pack?${searchParams.toString()}`)
if (!response.ok) {
throw new Error(`获取 Pack 列表失败: ${response.status}`)
}
return response.json()
}
/**
* Pack
*/
export async function getPack(packId: string): Promise<ModelPack> {
const response = await fetch(`${PACK_SERVICE_URL}/pack/${packId}`)
if (!response.ok) {
throw new Error(`获取 Pack 失败: ${response.status}`)
}
const data = await response.json()
if (!data.success) {
throw new Error(data.error || '获取 Pack 失败')
}
return data.pack
}
/**
* Pack
*/
export async function createPack(pack: {
name: string
description: string
author: string
tags?: string[]
providers: PackProvider[]
models: PackModel[]
task_config: PackTaskConfigs
}): Promise<{ pack_id: string; message: string }> {
const response = await fetch(`${PACK_SERVICE_URL}/pack`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(pack),
})
const data = await response.json()
if (!data.success) {
throw new Error(data.error || '创建 Pack 失败')
}
return data
}
/**
* Pack
*/
export async function recordPackDownload(packId: string, userId?: string): Promise<void> {
await fetch(`${PACK_SERVICE_URL}/pack/download`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pack_id: packId, user_id: userId }),
})
}
/**
* / Pack
*/
export async function togglePackLike(packId: string, userId: string): Promise<{ likes: number; liked: boolean }> {
const response = await fetch(`${PACK_SERVICE_URL}/pack/like`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pack_id: packId, user_id: userId }),
})
const data = await response.json()
if (!data.success) {
throw new Error(data.error || '点赞失败')
}
return { likes: data.likes, liked: data.liked }
}
/**
*
*/
export async function checkPackLike(packId: string, userId: string): Promise<boolean> {
const response = await fetch(
`${PACK_SERVICE_URL}/pack/like/check?pack_id=${packId}&user_id=${userId}`
)
const data = await response.json()
return data.liked || false
}
// ============ 本地应用 Pack 相关 ============
/**
* Pack
*/
export async function detectPackConflicts(
pack: ModelPack
): Promise<ApplyPackConflicts> {
// 获取当前配置
const response = await fetchWithAuth('/api/webui/config/model')
if (!response.ok) {
throw new Error('获取当前模型配置失败')
}
const responseData = await response.json()
const currentConfig = responseData.config || responseData
console.log('=== Pack Conflict Detection ===')
console.log('Pack providers:', pack.providers)
console.log('Local providers:', currentConfig.api_providers)
const conflicts: ApplyPackConflicts = {
existing_providers: [],
new_providers: [],
conflicting_models: [],
}
// 检测提供商冲突
const localProviders = currentConfig.api_providers || []
for (const packProvider of pack.providers) {
console.log(`\nChecking pack provider: ${packProvider.name}`)
console.log(` Pack URL: ${packProvider.base_url}`)
console.log(` Normalized: ${normalizeUrl(packProvider.base_url)}`)
// 按 URL 匹配 - 找出所有匹配的本地提供商
const matchedProviders = localProviders.filter(
(p: { base_url: string; name: string }) => {
const localNormalized = normalizeUrl(p.base_url)
const packNormalized = normalizeUrl(packProvider.base_url)
console.log(` Comparing with local "${p.name}": ${p.base_url}`)
console.log(` Local normalized: ${localNormalized}`)
console.log(` Match: ${localNormalized === packNormalized}`)
return localNormalized === packNormalized
}
)
if (matchedProviders.length > 0) {
console.log(` ✓ Matched with ${matchedProviders.length} local provider(s):`, matchedProviders.map((p: {name: string}) => p.name).join(', '))
conflicts.existing_providers.push({
pack_provider: packProvider,
local_providers: matchedProviders.map((p: { name: string; base_url: string }) => ({
name: p.name,
base_url: p.base_url,
})),
})
} else {
console.log(` ✗ No match found - will need API key`)
conflicts.new_providers.push(packProvider)
}
}
// 检测模型名称冲突
const localModels = currentConfig.models || []
console.log('\n=== Model Conflict Detection ===')
for (const packModel of pack.models) {
const conflictModel = localModels.find(
(m: { name: string }) => m.name === packModel.name
)
if (conflictModel) {
console.log(`Model conflict: ${packModel.name}`)
conflicts.conflicting_models.push({
pack_model: packModel.name,
local_model: conflictModel.name,
})
}
}
console.log('\n=== Detection Summary ===')
console.log(`Existing providers: ${conflicts.existing_providers.length}`)
console.log(`New providers: ${conflicts.new_providers.length}`)
console.log(`Conflicting models: ${conflicts.conflicting_models.length}`)
console.log('===========================\n')
return conflicts
}
/**
* Pack
*/
export async function applyPack(
pack: ModelPack,
options: ApplyPackOptions,
providerMapping: Record<string, string>, // pack_provider_name -> local_provider_name
newProviderApiKeys: Record<string, string>, // provider_name -> api_key
): Promise<void> {
// 获取当前配置
const response = await fetchWithAuth('/api/webui/config/model')
if (!response.ok) {
throw new Error('获取当前模型配置失败')
}
const responseData = await response.json()
const currentConfig = responseData.config || responseData
// 1. 处理提供商
if (options.apply_providers) {
const providersToApply = options.selected_providers
? pack.providers.filter(p => options.selected_providers!.includes(p.name))
: pack.providers
for (const packProvider of providersToApply) {
// 检查是否映射到已有提供商
if (providerMapping[packProvider.name]) {
// 使用已有提供商,不需要添加
continue
}
// 添加新提供商
const apiKey = newProviderApiKeys[packProvider.name]
if (!apiKey) {
throw new Error(`提供商 "${packProvider.name}" 缺少 API Key`)
}
const newProvider = {
...packProvider,
api_key: apiKey,
}
// 检查是否已存在同名提供商
const existingIndex = currentConfig.api_providers.findIndex(
(p: { name: string }) => p.name === packProvider.name
)
if (existingIndex >= 0) {
// 覆盖
currentConfig.api_providers[existingIndex] = newProvider
} else {
// 添加
currentConfig.api_providers.push(newProvider)
}
}
}
// 2. 处理模型
if (options.apply_models) {
const modelsToApply = options.selected_models
? pack.models.filter(m => options.selected_models!.includes(m.name))
: pack.models
for (const packModel of modelsToApply) {
// 映射提供商名称
const actualProvider = providerMapping[packModel.api_provider] || packModel.api_provider
const newModel = {
...packModel,
api_provider: actualProvider,
}
// 检查是否已存在同名模型
const existingIndex = currentConfig.models.findIndex(
(m: { name: string }) => m.name === packModel.name
)
if (existingIndex >= 0) {
// 覆盖
currentConfig.models[existingIndex] = newModel
} else {
// 添加
currentConfig.models.push(newModel)
}
}
}
// 3. 处理任务配置
if (options.apply_task_config) {
const taskKeys = options.selected_tasks || Object.keys(pack.task_config)
for (const taskKey of taskKeys) {
const packTaskConfig = pack.task_config[taskKey as keyof PackTaskConfigs]
if (!packTaskConfig) continue
// 映射模型名称(如果模型名称被跳过,则从任务列表中移除)
const appliedModelNames = new Set(
options.selected_models || pack.models.map(m => m.name)
)
const filteredModelList = packTaskConfig.model_list.filter(
name => appliedModelNames.has(name)
)
if (filteredModelList.length === 0) continue
const newTaskConfig = {
...packTaskConfig,
model_list: filteredModelList,
}
if (options.task_mode === 'replace') {
// 替换模式
currentConfig.model_task_config[taskKey] = newTaskConfig
} else {
// 追加模式
const existingConfig = currentConfig.model_task_config[taskKey]
if (existingConfig) {
// 合并模型列表(去重)
const mergedList = [...new Set([
...existingConfig.model_list,
...filteredModelList,
])]
currentConfig.model_task_config[taskKey] = {
...existingConfig,
model_list: mergedList,
}
} else {
currentConfig.model_task_config[taskKey] = newTaskConfig
}
}
}
}
// 保存配置
const saveResponse = await fetchWithAuth('/api/webui/config/model', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(currentConfig),
})
if (!saveResponse.ok) {
throw new Error('保存配置失败')
}
}
/**
* Pack
*/
export async function exportCurrentConfigAsPack(params: {
name: string
description: string
author: string
tags?: string[]
selectedProviders?: string[]
selectedModels?: string[]
selectedTasks?: string[]
}): Promise<{
providers: PackProvider[]
models: PackModel[]
task_config: PackTaskConfigs
}> {
// 获取当前配置
const response = await fetchWithAuth('/api/webui/config/model')
if (!response.ok) {
throw new Error('获取当前模型配置失败')
}
const responseData = await response.json()
// API 返回的格式是 { success: true, config: {...} }
if (!responseData.success || !responseData.config) {
throw new Error('获取配置失败')
}
const currentConfig = responseData.config
// 过滤提供商(移除 api_key
let providers: PackProvider[] = (currentConfig.api_providers || []).map(
(p: { name: string; base_url: string; client_type: string; max_retry?: number; timeout?: number; retry_interval?: number }) => ({
name: p.name,
base_url: p.base_url,
client_type: p.client_type,
max_retry: p.max_retry,
timeout: p.timeout,
retry_interval: p.retry_interval,
})
)
if (params.selectedProviders) {
providers = providers.filter(p => params.selectedProviders!.includes(p.name))
}
// 过滤模型
let models: PackModel[] = currentConfig.models || []
if (params.selectedModels) {
models = models.filter(m => params.selectedModels!.includes(m.name))
}
// 过滤任务配置
const task_config: PackTaskConfigs = {}
const allTasks = currentConfig.model_task_config || {}
const taskKeys = params.selectedTasks || Object.keys(allTasks)
for (const key of taskKeys) {
if (allTasks[key]) {
task_config[key as keyof PackTaskConfigs] = allTasks[key]
}
}
return { providers, models, task_config }
}
// ============ 辅助函数 ============
/**
* URL
*/
function normalizeUrl(url: string): string {
try {
const parsed = new URL(url)
// 移除末尾斜杠,统一小写
return `${parsed.protocol}//${parsed.host}${parsed.pathname}`.replace(/\/$/, '').toLowerCase()
} catch {
return url.toLowerCase().replace(/\/$/, '')
}
}
/**
* ID
*/
export function getPackUserId(): string {
const storageKey = 'maibot_pack_user_id'
let userId = localStorage.getItem(storageKey)
if (!userId) {
userId = 'pack_user_' + Math.random().toString(36).substring(2, 15)
localStorage.setItem(storageKey, userId)
}
return userId
}

View File

@ -0,0 +1,138 @@
/**
* API
*/
import { fetchWithAuth, getAuthHeaders } from '@/lib/fetch-with-auth'
import type {
PersonListResponse,
PersonDetailResponse,
PersonUpdateRequest,
PersonUpdateResponse,
PersonDeleteResponse,
PersonStatsResponse,
} from '@/types/person'
const API_BASE = '/api/webui/person'
/**
*
*/
export async function getPersonList(params: {
page?: number
page_size?: number
search?: string
is_known?: boolean
platform?: string
}): Promise<PersonListResponse> {
const queryParams = new URLSearchParams()
if (params.page) queryParams.append('page', params.page.toString())
if (params.page_size) queryParams.append('page_size', params.page_size.toString())
if (params.search) queryParams.append('search', params.search)
if (params.is_known !== undefined) queryParams.append('is_known', params.is_known.toString())
if (params.platform) queryParams.append('platform', params.platform)
const response = await fetchWithAuth(`${API_BASE}/list?${queryParams}`, {
headers: getAuthHeaders(),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取人物列表失败')
}
return response.json()
}
/**
*
*/
export async function getPersonDetail(personId: string): Promise<PersonDetailResponse> {
const response = await fetchWithAuth(`${API_BASE}/${personId}`, {
headers: getAuthHeaders(),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取人物详情失败')
}
return response.json()
}
/**
*
*/
export async function updatePerson(
personId: string,
data: PersonUpdateRequest
): Promise<PersonUpdateResponse> {
const response = await fetchWithAuth(`${API_BASE}/${personId}`, {
method: 'PATCH',
headers: getAuthHeaders(),
body: JSON.stringify(data),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '更新人物信息失败')
}
return response.json()
}
/**
*
*/
export async function deletePerson(personId: string): Promise<PersonDeleteResponse> {
const response = await fetchWithAuth(`${API_BASE}/${personId}`, {
method: 'DELETE',
headers: getAuthHeaders(),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '删除人物信息失败')
}
return response.json()
}
/**
*
*/
export async function getPersonStats(): Promise<PersonStatsResponse> {
const response = await fetchWithAuth(`${API_BASE}/stats/summary`, {
headers: getAuthHeaders(),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取统计数据失败')
}
return response.json()
}
/**
*
*/
export async function batchDeletePersons(personIds: string[]): Promise<{
success: boolean
message: string
deleted_count: number
failed_count: number
failed_ids: string[]
}> {
const response = await fetchWithAuth(`${API_BASE}/batch/delete`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({ person_ids: personIds }),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '批量删除失败')
}
return response.json()
}

View File

@ -0,0 +1,201 @@
import { fetchWithAuth } from './fetch-with-auth'
// ========== 新的优化接口 ==========
export interface ChatSummary {
chat_id: string
plan_count: number
latest_timestamp: number
latest_filename: string
}
export interface PlannerOverview {
total_chats: number
total_plans: number
chats: ChatSummary[]
}
export interface PlanLogSummary {
chat_id: string
timestamp: number
filename: string
action_count: number
action_types: string[] // 动作类型列表
total_plan_ms: number
llm_duration_ms: number
reasoning_preview: string
}
export interface PlanLogDetail {
type: string
chat_id: string
timestamp: number
prompt: string
reasoning: string
raw_output: string
actions: any[]
timing: {
prompt_build_ms: number
llm_duration_ms: number
total_plan_ms: number
loop_start_time: number
}
extra: any
}
export interface PaginatedChatLogs {
data: PlanLogSummary[]
total: number
page: number
page_size: number
chat_id: string
}
/**
* -
*/
export async function getPlannerOverview(): Promise<PlannerOverview> {
const response = await fetchWithAuth('/api/planner/overview')
return response.json()
}
/**
*
*/
export async function getChatLogs(chatId: string, page = 1, pageSize = 20, search?: string): Promise<PaginatedChatLogs> {
const params = new URLSearchParams({
page: page.toString(),
page_size: pageSize.toString()
})
if (search) {
params.append('search', search)
}
const response = await fetchWithAuth(`/api/planner/chat/${chatId}/logs?${params}`)
return response.json()
}
/**
* -
*/
export async function getLogDetail(chatId: string, filename: string): Promise<PlanLogDetail> {
const response = await fetchWithAuth(`/api/planner/log/${chatId}/${filename}`)
return response.json()
}
// ========== 兼容旧接口 ==========
export interface PlannerStats {
total_chats: number
total_plans: number
avg_plan_time_ms: number
avg_llm_time_ms: number
recent_plans: PlanLogSummary[]
}
export interface PaginatedPlanLogs {
data: PlanLogSummary[]
total: number
page: number
page_size: number
}
export async function getPlannerStats(): Promise<PlannerStats> {
const response = await fetchWithAuth('/api/planner/stats')
return response.json()
}
export async function getAllLogs(page = 1, pageSize = 20): Promise<PaginatedPlanLogs> {
const response = await fetchWithAuth(`/api/planner/all-logs?page=${page}&page_size=${pageSize}`)
return response.json()
}
export async function getChatList(): Promise<string[]> {
const response = await fetchWithAuth('/api/planner/chats')
return response.json()
}
// ========== 回复器接口 ==========
export interface ReplierChatSummary {
chat_id: string
reply_count: number
latest_timestamp: number
latest_filename: string
}
export interface ReplierOverview {
total_chats: number
total_replies: number
chats: ReplierChatSummary[]
}
export interface ReplyLogSummary {
chat_id: string
timestamp: number
filename: string
model: string
success: boolean
llm_ms: number
overall_ms: number
output_preview: string
}
export interface ReplyLogDetail {
type: string
chat_id: string
timestamp: number
prompt: string
output: string
processed_output: string[]
model: string
reasoning: string
think_level: number
timing: {
prompt_ms: number
overall_ms: number
timing_logs: string[]
llm_ms: number
almost_zero: string
}
error: string | null
success: boolean
}
export interface PaginatedReplyLogs {
data: ReplyLogSummary[]
total: number
page: number
page_size: number
chat_id: string
}
/**
* -
*/
export async function getReplierOverview(): Promise<ReplierOverview> {
const response = await fetchWithAuth('/api/replier/overview')
return response.json()
}
/**
*
*/
export async function getReplyChatLogs(chatId: string, page = 1, pageSize = 20, search?: string): Promise<PaginatedReplyLogs> {
const params = new URLSearchParams({
page: page.toString(),
page_size: pageSize.toString()
})
if (search) {
params.append('search', search)
}
const response = await fetchWithAuth(`/api/replier/chat/${chatId}/logs?${params}`)
return response.json()
}
/**
* -
*/
export async function getReplyLogDetail(chatId: string, filename: string): Promise<ReplyLogDetail> {
const response = await fetchWithAuth(`/api/replier/log/${chatId}/${filename}`)
return response.json()
}

View File

@ -0,0 +1,722 @@
import { fetchWithAuth, getAuthHeaders } from '@/lib/fetch-with-auth'
import type { PluginInfo } from '@/types/plugin'
/**
* Git
*/
export interface GitStatus {
installed: boolean
version?: string
path?: string
error?: string
}
/**
*
*/
export interface MaimaiVersion {
version: string
version_major: number
version_minor: number
version_patch: number
}
/**
*
*/
export interface InstalledPlugin {
id: string
manifest: {
manifest_version: number
name: string
version: string
description: string
author: {
name: string
url?: string
}
license: string
host_application: {
min_version: string
max_version?: string
}
homepage_url?: string
repository_url?: string
keywords?: string[]
categories?: string[]
[key: string]: unknown // 允许其他字段
}
path: string
}
/**
*
*/
export interface PluginLoadProgress {
operation: 'idle' | 'fetch' | 'install' | 'uninstall' | 'update'
stage: 'idle' | 'loading' | 'success' | 'error'
progress: number // 0-100
message: string
error?: string
plugin_id?: string
total_plugins: number
loaded_plugins: number
}
/**
*
*/
const PLUGIN_REPO_OWNER = 'Mai-with-u'
const PLUGIN_REPO_NAME = 'plugin-repo'
const PLUGIN_REPO_BRANCH = 'main'
const PLUGIN_DETAILS_FILE = 'plugin_details.json'
/**
* API
*/
interface PluginApiResponse {
id: string
manifest: {
manifest_version: number
name: string
version: string
description: string
author: {
name: string
url?: string
}
license: string
host_application: {
min_version: string
max_version?: string
}
homepage_url?: string
repository_url?: string
keywords: string[]
categories?: string[]
default_locale: string
locales_path?: string
}
// 可能还有其他字段,但我们不关心
[key: string]: unknown
}
/**
* CORS
*/
export async function fetchPluginList(): Promise<PluginInfo[]> {
try {
// 通过后端 API 获取 Raw 文件
const response = await fetchWithAuth('/api/webui/plugins/fetch-raw', {
method: 'POST',
body: JSON.stringify({
owner: PLUGIN_REPO_OWNER,
repo: PLUGIN_REPO_NAME,
branch: PLUGIN_REPO_BRANCH,
file_path: PLUGIN_DETAILS_FILE
})
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const result = await response.json()
// 检查后端返回的结果
if (!result.success || !result.data) {
throw new Error(result.error || '获取插件列表失败')
}
const data: PluginApiResponse[] = JSON.parse(result.data)
// 转换为 PluginInfo 格式,并过滤掉无效数据
const pluginList = data
.filter(item => {
// 验证必需字段
if (!item?.id || !item?.manifest) {
console.warn('跳过无效插件数据:', item)
return false
}
if (!item.manifest.name || !item.manifest.version) {
console.warn('跳过缺少必需字段的插件:', item.id)
return false
}
return true
})
.map((item) => ({
id: item.id,
manifest: {
manifest_version: item.manifest.manifest_version || 1,
name: item.manifest.name,
version: item.manifest.version,
description: item.manifest.description || '',
author: item.manifest.author || { name: 'Unknown' },
license: item.manifest.license || 'Unknown',
host_application: item.manifest.host_application || { min_version: '0.0.0' },
homepage_url: item.manifest.homepage_url,
repository_url: item.manifest.repository_url,
keywords: item.manifest.keywords || [],
categories: item.manifest.categories || [],
default_locale: item.manifest.default_locale || 'zh-CN',
locales_path: item.manifest.locales_path,
},
// 默认值,这些信息可能需要从其他 API 获取
downloads: 0,
rating: 0,
review_count: 0,
installed: false,
published_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
}))
return pluginList
} catch (error) {
console.error('Failed to fetch plugin list:', error)
throw error
}
}
/**
* Git
*/
export async function checkGitStatus(): Promise<GitStatus> {
try {
const response = await fetchWithAuth('/api/webui/plugins/git-status')
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
return await response.json()
} catch (error) {
console.error('Failed to check Git status:', error)
// 返回未安装状态
return {
installed: false,
error: '无法检测 Git 安装状态'
}
}
}
/**
*
*/
export async function getMaimaiVersion(): Promise<MaimaiVersion> {
try {
const response = await fetchWithAuth('/api/webui/plugins/version')
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
return await response.json()
} catch (error) {
console.error('Failed to get Maimai version:', error)
// 返回默认版本
return {
version: '0.0.0',
version_major: 0,
version_minor: 0,
version_patch: 0
}
}
}
/**
*
*
* @param pluginMinVersion
* @param pluginMaxVersion
* @param maimaiVersion
* @returns true false
*/
export function isPluginCompatible(
pluginMinVersion: string,
pluginMaxVersion: string | undefined,
maimaiVersion: MaimaiVersion
): boolean {
// 解析插件最小版本
const minParts = pluginMinVersion.split('.').map(p => parseInt(p) || 0)
const minMajor = minParts[0] || 0
const minMinor = minParts[1] || 0
const minPatch = minParts[2] || 0
// 检查最小版本
if (maimaiVersion.version_major < minMajor) return false
if (maimaiVersion.version_major === minMajor && maimaiVersion.version_minor < minMinor) return false
if (maimaiVersion.version_major === minMajor &&
maimaiVersion.version_minor === minMinor &&
maimaiVersion.version_patch < minPatch) return false
// 检查最大版本(如果有)
if (pluginMaxVersion) {
const maxParts = pluginMaxVersion.split('.').map(p => parseInt(p) || 0)
const maxMajor = maxParts[0] || 0
const maxMinor = maxParts[1] || 0
const maxPatch = maxParts[2] || 0
if (maimaiVersion.version_major > maxMajor) return false
if (maimaiVersion.version_major === maxMajor && maimaiVersion.version_minor > maxMinor) return false
if (maimaiVersion.version_major === maxMajor &&
maimaiVersion.version_minor === maxMinor &&
maimaiVersion.version_patch > maxPatch) return false
}
return true
}
/**
* WebSocket token
*/
async function getWsToken(): Promise<string | null> {
try {
const response = await fetchWithAuth('/api/webui/ws-token')
if (!response.ok) {
console.error('获取 WebSocket token 失败:', response.status)
return null
}
const data = await response.json()
if (data.success && data.token) {
return data.token
}
return null
} catch (error) {
console.error('获取 WebSocket token 失败:', error)
return null
}
}
/**
* WebSocket
*
* 使 token token
*/
export async function connectPluginProgressWebSocket(
onProgress: (progress: PluginLoadProgress) => void,
onError?: (error: Event) => void
): Promise<WebSocket | null> {
// 先获取临时 token
const wsToken = await getWsToken()
if (!wsToken) {
console.warn('无法获取 WebSocket token可能未登录')
return null
}
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
const host = window.location.host
const wsUrl = `${protocol}//${host}/api/webui/ws/plugin-progress?token=${encodeURIComponent(wsToken)}`
try {
const ws = new WebSocket(wsUrl)
ws.onopen = () => {
console.log('Plugin progress WebSocket connected')
// 发送心跳
const heartbeat = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send('ping')
} else {
clearInterval(heartbeat)
}
}, 30000)
}
ws.onmessage = (event) => {
try {
// 忽略心跳响应
if (event.data === 'pong') {
return
}
const data = JSON.parse(event.data) as PluginLoadProgress
onProgress(data)
} catch (error) {
console.error('Failed to parse progress data:', error)
}
}
ws.onerror = (error) => {
console.error('Plugin progress WebSocket error:', error)
onError?.(error)
}
ws.onclose = () => {
console.log('Plugin progress WebSocket disconnected')
}
return ws
} catch (error) {
console.error('创建 WebSocket 连接失败:', error)
return null
}
}
/**
*
*/
export async function getInstalledPlugins(): Promise<InstalledPlugin[]> {
try {
const response = await fetchWithAuth('/api/webui/plugins/installed', {
headers: getAuthHeaders()
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const result = await response.json()
if (!result.success) {
throw new Error(result.message || '获取已安装插件列表失败')
}
return result.plugins || []
} catch (error) {
console.error('Failed to get installed plugins:', error)
return []
}
}
/**
*
*/
export function checkPluginInstalled(pluginId: string, installedPlugins: InstalledPlugin[]): boolean {
return installedPlugins.some(p => p.id === pluginId)
}
/**
*
*/
export function getInstalledPluginVersion(pluginId: string, installedPlugins: InstalledPlugin[]): string | undefined {
const plugin = installedPlugins.find(p => p.id === pluginId)
if (!plugin) return undefined
// 兼容两种格式:新格式有 manifest旧格式直接有 version
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return plugin.manifest?.version || (plugin as any).version
}
/**
*
*/
export async function installPlugin(pluginId: string, repositoryUrl: string, branch: string = 'main'): Promise<{ success: boolean; message: string }> {
const response = await fetchWithAuth('/api/webui/plugins/install', {
method: 'POST',
body: JSON.stringify({
plugin_id: pluginId,
repository_url: repositoryUrl,
branch: branch
})
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '安装失败')
}
return await response.json()
}
/**
*
*/
export async function uninstallPlugin(pluginId: string): Promise<{ success: boolean; message: string }> {
const response = await fetchWithAuth('/api/webui/plugins/uninstall', {
method: 'POST',
body: JSON.stringify({
plugin_id: pluginId
})
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '卸载失败')
}
return await response.json()
}
/**
*
*/
export async function updatePlugin(pluginId: string, repositoryUrl: string, branch: string = 'main'): Promise<{ success: boolean; message: string; old_version: string; new_version: string }> {
const response = await fetchWithAuth('/api/webui/plugins/update', {
method: 'POST',
body: JSON.stringify({
plugin_id: pluginId,
repository_url: repositoryUrl,
branch: branch
})
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '更新失败')
}
return await response.json()
}
// ============ 插件配置管理 ============
/**
* object
*/
export interface ItemFieldDefinition {
type: string
label?: string
placeholder?: string
default?: unknown
}
/**
*
*/
export interface ConfigFieldSchema {
name: string
type: string
default: unknown
description: string
example?: string
required: boolean
choices?: unknown[]
min?: number
max?: number
step?: number
pattern?: string
max_length?: number
label: string
placeholder?: string
hint?: string
icon?: string
hidden: boolean
disabled: boolean
order: number
input_type?: string
ui_type: string
rows?: number
group?: string
depends_on?: string
depends_value?: unknown
// 列表类型专用
item_type?: string // "string" | "number" | "object"
item_fields?: Record<string, ItemFieldDefinition>
min_items?: number
max_items?: number
}
/**
*
*/
export interface ConfigSectionSchema {
name: string
title: string
description?: string
icon?: string
collapsed: boolean
order: number
fields: Record<string, ConfigFieldSchema>
}
/**
*
*/
export interface ConfigTabSchema {
id: string
title: string
sections: string[]
icon?: string
order: number
badge?: string
}
/**
*
*/
export interface ConfigLayoutSchema {
type: 'auto' | 'tabs' | 'pages'
tabs: ConfigTabSchema[]
}
/**
* Schema
*/
export interface PluginConfigSchema {
plugin_id: string
plugin_info: {
name: string
version: string
description: string
author: string
}
sections: Record<string, ConfigSectionSchema>
layout: ConfigLayoutSchema
_note?: string
}
/**
* Schema
*/
export async function getPluginConfigSchema(pluginId: string): Promise<PluginConfigSchema> {
const response = await fetchWithAuth(`/api/webui/plugins/config/${pluginId}/schema`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const text = await response.text()
try {
const error = JSON.parse(text)
throw new Error(error.detail || '获取配置 Schema 失败')
} catch {
throw new Error(`获取配置 Schema 失败 (${response.status})`)
}
}
const result = await response.json()
if (!result.success) {
throw new Error(result.message || '获取配置 Schema 失败')
}
return result.schema
}
/**
*
*/
export async function getPluginConfig(pluginId: string): Promise<Record<string, unknown>> {
const response = await fetchWithAuth(`/api/webui/plugins/config/${pluginId}`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const text = await response.text()
try {
const error = JSON.parse(text)
throw new Error(error.detail || '获取配置失败')
} catch {
throw new Error(`获取配置失败 (${response.status})`)
}
}
const result = await response.json()
if (!result.success) {
throw new Error(result.message || '获取配置失败')
}
return result.config
}
/**
* TOML
*/
export async function getPluginConfigRaw(pluginId: string): Promise<string> {
const response = await fetchWithAuth(`/api/webui/plugins/config/${pluginId}/raw`, {
headers: getAuthHeaders()
})
if (!response.ok) {
const text = await response.text()
try {
const error = JSON.parse(text)
throw new Error(error.detail || '获取配置失败')
} catch {
throw new Error(`获取配置失败 (${response.status})`)
}
}
const result = await response.json()
if (!result.success) {
throw new Error(result.message || '获取配置失败')
}
return result.config
}
/**
*
*/
export async function updatePluginConfig(
pluginId: string,
config: Record<string, unknown>
): Promise<{ success: boolean; message: string; note?: string }> {
const response = await fetchWithAuth(`/api/webui/plugins/config/${pluginId}`, {
method: 'PUT',
headers: getAuthHeaders(),
body: JSON.stringify({ config })
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '保存配置失败')
}
return await response.json()
}
/**
* TOML
*/
export async function updatePluginConfigRaw(
pluginId: string,
configToml: string
): Promise<{ success: boolean; message: string; note?: string }> {
const response = await fetchWithAuth(`/api/webui/plugins/config/${pluginId}/raw`, {
method: 'PUT',
headers: getAuthHeaders(),
body: JSON.stringify({ config: configToml })
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '保存配置失败')
}
return await response.json()
}
/**
*
*/
export async function resetPluginConfig(
pluginId: string
): Promise<{ success: boolean; message: string; backup?: string }> {
const response = await fetchWithAuth(`/api/webui/plugins/config/${pluginId}/reset`, {
method: 'POST',
headers: getAuthHeaders()
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '重置配置失败')
}
return await response.json()
}
/**
*
*/
export async function togglePlugin(
pluginId: string
): Promise<{ success: boolean; enabled: boolean; message: string; note?: string }> {
const response = await fetchWithAuth(`/api/webui/plugins/config/${pluginId}/toggle`, {
method: 'POST',
headers: getAuthHeaders()
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '切换状态失败')
}
return await response.json()
}

View File

@ -0,0 +1,244 @@
/**
* API
* Cloudflare Workers
*/
// 配置统计服务 API 地址(所有用户共享的云端统计服务)
const STATS_API_BASE_URL = 'https://maibot-plugin-stats.maibot-webui.workers.dev'
export interface PluginStatsData {
plugin_id: string
likes: number
dislikes: number
downloads: number
rating: number
rating_count: number
recent_ratings?: Array<{
user_id: string
rating: number
comment?: string
created_at: string
}>
}
export interface StatsResponse {
success: boolean
error?: string
remaining?: number
[key: string]: unknown
}
/**
*
*/
export async function getPluginStats(pluginId: string): Promise<PluginStatsData | null> {
try {
const response = await fetch(`${STATS_API_BASE_URL}/stats/${pluginId}`)
if (!response.ok) {
console.error('Failed to fetch plugin stats:', response.statusText)
return null
}
return await response.json()
} catch (error) {
console.error('Error fetching plugin stats:', error)
return null
}
}
/**
*
*/
export async function likePlugin(pluginId: string, userId?: string): Promise<StatsResponse> {
try {
const finalUserId = userId || getUserId()
const response = await fetch(`${STATS_API_BASE_URL}/stats/like`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ plugin_id: pluginId, user_id: finalUserId }),
})
const data = await response.json()
if (response.status === 429) {
return { success: false, error: '操作过于频繁,请稍后再试' }
}
if (!response.ok) {
return { success: false, error: data.error || '点赞失败' }
}
return { success: true, ...data }
} catch (error) {
console.error('Error liking plugin:', error)
return { success: false, error: '网络错误' }
}
}
/**
*
*/
export async function dislikePlugin(pluginId: string, userId?: string): Promise<StatsResponse> {
try {
const finalUserId = userId || getUserId()
const response = await fetch(`${STATS_API_BASE_URL}/stats/dislike`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ plugin_id: pluginId, user_id: finalUserId }),
})
const data = await response.json()
if (response.status === 429) {
return { success: false, error: '操作过于频繁,请稍后再试' }
}
if (!response.ok) {
return { success: false, error: data.error || '点踩失败' }
}
return { success: true, ...data }
} catch (error) {
console.error('Error disliking plugin:', error)
return { success: false, error: '网络错误' }
}
}
/**
*
*/
export async function ratePlugin(
pluginId: string,
rating: number,
comment?: string,
userId?: string
): Promise<StatsResponse> {
if (rating < 1 || rating > 5) {
return { success: false, error: '评分必须在 1-5 之间' }
}
try {
const finalUserId = userId || getUserId()
const response = await fetch(`${STATS_API_BASE_URL}/stats/rate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ plugin_id: pluginId, rating, comment, user_id: finalUserId }),
})
const data = await response.json()
if (response.status === 429) {
return { success: false, error: '每天最多评分 3 次' }
}
if (!response.ok) {
return { success: false, error: data.error || '评分失败' }
}
return { success: true, ...data }
} catch (error) {
console.error('Error rating plugin:', error)
return { success: false, error: '网络错误' }
}
}
/**
*
*/
export async function recordPluginDownload(pluginId: string): Promise<StatsResponse> {
try {
const response = await fetch(`${STATS_API_BASE_URL}/stats/download`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ plugin_id: pluginId }),
})
const data = await response.json()
if (response.status === 429) {
// 下载统计被限流时静默失败,不影响用户体验
console.warn('Download recording rate limited')
return { success: true }
}
if (!response.ok) {
console.error('Failed to record download:', data.error)
return { success: false, error: data.error }
}
return { success: true, ...data }
} catch (error) {
console.error('Error recording download:', error)
return { success: false, error: '网络错误' }
}
}
/**
*
*
*/
export function generateUserFingerprint(): string {
const nav = navigator as Navigator & { deviceMemory?: number }
const features = [
navigator.userAgent,
navigator.language,
navigator.languages?.join(',') || '',
navigator.platform,
navigator.hardwareConcurrency || 0,
screen.width,
screen.height,
screen.colorDepth,
screen.pixelDepth,
new Date().getTimezoneOffset(),
Intl.DateTimeFormat().resolvedOptions().timeZone,
navigator.maxTouchPoints || 0,
nav.deviceMemory || 0,
].join('|')
// 简单哈希函数
let hash = 0
for (let i = 0; i < features.length; i++) {
const char = features.charCodeAt(i)
hash = ((hash << 5) - hash) + char
hash = hash & hash // Convert to 32bit integer
}
return `fp_${Math.abs(hash).toString(36)}`
}
/**
* UUID
* localStorage
*/
export function getUserId(): string {
const STORAGE_KEY = 'maibot_user_id'
// 尝试从 localStorage 获取
let userId = localStorage.getItem(STORAGE_KEY)
if (!userId) {
// 生成新的 UUID
const fingerprint = generateUserFingerprint()
const timestamp = Date.now().toString(36)
const random = Math.random().toString(36).substring(2, 15)
userId = `${fingerprint}_${timestamp}_${random}`
// 存储到 localStorage
localStorage.setItem(STORAGE_KEY, userId)
}
return userId
}

View File

@ -0,0 +1,350 @@
/**
* Context
*
*
* 使
* const { triggerRestart, isRestarting } = useRestart()
* triggerRestart() // 触发重启
*/
import {
createContext,
useContext,
useState,
useCallback,
useRef,
type ReactNode,
} from 'react'
import { restartMaiBot } from './system-api'
// ============ 类型定义 ============
export type RestartStatus =
| 'idle'
| 'requesting'
| 'restarting'
| 'checking'
| 'success'
| 'failed'
export interface RestartState {
status: RestartStatus
progress: number
elapsedTime: number
checkAttempts: number
maxAttempts: number
error?: string
}
export interface RestartContextValue {
/** 当前重启状态 */
state: RestartState
/** 是否正在重启中(任何非 idle 状态) */
isRestarting: boolean
/** 触发重启 */
triggerRestart: (options?: TriggerRestartOptions) => Promise<void>
/** 重置状态(用于失败后重试) */
resetState: () => void
/** 手动开始健康检查(用于重试) */
retryHealthCheck: () => void
}
export interface TriggerRestartOptions {
/** 重启前延迟(毫秒),用于显示提示 */
delay?: number
/** 自定义重启消息 */
message?: string
/** 跳过 API 调用(用于后端已触发重启的情况) */
skipApiCall?: boolean
}
// ============ 配置常量 ============
const CONFIG = {
/** 初始等待时间(毫秒),给后端重启时间 */
INITIAL_DELAY: 3000,
/** 健康检查间隔(毫秒) */
CHECK_INTERVAL: 2000,
/** 健康检查超时(毫秒) */
CHECK_TIMEOUT: 3000,
/** 最大检查次数 */
MAX_ATTEMPTS: 60,
/** 进度条更新间隔(毫秒) */
PROGRESS_INTERVAL: 200,
/** 成功后跳转延迟(毫秒) */
SUCCESS_REDIRECT_DELAY: 1500,
} as const
// ============ Context ============
const RestartContext = createContext<RestartContextValue | null>(null)
// ============ Provider ============
interface RestartProviderProps {
children: ReactNode
/** 重启成功后的回调 */
onRestartComplete?: () => void
/** 重启失败后的回调 */
onRestartFailed?: (error: string) => void
/** 自定义健康检查 URL */
healthCheckUrl?: string
/** 自定义最大尝试次数 */
maxAttempts?: number
}
export function RestartProvider({
children,
onRestartComplete,
onRestartFailed,
healthCheckUrl = '/api/webui/system/status',
maxAttempts = CONFIG.MAX_ATTEMPTS,
}: RestartProviderProps) {
const [state, setState] = useState<RestartState>({
status: 'idle',
progress: 0,
elapsedTime: 0,
checkAttempts: 0,
maxAttempts,
})
// 使用 useRef 存储定时器引用,避免闭包陷阱
const timersRef = useRef<{
progress?: ReturnType<typeof setInterval>
elapsed?: ReturnType<typeof setInterval>
check?: ReturnType<typeof setTimeout>
}>({})
// 清理所有定时器
const clearAllTimers = useCallback(() => {
const timers = timersRef.current
if (timers.progress) {
clearInterval(timers.progress)
timers.progress = undefined
}
if (timers.elapsed) {
clearInterval(timers.elapsed)
timers.elapsed = undefined
}
if (timers.check) {
clearTimeout(timers.check)
timers.check = undefined
}
}, [])
// 重置状态
const resetState = useCallback(() => {
clearAllTimers()
setState({
status: 'idle',
progress: 0,
elapsedTime: 0,
checkAttempts: 0,
maxAttempts,
})
}, [clearAllTimers, maxAttempts])
// 健康检查
const checkHealth = useCallback(
async (): Promise<boolean> => {
try {
const controller = new AbortController()
const timeoutId = setTimeout(
() => controller.abort(),
CONFIG.CHECK_TIMEOUT
)
const response = await fetch(healthCheckUrl, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
signal: controller.signal,
})
clearTimeout(timeoutId)
return response.ok
} catch {
// 网络错误、超时等都视为服务不可用,这是正常的
return false
}
},
[healthCheckUrl]
)
// 开始健康检查循环
const startHealthCheck = useCallback(() => {
let currentAttempt = 0
const doCheck = async () => {
currentAttempt++
setState((prev) => ({
...prev,
status: 'checking',
checkAttempts: currentAttempt,
}))
const isHealthy = await checkHealth()
if (isHealthy) {
// 成功
clearAllTimers()
setState((prev) => ({
...prev,
status: 'success',
progress: 100,
}))
// 延迟后跳转
setTimeout(() => {
onRestartComplete?.()
// 默认跳转到 auth 页面
window.location.href = '/auth'
}, CONFIG.SUCCESS_REDIRECT_DELAY)
} else if (currentAttempt >= maxAttempts) {
// 失败
clearAllTimers()
const error = `健康检查超时 (${currentAttempt}/${maxAttempts})`
setState((prev) => ({
...prev,
status: 'failed',
error,
}))
onRestartFailed?.(error)
} else {
// 继续检查
const checkTimer = setTimeout(doCheck, CONFIG.CHECK_INTERVAL)
timersRef.current.check = checkTimer
}
}
doCheck()
}, [checkHealth, clearAllTimers, maxAttempts, onRestartComplete, onRestartFailed])
// 重试健康检查
const retryHealthCheck = useCallback(() => {
setState((prev) => ({
...prev,
status: 'checking',
checkAttempts: 0,
error: undefined,
}))
startHealthCheck()
}, [startHealthCheck])
// 触发重启
const triggerRestart = useCallback(
async (options?: TriggerRestartOptions) => {
const { delay = 0, skipApiCall = false } = options ?? {}
// 已经在重启中,忽略
if (state.status !== 'idle' && state.status !== 'failed') {
return
}
// 重置状态
clearAllTimers()
setState({
status: 'requesting',
progress: 0,
elapsedTime: 0,
checkAttempts: 0,
maxAttempts,
})
// 可选延迟
if (delay > 0) {
await new Promise((resolve) => setTimeout(resolve, delay))
}
// 调用重启 API
if (!skipApiCall) {
try {
setState((prev) => ({ ...prev, status: 'restarting' }))
// 重启 API 可能不返回响应(服务立即关闭)
await Promise.race([
restartMaiBot(),
// 5秒超时超时也视为成功服务已关闭
new Promise((resolve) => setTimeout(resolve, 5000)),
])
} catch {
// API 调用失败也是正常的(服务已关闭)
// 继续进行健康检查
}
} else {
setState((prev) => ({ ...prev, status: 'restarting' }))
}
// 启动进度条动画
const progressTimer = setInterval(() => {
setState((prev) => ({
...prev,
progress: prev.progress >= 90 ? prev.progress : prev.progress + 1,
}))
}, CONFIG.PROGRESS_INTERVAL)
// 启动计时器
const elapsedTimer = setInterval(() => {
setState((prev) => ({
...prev,
elapsedTime: prev.elapsedTime + 1,
}))
}, 1000)
timersRef.current.progress = progressTimer
timersRef.current.elapsed = elapsedTimer
// 延迟后开始健康检查
setTimeout(() => {
startHealthCheck()
}, CONFIG.INITIAL_DELAY)
},
[state.status, clearAllTimers, maxAttempts, startHealthCheck]
)
const contextValue: RestartContextValue = {
state,
isRestarting: state.status !== 'idle',
triggerRestart,
resetState,
retryHealthCheck,
}
return (
<RestartContext.Provider value={contextValue}>
{children}
</RestartContext.Provider>
)
}
// ============ Hook ============
export function useRestart(): RestartContextValue {
const context = useContext(RestartContext)
if (!context) {
throw new Error('useRestart must be used within a RestartProvider')
}
return context
}
// ============ 便捷 Hook无需 Provider ============
/**
* Hook Provider
*
*/
export function useRestartAction() {
const [isRestarting, setIsRestarting] = useState(false)
const triggerRestart = useCallback(async () => {
if (isRestarting) return
setIsRestarting(true)
try {
await restartMaiBot()
} catch {
// 忽略错误,服务可能已关闭
}
}, [isRestarting])
return { isRestarting, triggerRestart }
}

View File

@ -0,0 +1,284 @@
/**
*
* localStorage
*/
// 所有设置的 key 定义
export const STORAGE_KEYS = {
// 外观设置
/** @deprecated 使用新的主题系统 — 见 @/lib/theme/storage.ts 的 THEME_STORAGE_KEYS.MODE */
THEME: 'maibot-ui-theme',
/** @deprecated 使用新的主题系统 — 见 @/lib/theme/storage.ts 的 THEME_STORAGE_KEYS.ACCENT */
ACCENT_COLOR: 'accent-color',
ENABLE_ANIMATIONS: 'maibot-animations',
ENABLE_WAVES_BACKGROUND: 'maibot-waves-background',
// 性能与存储设置
LOG_CACHE_SIZE: 'maibot-log-cache-size',
LOG_AUTO_SCROLL: 'maibot-log-auto-scroll',
LOG_FONT_SIZE: 'maibot-log-font-size',
LOG_LINE_SPACING: 'maibot-log-line-spacing',
DATA_SYNC_INTERVAL: 'maibot-data-sync-interval',
WS_RECONNECT_INTERVAL: 'maibot-ws-reconnect-interval',
WS_MAX_RECONNECT_ATTEMPTS: 'maibot-ws-max-reconnect-attempts',
// 用户数据
// 注意ACCESS_TOKEN 已弃用,现在使用 HttpOnly Cookie 存储认证信息
// 保留此常量仅用于向后兼容和清理旧数据
ACCESS_TOKEN: 'access-token',
COMPLETED_TOURS: 'maibot-completed-tours',
CHAT_USER_ID: 'maibot_webui_user_id',
CHAT_USER_NAME: 'maibot_webui_user_name',
} as const
// 默认设置值
export const DEFAULT_SETTINGS = {
// 外观
theme: 'system' as 'light' | 'dark' | 'system',
accentColor: 'blue',
enableAnimations: true,
enableWavesBackground: true,
// 性能与存储
logCacheSize: 1000,
logAutoScroll: true,
logFontSize: 'xs' as 'xs' | 'sm' | 'base',
logLineSpacing: 4,
dataSyncInterval: 30, // 秒
wsReconnectInterval: 3000, // 毫秒
wsMaxReconnectAttempts: 10,
}
// 设置类型定义
export type Settings = typeof DEFAULT_SETTINGS
// 可导出的设置(不包含敏感信息)
export type ExportableSettings = Omit<Settings, never> & {
completedTours?: string[]
}
/**
*
*/
export function getSetting<K extends keyof Settings>(key: K): Settings[K] {
const storageKey = getStorageKey(key)
const stored = localStorage.getItem(storageKey)
if (stored === null) {
return DEFAULT_SETTINGS[key]
}
// 根据默认值类型进行转换
const defaultValue = DEFAULT_SETTINGS[key]
if (typeof defaultValue === 'boolean') {
return (stored === 'true') as Settings[K]
}
if (typeof defaultValue === 'number') {
const num = parseFloat(stored)
return (isNaN(num) ? defaultValue : num) as Settings[K]
}
return stored as Settings[K]
}
/**
*
*/
export function setSetting<K extends keyof Settings>(key: K, value: Settings[K]): void {
const storageKey = getStorageKey(key)
localStorage.setItem(storageKey, String(value))
// 触发自定义事件,通知其他组件设置已更新
window.dispatchEvent(new CustomEvent('maibot-settings-change', {
detail: { key, value }
}))
}
/**
*
*/
export function getAllSettings(): Settings {
return {
theme: getSetting('theme'),
accentColor: getSetting('accentColor'),
enableAnimations: getSetting('enableAnimations'),
enableWavesBackground: getSetting('enableWavesBackground'),
logCacheSize: getSetting('logCacheSize'),
logAutoScroll: getSetting('logAutoScroll'),
logFontSize: getSetting('logFontSize'),
logLineSpacing: getSetting('logLineSpacing'),
dataSyncInterval: getSetting('dataSyncInterval'),
wsReconnectInterval: getSetting('wsReconnectInterval'),
wsMaxReconnectAttempts: getSetting('wsMaxReconnectAttempts'),
}
}
/**
*
*/
export function exportSettings(): ExportableSettings {
const settings = getAllSettings()
// 添加已完成的引导
const completedToursStr = localStorage.getItem(STORAGE_KEYS.COMPLETED_TOURS)
const completedTours = completedToursStr ? JSON.parse(completedToursStr) : []
return {
...settings,
completedTours,
}
}
/**
*
*/
export function importSettings(settings: Partial<ExportableSettings>): { success: boolean; imported: string[]; skipped: string[] } {
const imported: string[] = []
const skipped: string[] = []
// 验证并导入每个设置
for (const [key, value] of Object.entries(settings)) {
if (key === 'completedTours') {
// 特殊处理已完成的引导
if (Array.isArray(value)) {
localStorage.setItem(STORAGE_KEYS.COMPLETED_TOURS, JSON.stringify(value))
imported.push('completedTours')
} else {
skipped.push('completedTours')
}
continue
}
if (key in DEFAULT_SETTINGS) {
const settingKey = key as keyof Settings
const defaultValue = DEFAULT_SETTINGS[settingKey]
// 类型验证
if (typeof value === typeof defaultValue) {
// 额外验证
if (settingKey === 'theme' && !['light', 'dark', 'system'].includes(value as string)) {
skipped.push(key)
continue
}
if (settingKey === 'logFontSize' && !['xs', 'sm', 'base'].includes(value as string)) {
skipped.push(key)
continue
}
setSetting(settingKey, value as Settings[typeof settingKey])
imported.push(key)
} else {
skipped.push(key)
}
} else {
skipped.push(key)
}
}
return {
success: imported.length > 0,
imported,
skipped,
}
}
/**
*
*/
export function resetAllSettings(): void {
for (const key of Object.keys(DEFAULT_SETTINGS) as (keyof Settings)[]) {
setSetting(key, DEFAULT_SETTINGS[key])
}
// 清除已完成的引导
localStorage.removeItem(STORAGE_KEYS.COMPLETED_TOURS)
// 触发全局事件
window.dispatchEvent(new CustomEvent('maibot-settings-reset'))
}
/**
*
* HttpOnly Cookie
*/
export function clearLocalCache(): { clearedKeys: string[]; preservedKeys: string[] } {
const clearedKeys: string[] = []
const preservedKeys: string[] = []
// 遍历所有 localStorage 项
const keysToRemove: string[] = []
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)
if (key) {
if (key.startsWith('maibot') || key.startsWith('accent-color') || key === 'access-token') {
keysToRemove.push(key)
}
}
}
// 删除需要清除的 key
for (const key of keysToRemove) {
localStorage.removeItem(key)
clearedKeys.push(key)
}
return { clearedKeys, preservedKeys }
}
/**
* 使
*/
export function getStorageUsage(): { used: number; items: number; details: { key: string; size: number }[] } {
let totalSize = 0
const details: { key: string; size: number }[] = []
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)
if (key) {
const value = localStorage.getItem(key) || ''
const size = (key.length + value.length) * 2 // UTF-16 编码,每个字符 2 字节
totalSize += size
details.push({ key, size })
}
}
// 按大小排序
details.sort((a, b) => b.size - a.size)
return {
used: totalSize,
items: localStorage.length,
details,
}
}
/**
*
*/
export function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
// 内部辅助函数:获取 localStorage key
function getStorageKey(settingKey: keyof Settings): string {
const keyMap: Record<keyof Settings, string> = {
theme: STORAGE_KEYS.THEME,
accentColor: STORAGE_KEYS.ACCENT_COLOR,
enableAnimations: STORAGE_KEYS.ENABLE_ANIMATIONS,
enableWavesBackground: STORAGE_KEYS.ENABLE_WAVES_BACKGROUND,
logCacheSize: STORAGE_KEYS.LOG_CACHE_SIZE,
logAutoScroll: STORAGE_KEYS.LOG_AUTO_SCROLL,
logFontSize: STORAGE_KEYS.LOG_FONT_SIZE,
logLineSpacing: STORAGE_KEYS.LOG_LINE_SPACING,
dataSyncInterval: STORAGE_KEYS.DATA_SYNC_INTERVAL,
wsReconnectInterval: STORAGE_KEYS.WS_RECONNECT_INTERVAL,
wsMaxReconnectAttempts: STORAGE_KEYS.WS_MAX_RECONNECT_ATTEMPTS,
}
return keyMap[settingKey]
}

View File

@ -0,0 +1,176 @@
/**
* API
* Cloudflare Workers
*/
import type {
SurveySubmission,
StoredSubmission,
SurveyStats,
SurveySubmitResponse,
SurveyStatsResponse,
UserSubmissionsResponse,
QuestionAnswer
} from '@/types/survey'
// 配置统计服务 API 地址
const STATS_API_BASE_URL = 'https://maibot-plugin-stats.maibot-webui.workers.dev'
/**
* ID
*/
export function getUserId(): string {
const storageKey = 'maibot_user_id'
let userId = localStorage.getItem(storageKey)
if (!userId) {
// 生成新的用户ID: fp_{fingerprint}_{timestamp}_{random}
const fingerprint = Math.random().toString(36).substring(2, 10)
const timestamp = Date.now().toString(36)
const random = Math.random().toString(36).substring(2, 10)
userId = `fp_${fingerprint}_${timestamp}_${random}`
localStorage.setItem(storageKey, userId)
}
return userId
}
/**
*
*/
export async function submitSurvey(
surveyId: string,
surveyVersion: string,
answers: QuestionAnswer[],
options?: {
allowMultiple?: boolean
userId?: string
}
): Promise<SurveySubmitResponse> {
try {
const userId = options?.userId || getUserId()
const submission: SurveySubmission & { allowMultiple?: boolean } = {
surveyId,
surveyVersion,
userId,
answers,
submittedAt: new Date().toISOString(),
allowMultiple: options?.allowMultiple,
metadata: {
userAgent: navigator.userAgent,
language: navigator.language
}
}
const response = await fetch(`${STATS_API_BASE_URL}/survey/submit`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(submission),
})
const data = await response.json()
if (response.status === 429) {
return { success: false, error: '提交过于频繁,请稍后再试' }
}
if (response.status === 409) {
return { success: false, error: data.error || '你已经提交过这份问卷了' }
}
if (!response.ok) {
return { success: false, error: data.error || '提交失败' }
}
return {
success: true,
submissionId: data.submissionId,
message: data.message
}
} catch (error) {
console.error('Error submitting survey:', error)
return { success: false, error: '网络错误' }
}
}
/**
*
*/
export async function getSurveyStats(surveyId: string): Promise<SurveyStatsResponse> {
try {
const response = await fetch(`${STATS_API_BASE_URL}/survey/stats/${surveyId}`)
if (!response.ok) {
const data = await response.json()
return { success: false, error: data.error || '获取统计数据失败' }
}
const data = await response.json()
return { success: true, stats: data.stats as SurveyStats }
} catch (error) {
console.error('Error fetching survey stats:', error)
return { success: false, error: '网络错误' }
}
}
/**
*
*/
export async function getUserSubmissions(
surveyId?: string,
userId?: string
): Promise<UserSubmissionsResponse> {
try {
const finalUserId = userId || getUserId()
const params = new URLSearchParams({ user_id: finalUserId })
if (surveyId) {
params.append('survey_id', surveyId)
}
const response = await fetch(`${STATS_API_BASE_URL}/survey/submissions?${params}`)
if (!response.ok) {
const data = await response.json()
return { success: false, error: data.error || '获取提交记录失败' }
}
const data = await response.json()
return { success: true, submissions: data.submissions as StoredSubmission[] }
} catch (error) {
console.error('Error fetching user submissions:', error)
return { success: false, error: '网络错误' }
}
}
/**
*
*/
export async function checkUserSubmission(
surveyId: string,
userId?: string
): Promise<{ success: boolean; hasSubmitted?: boolean; error?: string }> {
try {
const finalUserId = userId || getUserId()
const params = new URLSearchParams({
user_id: finalUserId,
survey_id: surveyId
})
const response = await fetch(`${STATS_API_BASE_URL}/survey/check?${params}`)
if (!response.ok) {
const data = await response.json()
return { success: false, error: data.error || '检查失败' }
}
const data = await response.json()
return { success: true, hasSubmitted: data.hasSubmitted }
} catch (error) {
console.error('Error checking submission:', error)
return { success: false, error: '网络错误' }
}
}

View File

@ -0,0 +1,44 @@
import { fetchWithAuth, getAuthHeaders } from './fetch-with-auth'
/**
* API
*/
/**
*
*/
export async function restartMaiBot(): Promise<{ success: boolean; message: string }> {
const response = await fetchWithAuth('/api/webui/system/restart', {
method: 'POST',
headers: getAuthHeaders(),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '重启失败')
}
return await response.json()
}
/**
*
*/
export async function getMaiBotStatus(): Promise<{
running: boolean
uptime: number
version: string
start_time: string
}> {
const response = await fetchWithAuth('/api/webui/system/status', {
method: 'GET',
headers: getAuthHeaders(),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || '获取状态失败')
}
return await response.json()
}

View File

@ -0,0 +1,30 @@
import { createContext } from 'react'
import type { UserThemeConfig } from './theme/tokens'
type Theme = 'dark' | 'light' | 'system'
export type ThemeProviderState = {
theme: Theme
resolvedTheme: 'dark' | 'light'
setTheme: (theme: Theme) => void
themeConfig: UserThemeConfig
updateThemeConfig: (partial: Partial<UserThemeConfig>) => void
resetTheme: () => void
}
const initialState: ThemeProviderState = {
theme: 'system',
resolvedTheme: 'light',
setTheme: () => null,
themeConfig: {
selectedPreset: 'light',
accentColor: '',
tokenOverrides: {},
customCSS: '',
},
updateThemeConfig: () => null,
resetTheme: () => null,
}
export const ThemeProviderContext = createContext<ThemeProviderState>(initialState)

View File

@ -0,0 +1,203 @@
import type { ColorTokens } from './tokens'
type HSL = {
h: number
s: number
l: number
}
const clamp = (value: number, min: number, max: number): number => {
if (value < min) return min
if (value > max) return max
return value
}
const roundToTenth = (value: number): number => Math.round(value * 10) / 10
const wrapHue = (value: number): number => ((value % 360) + 360) % 360
export const parseHSL = (hslStr: string): HSL => {
const cleaned = hslStr
.trim()
.replace(/^hsl\(/i, '')
.replace(/\)$/i, '')
.replace(/,/g, ' ')
const parts = cleaned.split(/\s+/).filter(Boolean)
const rawH = parts[0] ?? '0'
const rawS = parts[1] ?? '0%'
const rawL = parts[2] ?? '0%'
const h = Number.parseFloat(rawH)
const s = Number.parseFloat(rawS.replace('%', ''))
const l = Number.parseFloat(rawL.replace('%', ''))
return {
h: Number.isNaN(h) ? 0 : h,
s: Number.isNaN(s) ? 0 : s,
l: Number.isNaN(l) ? 0 : l,
}
}
export const formatHSL = (h: number, s: number, l: number): string => {
const safeH = roundToTenth(wrapHue(h))
const safeS = roundToTenth(clamp(s, 0, 100))
const safeL = roundToTenth(clamp(l, 0, 100))
return `${safeH} ${safeS}% ${safeL}%`
}
export const hexToHSL = (hex: string): string => {
let cleaned = hex.trim().replace('#', '')
if (cleaned.length === 3) {
cleaned = cleaned
.split('')
.map((char) => `${char}${char}`)
.join('')
}
if (cleaned.length !== 6) {
return formatHSL(0, 0, 0)
}
const r = Number.parseInt(cleaned.slice(0, 2), 16) / 255
const g = Number.parseInt(cleaned.slice(2, 4), 16) / 255
const b = Number.parseInt(cleaned.slice(4, 6), 16) / 255
const max = Math.max(r, g, b)
const min = Math.min(r, g, b)
const delta = max - min
const l = (max + min) / 2
let h = 0
let s = 0
if (delta !== 0) {
s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min)
switch (max) {
case r:
h = (g - b) / delta + (g < b ? 6 : 0)
break
case g:
h = (b - r) / delta + 2
break
case b:
h = (r - g) / delta + 4
break
default:
break
}
h *= 60
}
return formatHSL(h, s * 100, l * 100)
}
export const adjustLightness = (hsl: string, amount: number): string => {
const { h, s, l } = parseHSL(hsl)
return formatHSL(h, s, l + amount)
}
export const adjustSaturation = (hsl: string, amount: number): string => {
const { h, s, l } = parseHSL(hsl)
return formatHSL(h, s + amount, l)
}
export const rotateHue = (hsl: string, degrees: number): string => {
const { h, s, l } = parseHSL(hsl)
return formatHSL(h + degrees, s, l)
}
const setLightness = (hsl: string, lightness: number): string => {
const { h, s } = parseHSL(hsl)
return formatHSL(h, s, lightness)
}
const setSaturation = (hsl: string, saturation: number): string => {
const { h, l } = parseHSL(hsl)
return formatHSL(h, saturation, l)
}
const getReadableForeground = (hsl: string): string => {
const { h, s, l } = parseHSL(hsl)
const neutralSaturation = clamp(s * 0.15, 6, 20)
return l > 60
? formatHSL(h, neutralSaturation, 10)
: formatHSL(h, neutralSaturation, 96)
}
export const generatePalette = (accentHSL: string, isDark: boolean): ColorTokens => {
const accent = parseHSL(accentHSL)
const primary = formatHSL(accent.h, accent.s, accent.l)
const background = isDark ? '222.2 84% 4.9%' : '0 0% 100%'
const foreground = isDark ? '210 40% 98%' : '222.2 84% 4.9%'
const secondary = formatHSL(
accent.h,
clamp(accent.s * 0.35, 8, 40),
isDark ? 17.5 : 96,
)
const muted = formatHSL(
accent.h,
clamp(accent.s * 0.12, 2, 18),
isDark ? 17.5 : 96,
)
const accentVariant = formatHSL(
accent.h + 35,
clamp(accent.s * 0.6, 20, 85),
isDark ? clamp(accent.l * 0.6 + 8, 25, 60) : clamp(accent.l * 0.8 + 14, 40, 75),
)
const destructive = formatHSL(
0,
clamp(accent.s, 60, 90),
isDark ? 30.6 : 60.2,
)
const border = formatHSL(
accent.h,
clamp(accent.s * 0.2, 5, 25),
isDark ? 17.5 : 91.4,
)
const mutedForeground = setSaturation(
setLightness(muted, isDark ? 65.1 : 46.9),
clamp(accent.s * 0.2, 10, 30),
)
const chartBase = formatHSL(accent.h, accent.s, accent.l)
const chartSteps = [0, 72, 144, 216, 288]
const charts = chartSteps.map((step) => rotateHue(chartBase, step))
const card = adjustLightness(background, isDark ? 2 : -1)
const popover = adjustLightness(background, isDark ? 3 : -0.5)
return {
primary,
'primary-foreground': getReadableForeground(primary),
'primary-gradient': 'none',
secondary,
'secondary-foreground': getReadableForeground(secondary),
muted,
'muted-foreground': mutedForeground,
accent: accentVariant,
'accent-foreground': getReadableForeground(accentVariant),
destructive,
'destructive-foreground': getReadableForeground(destructive),
background,
foreground,
card,
'card-foreground': foreground,
popover,
'popover-foreground': foreground,
border,
input: border,
ring: primary,
'chart-1': charts[0],
'chart-2': charts[1],
'chart-3': charts[2],
'chart-4': charts[3],
'chart-5': charts[4],
}
}

View File

@ -0,0 +1,194 @@
import type { ThemeTokens, UserThemeConfig } from './tokens'
import { generatePalette } from './palette'
import { getPresetById } from './presets'
import { sanitizeCSS } from './sanitizer'
import { defaultDarkTokens, defaultLightTokens, tokenToCSSVarName } from './tokens'
const CUSTOM_CSS_ID = 'maibot-custom-css'
const COMPONENT_CSS_ID_PREFIX = 'maibot-bg-css-'
const COMPONENT_IDS = ['page', 'sidebar', 'header', 'card', 'dialog'] as const
const mergeTokens = (base: ThemeTokens, overrides: Partial<ThemeTokens>): ThemeTokens => {
return {
color: {
...base.color,
...(overrides.color ?? {}),
},
typography: {
...base.typography,
...(overrides.typography ?? {}),
},
visual: {
...base.visual,
...(overrides.visual ?? {}),
},
layout: {
...base.layout,
...(overrides.layout ?? {}),
},
animation: {
...base.animation,
...(overrides.animation ?? {}),
},
}
}
const buildTokens = (config: UserThemeConfig, isDark: boolean): ThemeTokens => {
const baseTokens = isDark ? defaultDarkTokens : defaultLightTokens
let mergedTokens = mergeTokens(baseTokens, {})
if (config.accentColor) {
const paletteTokens = generatePalette(config.accentColor, isDark)
mergedTokens = mergeTokens(mergedTokens, { color: paletteTokens })
}
if (config.selectedPreset) {
const preset = getPresetById(config.selectedPreset)
if (preset?.tokens) {
mergedTokens = mergeTokens(mergedTokens, preset.tokens)
}
}
if (config.tokenOverrides) {
mergedTokens = mergeTokens(mergedTokens, config.tokenOverrides)
}
return mergedTokens
}
export function getComputedTokens(config: UserThemeConfig, isDark: boolean): ThemeTokens {
return buildTokens(config, isDark)
}
export function injectTokensAsCSS(tokens: ThemeTokens, target: HTMLElement): void {
Object.entries(tokens.color).forEach(([key, value]) => {
target.style.setProperty(tokenToCSSVarName('color', key), String(value))
})
Object.entries(tokens.typography).forEach(([key, value]) => {
target.style.setProperty(tokenToCSSVarName('typography', key), String(value))
})
Object.entries(tokens.visual).forEach(([key, value]) => {
target.style.setProperty(tokenToCSSVarName('visual', key), String(value))
})
Object.entries(tokens.layout).forEach(([key, value]) => {
target.style.setProperty(tokenToCSSVarName('layout', key), String(value))
})
Object.entries(tokens.animation).forEach(([key, value]) => {
target.style.setProperty(tokenToCSSVarName('animation', key), String(value))
})
}
export function injectCustomCSS(css: string): void {
if (css.trim().length === 0) {
removeCustomCSS()
return
}
const existing = document.getElementById(CUSTOM_CSS_ID)
if (existing) {
existing.textContent = css
return
}
const style = document.createElement('style')
style.id = CUSTOM_CSS_ID
style.textContent = css
document.head.appendChild(style)
}
export function removeCustomCSS(): void {
const existing = document.getElementById(CUSTOM_CSS_ID)
if (existing) {
existing.remove()
}
}
/**
* CSS
* 使 style ,CSS sanitize
* @param css - CSS
* @param componentId - (page/sidebar/header/card/dialog)
*/
export function injectComponentCSS(css: string, componentId: string): void {
const styleId = `${COMPONENT_CSS_ID_PREFIX}${componentId}`
if (css.trim().length === 0) {
removeComponentCSS(componentId)
return
}
const sanitized = sanitizeCSS(css)
const sanitizedCss = sanitized.css
if (sanitizedCss.trim().length === 0) {
removeComponentCSS(componentId)
return
}
const existing = document.getElementById(styleId)
if (existing) {
existing.textContent = sanitizedCss
return
}
const style = document.createElement('style')
style.id = styleId
style.textContent = sanitizedCss
document.head.appendChild(style)
}
/**
* CSS
*/
export function removeComponentCSS(componentId: string): void {
const styleId = `${COMPONENT_CSS_ID_PREFIX}${componentId}`
document.getElementById(styleId)?.remove()
}
/**
* CSS
*/
export function removeAllComponentCSS(): void {
COMPONENT_IDS.forEach(removeComponentCSS)
}
export function applyThemePipeline(config: UserThemeConfig, isDark: boolean): void {
const root = document.documentElement
const tokens = buildTokens(config, isDark)
injectTokensAsCSS(tokens, root)
if (config.customCSS) {
const sanitized = sanitizeCSS(config.customCSS)
if (sanitized.css.trim().length > 0) {
injectCustomCSS(sanitized.css)
} else {
removeCustomCSS()
}
} else {
removeCustomCSS()
}
// 应用组件级 CSS(注入顺序在全局 CSS 之后)
if (config.backgroundConfig) {
const { page, sidebar, header, card, dialog } = config.backgroundConfig
;[
['page', page],
['sidebar', sidebar],
['header', header],
['card', card],
['dialog', dialog],
].forEach(([id, cfg]) => {
if (cfg && typeof cfg === 'object' && 'customCSS' in cfg && cfg.customCSS) {
injectComponentCSS(cfg.customCSS, id as string)
} else {
removeComponentCSS(id as string)
}
})
} else {
removeAllComponentCSS()
}
}

View File

@ -0,0 +1,62 @@
/**
* Theme Presets
*
*/
import {
defaultDarkTokens,
defaultLightTokens,
} from './tokens'
import type { ThemePreset } from './tokens'
// ============================================================================
// Default Light Preset
// ============================================================================
export const defaultLightPreset: ThemePreset = {
id: 'light',
name: '默认亮色',
description: '默认亮色主题',
tokens: defaultLightTokens,
isDark: false,
}
// ============================================================================
// Default Dark Preset
// ============================================================================
export const defaultDarkPreset: ThemePreset = {
id: 'dark',
name: '默认暗色',
description: '默认暗色主题',
tokens: defaultDarkTokens,
isDark: true,
}
// ============================================================================
// Built-in Presets Collection
// ============================================================================
export const builtInPresets: ThemePreset[] = [
defaultLightPreset,
defaultDarkPreset,
]
// ============================================================================
// Default Preset ID
// ============================================================================
export const DEFAULT_PRESET_ID = 'light'
// ============================================================================
// Preset Utility Functions
// ============================================================================
/**
* ID
* @param id - ID
* @returns undefined
*/
export function getPresetById(id: string): ThemePreset | undefined {
return builtInPresets.find((preset) => preset.id === id)
}

View File

@ -0,0 +1,111 @@
/**
* CSS - CSS
* XSS
*/
interface SanitizeResult {
css: string
warnings: string[]
}
/**
*
*
*/
interface FilterRule {
pattern: RegExp
message: string
}
/**
*
*/
const filterRules: FilterRule[] = [
{
pattern: /@import\s+(?:url\()?['"]?(?:https?:|\/\/)?[^)'"]+['"]?\)?[;]?/gi,
message: '移除 @import 语句(禁止加载外部资源)',
},
{
pattern: /url\s*\(\s*(?:https?:|\/\/|data:|javascript:)[^)]*\)/gi,
message: '移除 url() 调用(禁止外部请求)',
},
{
pattern: /javascript:/gi,
message: '移除 javascript: 协议XSS 防护)',
},
{
pattern: /expression\s*\(\s*[^)]*\)/gi,
message: '移除 expression() 函数IE 遗留 XSS 向量)',
},
{
pattern: /-moz-binding\s*:\s*[^;]+/gi,
message: '移除 -moz-binding 属性Firefox XSS 向量)',
},
{
pattern: /behavior\s*:\s*[^;]+/gi,
message: '移除 behavior: 属性IE HTC',
},
]
/**
* CSS
*/
function splitCSSByLines(css: string): string[] {
return css.split(/\r?\n/)
}
/**
* CSS
*/
function findMatchingLineNumbers(css: string, pattern: RegExp): number[] {
const lines = splitCSSByLines(css)
const matchingLines: number[] = []
lines.forEach((line, index) => {
if (pattern.test(line)) {
matchingLines.push(index + 1) // 行号从 1 开始
}
})
return matchingLines
}
/**
* CSS
* @param rawCSS CSS
* @returns CSS
*/
export function sanitizeCSS(rawCSS: string): SanitizeResult {
let sanitizedCSS = rawCSS
const warnings: string[] = []
// 应用所有过滤规则
filterRules.forEach((rule) => {
const lineNumbers = findMatchingLineNumbers(sanitizedCSS, rule.pattern)
// 对每个匹配的行生成警告
lineNumbers.forEach((lineNum) => {
warnings.push(`Line ${lineNum}: ${rule.message}`)
})
// 从 CSS 中移除匹配内容
sanitizedCSS = sanitizedCSS.replace(rule.pattern, '')
})
// 清理多余的空白行
sanitizedCSS = sanitizedCSS.replace(/\n\s*\n/g, '\n').trim()
return {
css: sanitizedCSS,
warnings,
}
}
/**
* CSS
* @param css CSS
* @returns true false
*/
export function isCSSSafe(css: string): boolean {
return !filterRules.some((rule) => rule.pattern.test(css))
}

View File

@ -0,0 +1,225 @@
/**
* localStorage
* key
*/
import type { BackgroundConfigMap, UserThemeConfig } from './tokens'
/**
* key
* 使 'maibot-theme-*' 'ui-theme''maibot-ui-theme' 'accent-color'
*/
export const THEME_STORAGE_KEYS = {
MODE: 'maibot-theme-mode',
PRESET: 'maibot-theme-preset',
ACCENT: 'maibot-theme-accent',
OVERRIDES: 'maibot-theme-overrides',
CUSTOM_CSS: 'maibot-theme-custom-css',
BACKGROUND_CONFIG: 'maibot-theme-background',
} as const
/**
*
*/
const DEFAULT_THEME_CONFIG: UserThemeConfig = {
selectedPreset: 'light',
accentColor: 'blue',
tokenOverrides: {},
customCSS: '',
backgroundConfig: {} as BackgroundConfigMap,
}
/**
* localStorage
* 使
*
* @returns
*/
export function loadThemeConfig(): UserThemeConfig {
const preset = localStorage.getItem(THEME_STORAGE_KEYS.PRESET)
const accent = localStorage.getItem(THEME_STORAGE_KEYS.ACCENT)
const overridesStr = localStorage.getItem(THEME_STORAGE_KEYS.OVERRIDES)
const customCSS = localStorage.getItem(THEME_STORAGE_KEYS.CUSTOM_CSS)
// 解析 tokenOverrides JSON
let tokenOverrides = {}
if (overridesStr) {
try {
tokenOverrides = JSON.parse(overridesStr)
} catch {
// JSON 解析失败,使用空对象
tokenOverrides = {}
}
}
// 加载 backgroundConfig
const backgroundConfigStr = localStorage.getItem(THEME_STORAGE_KEYS.BACKGROUND_CONFIG)
let backgroundConfig: BackgroundConfigMap = {}
if (backgroundConfigStr) {
try {
backgroundConfig = JSON.parse(backgroundConfigStr)
} catch {
backgroundConfig = {}
}
}
return {
selectedPreset: preset || DEFAULT_THEME_CONFIG.selectedPreset,
accentColor: accent || DEFAULT_THEME_CONFIG.accentColor,
tokenOverrides,
customCSS: customCSS || DEFAULT_THEME_CONFIG.customCSS,
backgroundConfig,
}
}
/**
* localStorage
*
* @param config -
*/
export function saveThemeConfig(config: UserThemeConfig): void {
localStorage.setItem(THEME_STORAGE_KEYS.PRESET, config.selectedPreset)
localStorage.setItem(THEME_STORAGE_KEYS.ACCENT, config.accentColor)
localStorage.setItem(THEME_STORAGE_KEYS.OVERRIDES, JSON.stringify(config.tokenOverrides))
localStorage.setItem(THEME_STORAGE_KEYS.CUSTOM_CSS, config.customCSS)
if (config.backgroundConfig) {
localStorage.setItem(THEME_STORAGE_KEYS.BACKGROUND_CONFIG, JSON.stringify(config.backgroundConfig))
} else {
localStorage.removeItem(THEME_STORAGE_KEYS.BACKGROUND_CONFIG)
}
}
/**
*
*
*
* @param partial -
*/
export function saveThemePartial(partial: Partial<UserThemeConfig>): void {
const current = loadThemeConfig()
const updated: UserThemeConfig = {
...current,
...partial,
}
saveThemeConfig(updated)
}
/**
* JSON
*
* @returns JSON
*/
export function exportThemeJSON(): string {
const config = loadThemeConfig()
return JSON.stringify(config, null, 2)
}
/**
* JSON
*
*
* @param json - JSON
* @returns
*/
export function importThemeJSON(
json: string,
): { success: boolean; errors: string[] } {
const errors: string[] = []
// JSON 格式校验
let config: unknown
try {
config = JSON.parse(json)
} catch (error) {
return {
success: false,
errors: [`Invalid JSON format: ${error instanceof Error ? error.message : 'Unknown error'}`],
}
}
// 基本对象类型校验
if (typeof config !== 'object' || config === null) {
return {
success: false,
errors: ['Configuration must be a JSON object'],
}
}
const configObj = config as Record<string, unknown>
// 必要字段存在性校验
if (typeof configObj.selectedPreset !== 'string') {
errors.push('selectedPreset must be a string')
}
if (typeof configObj.accentColor !== 'string') {
errors.push('accentColor must be a string')
}
if (typeof configObj.customCSS !== 'string') {
errors.push('customCSS must be a string')
}
if (configObj.tokenOverrides !== undefined && typeof configObj.tokenOverrides !== 'object') {
errors.push('tokenOverrides must be an object')
}
if (errors.length > 0) {
return { success: false, errors }
}
// 校验通过,保存配置
const validConfig: UserThemeConfig = {
selectedPreset: configObj.selectedPreset as string,
accentColor: configObj.accentColor as string,
tokenOverrides: (configObj.tokenOverrides as Partial<any>) || {},
customCSS: configObj.customCSS as string,
backgroundConfig: (configObj.backgroundConfig as BackgroundConfigMap) ?? {},
}
saveThemeConfig(validConfig)
return { success: true, errors: [] }
}
/**
*
* THEME_STORAGE_KEYS localStorage
*/
export function resetThemeToDefault(): void {
Object.values(THEME_STORAGE_KEYS).forEach((key) => {
localStorage.removeItem(key)
})
}
/**
* localStorage key key
*
* - 'ui-theme' 'maibot-ui-theme' 'maibot-theme-mode'
* - 'accent-color' 'maibot-theme-accent'
* key
*/
export function migrateOldKeys(): void {
// 迁移主题模式
// 优先使用 'ui-theme'(因为 ThemeProvider 默认使用它)
const uiTheme = localStorage.getItem('ui-theme')
const maiTheme = localStorage.getItem('maibot-ui-theme')
const newMode = localStorage.getItem(THEME_STORAGE_KEYS.MODE)
if (!newMode) {
if (uiTheme) {
localStorage.setItem(THEME_STORAGE_KEYS.MODE, uiTheme)
} else if (maiTheme) {
localStorage.setItem(THEME_STORAGE_KEYS.MODE, maiTheme)
}
}
// 迁移强调色
const accentColor = localStorage.getItem('accent-color')
const newAccent = localStorage.getItem(THEME_STORAGE_KEYS.ACCENT)
if (accentColor && !newAccent) {
localStorage.setItem(THEME_STORAGE_KEYS.ACCENT, accentColor)
}
// 删除旧 key
localStorage.removeItem('ui-theme')
localStorage.removeItem('maibot-ui-theme')
localStorage.removeItem('accent-color')
}

View File

@ -0,0 +1,401 @@
/**
* Design Token Schema
*
*/
// ============================================================================
// Color Tokens 类型定义
// ============================================================================
export type ColorTokens = {
primary: string
'primary-foreground': string
'primary-gradient': string
secondary: string
'secondary-foreground': string
muted: string
'muted-foreground': string
accent: string
'accent-foreground': string
destructive: string
'destructive-foreground': string
background: string
foreground: string
card: string
'card-foreground': string
popover: string
'popover-foreground': string
border: string
input: string
ring: string
'chart-1': string
'chart-2': string
'chart-3': string
'chart-4': string
'chart-5': string
}
// ============================================================================
// Typography Tokens 类型定义
// ============================================================================
export type TypographyTokens = {
'font-family-base': string
'font-family-code': string
'font-size-xs': string
'font-size-sm': string
'font-size-base': string
'font-size-lg': string
'font-size-xl': string
'font-size-2xl': string
'font-weight-normal': number
'font-weight-medium': number
'font-weight-semibold': number
'font-weight-bold': number
'line-height-tight': number
'line-height-normal': number
'line-height-relaxed': number
'letter-spacing-tight': string
'letter-spacing-normal': string
'letter-spacing-wide': string
}
// ============================================================================
// Visual Tokens 类型定义
// ============================================================================
export type VisualTokens = {
'radius-sm': string
'radius-md': string
'radius-lg': string
'radius-xl': string
'radius-full': string
'shadow-sm': string
'shadow-md': string
'shadow-lg': string
'shadow-xl': string
'blur-sm': string
'blur-md': string
'blur-lg': string
'opacity-disabled': number
'opacity-hover': number
'opacity-overlay': number
}
// ============================================================================
// Layout Tokens 类型定义
// ============================================================================
export type LayoutTokens = {
'space-unit': string
'space-xs': string
'space-sm': string
'space-md': string
'space-lg': string
'space-xl': string
'space-2xl': string
'sidebar-width': string
'header-height': string
'max-content-width': string
}
// ============================================================================
// Animation Tokens 类型定义
// ============================================================================
export type AnimationTokens = {
'anim-duration-fast': string
'anim-duration-normal': string
'anim-duration-slow': string
'anim-easing-default': string
'anim-easing-in': string
'anim-easing-out': string
'anim-easing-in-out': string
'transition-colors': string
'transition-transform': string
'transition-opacity': string
}
// ============================================================================
// Aggregated Theme Tokens
// ============================================================================
export type ThemeTokens = {
color: ColorTokens
typography: TypographyTokens
visual: VisualTokens
layout: LayoutTokens
animation: AnimationTokens
}
// ============================================================================
// Theme Preset & Config Types
// ============================================================================
export type ThemePreset = {
id: string
name: string
description: string
tokens: ThemeTokens
isDark: boolean
}
export type UserThemeConfig = {
selectedPreset: string
accentColor: string
tokenOverrides: Partial<ThemeTokens>
customCSS: string
backgroundConfig?: BackgroundConfigMap
}
// ============================================================================
// Default Light Tokens (from index.css :root)
// ============================================================================
export const defaultLightTokens: ThemeTokens = {
color: {
primary: '221.2 83.2% 53.3%',
'primary-foreground': '210 40% 98%',
'primary-gradient': 'none',
secondary: '210 40% 96.1%',
'secondary-foreground': '222.2 47.4% 11.2%',
muted: '210 40% 96.1%',
'muted-foreground': '215.4 16.3% 46.9%',
accent: '210 40% 96.1%',
'accent-foreground': '222.2 47.4% 11.2%',
destructive: '0 84.2% 60.2%',
'destructive-foreground': '210 40% 98%',
background: '0 0% 100%',
foreground: '222.2 84% 4.9%',
card: '0 0% 100%',
'card-foreground': '222.2 84% 4.9%',
popover: '0 0% 100%',
'popover-foreground': '222.2 84% 4.9%',
border: '214.3 31.8% 91.4%',
input: '214.3 31.8% 91.4%',
ring: '221.2 83.2% 53.3%',
'chart-1': '221.2 83.2% 53.3%',
'chart-2': '160 60% 45%',
'chart-3': '30 80% 55%',
'chart-4': '280 65% 60%',
'chart-5': '340 75% 55%',
},
typography: {
'font-family-base': '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
'font-family-code': '"JetBrains Mono", "Monaco", "Courier New", monospace',
'font-size-xs': '0.75rem',
'font-size-sm': '0.875rem',
'font-size-base': '1rem',
'font-size-lg': '1.125rem',
'font-size-xl': '1.25rem',
'font-size-2xl': '1.5rem',
'font-weight-normal': 400,
'font-weight-medium': 500,
'font-weight-semibold': 600,
'font-weight-bold': 700,
'line-height-tight': 1.2,
'line-height-normal': 1.5,
'line-height-relaxed': 1.75,
'letter-spacing-tight': '-0.02em',
'letter-spacing-normal': '0em',
'letter-spacing-wide': '0.02em',
},
visual: {
'radius-sm': '0.25rem',
'radius-md': '0.375rem',
'radius-lg': '0.5rem',
'radius-xl': '0.75rem',
'radius-full': '9999px',
'shadow-sm': '0 1px 2px 0 rgba(0, 0, 0, 0.05)',
'shadow-md': '0 4px 6px -1px rgba(0, 0, 0, 0.1)',
'shadow-lg': '0 10px 15px -3px rgba(0, 0, 0, 0.1)',
'shadow-xl': '0 20px 25px -5px rgba(0, 0, 0, 0.1)',
'blur-sm': '4px',
'blur-md': '12px',
'blur-lg': '24px',
'opacity-disabled': 0.5,
'opacity-hover': 0.8,
'opacity-overlay': 0.75,
},
layout: {
'space-unit': '0.25rem',
'space-xs': '0.5rem',
'space-sm': '0.75rem',
'space-md': '1rem',
'space-lg': '1.5rem',
'space-xl': '2rem',
'space-2xl': '3rem',
'sidebar-width': '16rem',
'header-height': '3.5rem',
'max-content-width': '1280px',
},
animation: {
'anim-duration-fast': '150ms',
'anim-duration-normal': '300ms',
'anim-duration-slow': '500ms',
'anim-easing-default': 'cubic-bezier(0.4, 0, 0.2, 1)',
'anim-easing-in': 'cubic-bezier(0.4, 0, 1, 1)',
'anim-easing-out': 'cubic-bezier(0, 0, 0.2, 1)',
'anim-easing-in-out': 'cubic-bezier(0.4, 0, 0.2, 1)',
'transition-colors': 'color 300ms cubic-bezier(0.4, 0, 0.2, 1)',
'transition-transform': 'transform 300ms cubic-bezier(0.4, 0, 0.2, 1)',
'transition-opacity': 'opacity 300ms cubic-bezier(0.4, 0, 0.2, 1)',
},
}
// ============================================================================
// Default Dark Tokens (from index.css .dark)
// ============================================================================
export const defaultDarkTokens: ThemeTokens = {
color: {
primary: '217.2 91.2% 59.8%',
'primary-foreground': '210 40% 98%',
'primary-gradient': 'none',
secondary: '217.2 32.6% 17.5%',
'secondary-foreground': '210 40% 98%',
muted: '217.2 32.6% 17.5%',
'muted-foreground': '215 20.2% 65.1%',
accent: '217.2 32.6% 17.5%',
'accent-foreground': '210 40% 98%',
destructive: '0 62.8% 30.6%',
'destructive-foreground': '210 40% 98%',
background: '222.2 84% 4.9%',
foreground: '210 40% 98%',
card: '222.2 84% 4.9%',
'card-foreground': '210 40% 98%',
popover: '222.2 84% 4.9%',
'popover-foreground': '210 40% 98%',
border: '217.2 32.6% 17.5%',
input: '217.2 32.6% 17.5%',
ring: '224.3 76.3% 48%',
'chart-1': '217.2 91.2% 59.8%',
'chart-2': '160 60% 50%',
'chart-3': '30 80% 60%',
'chart-4': '280 65% 65%',
'chart-5': '340 75% 60%',
},
typography: {
'font-family-base': '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
'font-family-code': '"JetBrains Mono", "Monaco", "Courier New", monospace',
'font-size-xs': '0.75rem',
'font-size-sm': '0.875rem',
'font-size-base': '1rem',
'font-size-lg': '1.125rem',
'font-size-xl': '1.25rem',
'font-size-2xl': '1.5rem',
'font-weight-normal': 400,
'font-weight-medium': 500,
'font-weight-semibold': 600,
'font-weight-bold': 700,
'line-height-tight': 1.2,
'line-height-normal': 1.5,
'line-height-relaxed': 1.75,
'letter-spacing-tight': '-0.02em',
'letter-spacing-normal': '0em',
'letter-spacing-wide': '0.02em',
},
visual: {
'radius-sm': '0.25rem',
'radius-md': '0.375rem',
'radius-lg': '0.5rem',
'radius-xl': '0.75rem',
'radius-full': '9999px',
'shadow-sm': '0 1px 2px 0 rgba(0, 0, 0, 0.25)',
'shadow-md': '0 4px 6px -1px rgba(0, 0, 0, 0.3)',
'shadow-lg': '0 10px 15px -3px rgba(0, 0, 0, 0.4)',
'shadow-xl': '0 20px 25px -5px rgba(0, 0, 0, 0.5)',
'blur-sm': '4px',
'blur-md': '12px',
'blur-lg': '24px',
'opacity-disabled': 0.5,
'opacity-hover': 0.8,
'opacity-overlay': 0.75,
},
layout: {
'space-unit': '0.25rem',
'space-xs': '0.5rem',
'space-sm': '0.75rem',
'space-md': '1rem',
'space-lg': '1.5rem',
'space-xl': '2rem',
'space-2xl': '3rem',
'sidebar-width': '16rem',
'header-height': '3.5rem',
'max-content-width': '1280px',
},
animation: {
'anim-duration-fast': '150ms',
'anim-duration-normal': '300ms',
'anim-duration-slow': '500ms',
'anim-easing-default': 'cubic-bezier(0.4, 0, 0.2, 1)',
'anim-easing-in': 'cubic-bezier(0.4, 0, 1, 1)',
'anim-easing-out': 'cubic-bezier(0, 0, 0.2, 1)',
'anim-easing-in-out': 'cubic-bezier(0.4, 0, 0.2, 1)',
'transition-colors': 'color 300ms cubic-bezier(0.4, 0, 0.2, 1)',
'transition-transform': 'transform 300ms cubic-bezier(0.4, 0, 0.2, 1)',
'transition-opacity': 'opacity 300ms cubic-bezier(0.4, 0, 0.2, 1)',
},
}
// ============================================================================
// Token Utility Functions
// ============================================================================
/**
* Token key CSS
* @example tokenToCSSVarName('color', 'primary') => '--color-primary'
*/
export function tokenToCSSVarName(
category: keyof ThemeTokens | 'color' | 'typography' | 'visual' | 'layout' | 'animation',
key: string,
): string {
return `--${category}-${key}`
}
// ============================================================================
// Background Config Types
// ============================================================================
export type BackgroundEffects = {
blur: number // px, 0-50
overlayColor: string // HSL string如 '0 0% 0%'
overlayOpacity: number // 0-1
position: 'cover' | 'contain' | 'center' | 'stretch'
brightness: number // 0-200, default 100
contrast: number // 0-200, default 100
saturate: number // 0-200, default 100
gradientOverlay?: string // CSS gradient string可选
}
export type BackgroundConfig = {
type: 'none' | 'image' | 'video'
assetId?: string // IndexedDB asset ID
inherit?: boolean // true = 继承页面背景
effects: BackgroundEffects
customCSS: string // 组件级自定义 CSS
}
export type BackgroundConfigMap = {
page?: BackgroundConfig
sidebar?: BackgroundConfig
header?: BackgroundConfig
card?: BackgroundConfig
dialog?: BackgroundConfig
}
export const defaultBackgroundEffects: BackgroundEffects = {
blur: 0,
overlayColor: '0 0% 0%',
overlayOpacity: 0,
position: 'cover',
brightness: 100,
contrast: 100,
saturate: 100,
}
export const defaultBackgroundConfig: BackgroundConfig = {
type: 'none',
effects: defaultBackgroundEffects,
customCSS: '',
}

View File

@ -0,0 +1,82 @@
/**
* Token
*/
export interface TokenValidationRule {
id: string
label: string
validate: (token: string) => boolean
description: string
}
export interface TokenValidationResult {
isValid: boolean
rules: Array<{
id: string
label: string
passed: boolean
description: string
}>
}
// Token 验证规则定义
export const TOKEN_VALIDATION_RULES: TokenValidationRule[] = [
{
id: 'minLength',
label: '长度至少 10 位',
description: 'Token 长度必须大于等于 10 个字符',
validate: (token: string) => token.length >= 10,
},
{
id: 'hasUppercase',
label: '包含大写字母',
description: '至少包含一个大写字母 (A-Z)',
validate: (token: string) => /[A-Z]/.test(token),
},
{
id: 'hasLowercase',
label: '包含小写字母',
description: '至少包含一个小写字母 (a-z)',
validate: (token: string) => /[a-z]/.test(token),
},
{
id: 'hasSpecialChar',
label: '包含特殊符号',
description: '至少包含一个特殊符号 (!@#$%^&*()_+-=[]{}|;:,.<>?/)',
validate: (token: string) => /[!@#$%^&*()_+\-=[\]{}|;:,.<>?/]/.test(token),
},
]
/**
* Token
*/
export function validateToken(token: string): TokenValidationResult {
const rules = TOKEN_VALIDATION_RULES.map((rule) => ({
id: rule.id,
label: rule.label,
description: rule.description,
passed: rule.validate(token),
}))
const isValid = rules.every((rule) => rule.passed)
return {
isValid,
rules,
}
}
/**
*
*/
export function getFailedRules(token: string): string[] {
const result = validateToken(token)
return result.rules.filter((rule) => !rule.passed).map((rule) => rule.label)
}
/**
* Token
*/
export function isTokenValid(token: string): boolean {
return validateToken(token).isValid
}

View File

@ -0,0 +1,6 @@
import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

View File

@ -0,0 +1,26 @@
/**
* MaiBot Dashboard
*
*
*
*/
export const APP_VERSION = '1.0.0'
export const APP_NAME = 'MaiBot Dashboard'
export const APP_FULL_NAME = `${APP_NAME} v${APP_VERSION}`
/**
*
*/
export const getVersionInfo = () => ({
version: APP_VERSION,
name: APP_NAME,
fullName: APP_FULL_NAME,
buildDate: import.meta.env.VITE_BUILD_DATE || new Date().toISOString().split('T')[0],
buildEnv: import.meta.env.MODE,
})
/**
*
*/
export const formatVersion = (prefix = 'v') => `${prefix}${APP_VERSION}`

View File

@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client'
import { RouterProvider } from '@tanstack/react-router'
import './index.css'
import { router } from './router'
import { AssetStoreProvider } from './components/asset-provider'
import { ThemeProvider } from './components/theme-provider'
import { AnimationProvider } from './components/animation-provider'
import { TourProvider, TourRenderer } from './components/tour'
@ -12,15 +13,17 @@ import { ErrorBoundary } from './components/error-boundary'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<ErrorBoundary>
<ThemeProvider defaultTheme="system">
<AnimationProvider>
<TourProvider>
<RouterProvider router={router} />
<TourRenderer />
<Toaster />
</TourProvider>
</AnimationProvider>
</ThemeProvider>
<AssetStoreProvider>
<ThemeProvider defaultTheme="system">
<AnimationProvider>
<TourProvider>
<RouterProvider router={router} />
<TourRenderer />
<Toaster />
</TourProvider>
</AnimationProvider>
</ThemeProvider>
</AssetStoreProvider>
</ErrorBoundary>
</StrictMode>
)

View File

@ -341,7 +341,7 @@ export function AnnualReportPage() {
contentStyle={{ borderRadius: '8px', border: 'none', boxShadow: '0 4px 12px rgba(0,0,0,0.1)' }}
cursor={{ fill: 'transparent' }}
/>
<Bar dataKey="count" fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} />
<Bar dataKey="count" fill="hsl(var(--color-primary))" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</CardContent>

View File

@ -2,7 +2,6 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
BotInfoSection,
PersonalitySection,
ChatSection,
DreamSection,
LPMMSection,
LogSection,
@ -69,6 +68,11 @@ import { useAutoSave, useConfigAutoSave } from './bot/hooks'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Button } from '@/components/ui/button'
// 导入动态表单和 Hook 系统
import { DynamicConfigForm } from '@/components/dynamic-form'
import { fieldHooks } from '@/lib/field-hooks'
import { ChatSectionHook } from '@/routes/config/bot/hooks'
// ==================== 常量定义 ====================
/** Toast 显示前的延迟时间 (毫秒) */
const TOAST_DISPLAY_DELAY = 500
@ -308,6 +312,13 @@ function BotConfigPageContent() {
loadConfig()
}, [loadConfig])
useEffect(() => {
fieldHooks.register('chat', ChatSectionHook, 'replace')
return () => {
fieldHooks.unregister('chat')
}
}, [])
// 使用模块化的 useAutoSave hook
const { triggerAutoSave, cancelPendingAutoSave } = useAutoSave(
initialLoadRef.current,
@ -613,7 +624,6 @@ function BotConfigPageContent() {
}
}}
language="toml"
theme="dark"
height="calc(100vh - 280px)"
minHeight="500px"
placeholder="TOML 配置内容"
@ -652,7 +662,24 @@ function BotConfigPageContent() {
{/* 聊天配置 */}
<TabsContent value="chat" className="space-y-4">
{chatConfig && <ChatSection config={chatConfig} onChange={setChatConfig} />}
{chatConfig && (
<DynamicConfigForm
schema={{
className: 'ChatConfig',
classDoc: '聊天配置',
fields: [],
nested: {},
}}
values={{ chat: chatConfig }}
onChange={(field, value) => {
if (field === 'chat') {
setChatConfig(value as ChatConfig)
setHasUnsavedChanges(true)
}
}}
hooks={fieldHooks}
/>
)}
</TabsContent>
{/* 表达配置 */}

View File

@ -0,0 +1,15 @@
import type { FieldHookComponent } from '@/lib/field-hooks'
import { BotInfoSection } from '../sections/BotInfoSection'
/**
* BotInfoSection as a Field Hook Component
* This component replaces the entire 'bot' nested config section rendering
*/
export const BotInfoSectionHook: FieldHookComponent = ({ value, onChange }) => {
return (
<BotInfoSection
config={value as any}
onChange={(newConfig) => onChange?.(newConfig)}
/>
)
}

View File

@ -0,0 +1,617 @@
import React, { useState, useEffect, useMemo } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Slider } from '@/components/ui/slider'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover'
import { Plus, Trash2, Eye, Clock } from 'lucide-react'
import type { FieldHookComponent } from '@/lib/field-hooks'
import type { ChatConfig } from '../types'
// 时间选择组件
const TimeRangePicker = React.memo(function TimeRangePicker({
value,
onChange,
}: {
value: string
onChange: (value: string) => void
}) {
// 解析初始值
const parsedValue = useMemo(() => {
const parts = value.split('-')
if (parts.length === 2) {
const [start, end] = parts
const [sh, sm] = start.split(':')
const [eh, em] = end.split(':')
return {
startHour: sh ? sh.padStart(2, '0') : '00',
startMinute: sm ? sm.padStart(2, '0') : '00',
endHour: eh ? eh.padStart(2, '0') : '23',
endMinute: em ? em.padStart(2, '0') : '59',
}
}
return {
startHour: '00',
startMinute: '00',
endHour: '23',
endMinute: '59',
}
}, [value])
const [startHour, setStartHour] = useState(parsedValue.startHour)
const [startMinute, setStartMinute] = useState(parsedValue.startMinute)
const [endHour, setEndHour] = useState(parsedValue.endHour)
const [endMinute, setEndMinute] = useState(parsedValue.endMinute)
// 当value变化时同步状态
useEffect(() => {
setStartHour(parsedValue.startHour)
setStartMinute(parsedValue.startMinute)
setEndHour(parsedValue.endHour)
setEndMinute(parsedValue.endMinute)
}, [parsedValue])
const updateTime = (
newStartHour: string,
newStartMinute: string,
newEndHour: string,
newEndMinute: string
) => {
const newValue = `${newStartHour}:${newStartMinute}-${newEndHour}:${newEndMinute}`
onChange(newValue)
}
return (
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" className="w-full justify-start font-mono text-sm">
<Clock className="h-4 w-4 mr-2" />
{value || '选择时间段'}
</Button>
</PopoverTrigger>
<PopoverContent className="w-72 sm:w-80">
<div className="space-y-4">
<div>
<h4 className="font-medium text-sm mb-3"></h4>
<div className="grid grid-cols-2 gap-2 sm:gap-3">
<div>
<Label className="text-xs"></Label>
<Select
value={startHour}
onValueChange={(v) => {
setStartHour(v)
updateTime(v, startMinute, endHour, endMinute)
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{Array.from({ length: 24 }, (_, i) => i).map((h) => (
<SelectItem key={h} value={h.toString().padStart(2, '0')}>
{h.toString().padStart(2, '0')}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs"></Label>
<Select
value={startMinute}
onValueChange={(v) => {
setStartMinute(v)
updateTime(startHour, v, endHour, endMinute)
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{Array.from({ length: 60 }, (_, i) => i).map((m) => (
<SelectItem key={m} value={m.toString().padStart(2, '0')}>
{m.toString().padStart(2, '0')}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
<div>
<h4 className="font-medium text-sm mb-3"></h4>
<div className="grid grid-cols-2 gap-2 sm:gap-3">
<div>
<Label className="text-xs"></Label>
<Select
value={endHour}
onValueChange={(v) => {
setEndHour(v)
updateTime(startHour, startMinute, v, endMinute)
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{Array.from({ length: 24 }, (_, i) => i).map((h) => (
<SelectItem key={h} value={h.toString().padStart(2, '0')}>
{h.toString().padStart(2, '0')}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs"></Label>
<Select
value={endMinute}
onValueChange={(v) => {
setEndMinute(v)
updateTime(startHour, startMinute, endHour, v)
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{Array.from({ length: 60 }, (_, i) => i).map((m) => (
<SelectItem key={m} value={m.toString().padStart(2, '0')}>
{m.toString().padStart(2, '0')}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
</div>
</PopoverContent>
</Popover>
)
})
// 预览窗口组件
const RulePreview = React.memo(function RulePreview({ rule }: { rule: { target: string; time: string; value: number } }) {
const previewText = `{ target = "${rule.target}", time = "${rule.time}", value = ${rule.value.toFixed(1)} }`
return (
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" size="sm">
<Eye className="h-4 w-4 mr-1" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-80 sm:w-96">
<div className="space-y-2">
<h4 className="font-medium text-sm"></h4>
<div className="rounded-md bg-muted p-3 font-mono text-xs break-all">
{previewText}
</div>
<p className="text-xs text-muted-foreground">
bot_config.toml
</p>
</div>
</PopoverContent>
</Popover>
)
})
/**
* ChatSection as a Field Hook Component
* This component replaces the entire 'chat' nested config section rendering
*/
export const ChatSectionHook: FieldHookComponent = ({ value, onChange }) => {
// Cast value to ChatConfig (assuming it's the entire chat config object)
const config = value as ChatConfig
// Helper to update config
const updateConfig = (updates: Partial<ChatConfig>) => {
if (onChange) {
onChange({ ...config, ...updates })
}
}
// 添加发言频率规则
const addTalkValueRule = () => {
updateConfig({
talk_value_rules: [
...config.talk_value_rules,
{ target: '', time: '00:00-23:59', value: 1.0 },
],
})
}
// 删除发言频率规则
const removeTalkValueRule = (index: number) => {
updateConfig({
talk_value_rules: config.talk_value_rules.filter((_, i) => i !== index),
})
}
// 更新发言频率规则
const updateTalkValueRule = (
index: number,
field: 'target' | 'time' | 'value',
value: string | number
) => {
const newRules = [...config.talk_value_rules]
newRules[index] = {
...newRules[index],
[field]: value,
}
updateConfig({
talk_value_rules: newRules,
})
}
return (
<div className="rounded-lg border bg-card p-4 sm:p-6 space-y-6">
<div>
<h3 className="text-lg font-semibold mb-4"></h3>
<div className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="talk_value"></Label>
<Input
id="talk_value"
type="number"
step="0.1"
min="0"
max="1"
value={config.talk_value}
onChange={(e) => updateConfig({ talk_value: parseFloat(e.target.value) })}
/>
<p className="text-xs text-muted-foreground"> 0-1</p>
</div>
<div className="grid gap-2">
<Label htmlFor="think_mode"></Label>
<Select
value={config.think_mode || 'classic'}
onValueChange={(value) => updateConfig({ think_mode: value as 'classic' | 'deep' | 'dynamic' })}
>
<SelectTrigger id="think_mode">
<SelectValue placeholder="选择思考模式" />
</SelectTrigger>
<SelectContent>
<SelectItem value="classic"> - </SelectItem>
<SelectItem value="deep"> - </SelectItem>
<SelectItem value="dynamic"> - </SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
</p>
</div>
<div className="flex items-center space-x-2">
<Switch
id="mentioned_bot_reply"
checked={config.mentioned_bot_reply}
onCheckedChange={(checked) =>
updateConfig({ mentioned_bot_reply: checked })
}
/>
<Label htmlFor="mentioned_bot_reply" className="cursor-pointer">
</Label>
</div>
<div className="grid gap-2">
<Label htmlFor="max_context_size"></Label>
<Input
id="max_context_size"
type="number"
min="1"
value={config.max_context_size}
onChange={(e) =>
updateConfig({ max_context_size: parseInt(e.target.value) })
}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="planner_smooth"></Label>
<Input
id="planner_smooth"
type="number"
step="1"
min="0"
value={config.planner_smooth}
onChange={(e) =>
updateConfig({ planner_smooth: parseFloat(e.target.value) })
}
/>
<p className="text-xs text-muted-foreground">
planner 1-50
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="plan_reply_log_max_per_chat"></Label>
<Input
id="plan_reply_log_max_per_chat"
type="number"
step="1"
min="100"
value={config.plan_reply_log_max_per_chat ?? 1024}
onChange={(e) =>
updateConfig({ plan_reply_log_max_per_chat: parseInt(e.target.value) })
}
/>
<p className="text-xs text-muted-foreground">
Plan/Reply
</p>
</div>
<div className="flex items-center space-x-2">
<Switch
id="llm_quote"
checked={config.llm_quote ?? false}
onCheckedChange={(checked) =>
updateConfig({ llm_quote: checked })
}
/>
<Label htmlFor="llm_quote" className="cursor-pointer">
LLM
</Label>
</div>
<p className="text-xs text-muted-foreground -mt-2 ml-10">
LLM
</p>
<div className="flex items-center space-x-2">
<Switch
id="enable_talk_value_rules"
checked={config.enable_talk_value_rules}
onCheckedChange={(checked) =>
updateConfig({ enable_talk_value_rules: checked })
}
/>
<Label htmlFor="enable_talk_value_rules" className="cursor-pointer">
</Label>
</div>
</div>
</div>
{/* 动态发言频率规则配置 */}
{config.enable_talk_value_rules && (
<div className="border-t pt-6">
<div className="flex items-center justify-between mb-4">
<div>
<h4 className="text-base font-semibold"></h4>
<p className="text-xs text-muted-foreground mt-1">
ID
</p>
</div>
<Button onClick={addTalkValueRule} size="sm">
<Plus className="h-4 w-4 mr-1" />
</Button>
</div>
{config.talk_value_rules && config.talk_value_rules.length > 0 ? (
<div className="space-y-4">
{config.talk_value_rules.map((rule, index) => (
<div key={index} className="rounded-lg border p-4 bg-muted/50 space-y-4">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-muted-foreground">
#{index + 1}
</span>
<div className="flex items-center gap-2">
<RulePreview rule={rule} />
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="ghost" size="sm">
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
#{index + 1}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={() => removeTalkValueRule(index)}>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
<div className="space-y-4">
{/* 配置类型选择 */}
<div className="grid gap-2">
<Label className="text-xs font-medium"></Label>
<Select
value={rule.target === '' ? 'global' : 'specific'}
onValueChange={(value) => {
if (value === 'global') {
updateTalkValueRule(index, 'target', '')
} else {
updateTalkValueRule(index, 'target', 'qq::group')
}
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="global"></SelectItem>
<SelectItem value="specific"></SelectItem>
</SelectContent>
</Select>
</div>
{/* 详细配置选项 - 只在非全局时显示 */}
{rule.target !== '' && (() => {
const parts = rule.target.split(':')
const platform = parts[0] || 'qq'
const chatId = parts[1] || ''
const chatType = parts[2] || 'group'
return (
<div className="grid gap-4 p-3 sm:p-4 rounded-lg bg-muted/50">
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<div className="grid gap-2">
<Label className="text-xs font-medium"></Label>
<Select
value={platform}
onValueChange={(value) => {
updateTalkValueRule(index, 'target', `${value}:${chatId}:${chatType}`)
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="qq">QQ</SelectItem>
<SelectItem value="wx"></SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid gap-2">
<Label className="text-xs font-medium"> ID</Label>
<Input
value={chatId}
onChange={(e) => {
updateTalkValueRule(index, 'target', `${platform}:${e.target.value}:${chatType}`)
}}
placeholder="输入群 ID"
className="font-mono text-sm"
/>
</div>
<div className="grid gap-2">
<Label className="text-xs font-medium"></Label>
<Select
value={chatType}
onValueChange={(value) => {
updateTalkValueRule(index, 'target', `${platform}:${chatId}:${value}`)
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="group">group</SelectItem>
<SelectItem value="private">private</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<p className="text-xs text-muted-foreground">
ID{rule.target || '(未设置)'}
</p>
</div>
)
})()}
{/* 时间段选择器 */}
<div className="grid gap-2">
<Label className="text-xs font-medium"> (Time)</Label>
<TimeRangePicker
value={rule.time}
onChange={(v) => updateTalkValueRule(index, 'time', v)}
/>
<p className="text-xs text-muted-foreground">
23:00-02:00
</p>
</div>
{/* 发言频率滑块 */}
<div className="grid gap-3">
<div className="flex items-center justify-between">
<Label htmlFor={`rule-value-${index}`} className="text-xs font-medium">
(Value)
</Label>
<Input
id={`rule-value-${index}`}
type="number"
step="0.01"
min="0.01"
max="1"
value={rule.value}
onChange={(e) => {
const val = parseFloat(e.target.value)
if (!isNaN(val)) {
updateTalkValueRule(index, 'value', Math.max(0.01, Math.min(1, val)))
}
}}
className="w-20 h-8 text-xs"
/>
</div>
<Slider
value={[rule.value]}
onValueChange={(values) =>
updateTalkValueRule(index, 'value', values[0])
}
min={0.01}
max={1}
step={0.01}
className="w-full"
/>
<div className="flex justify-between text-xs text-muted-foreground">
<span>0.01 ()</span>
<span>0.5</span>
<span>1.0 ()</span>
</div>
</div>
</div>
</div>
))}
</div>
) : (
<div className="text-center py-8 text-muted-foreground">
<p className="text-sm">"添加规则"</p>
</div>
)}
<div className="mt-4 p-4 bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg">
<h5 className="text-sm font-semibold text-blue-900 dark:text-blue-100 mb-2">
📝
</h5>
<ul className="text-xs text-blue-800 dark:text-blue-200 space-y-1">
<li> <strong>Target </strong></li>
<li> <strong>Target </strong>platform:id:type</li>
<li> <strong></strong></li>
<li> <strong></strong> 23:00-02:00 112</li>
<li> <strong></strong> 0-10 1 </li>
</ul>
</div>
</div>
)}
</div>
)
}

View File

@ -0,0 +1,15 @@
import type { FieldHookComponent } from '@/lib/field-hooks'
import { DebugSection } from '../sections/DebugSection'
/**
* DebugSection as a Field Hook Component
* This component replaces the entire 'debug' nested config section rendering
*/
export const DebugSectionHook: FieldHookComponent = ({ value, onChange }) => {
return (
<DebugSection
config={value as any}
onChange={(newConfig) => onChange?.(newConfig)}
/>
)
}

View File

@ -0,0 +1,15 @@
import type { FieldHookComponent } from '@/lib/field-hooks'
import { ExpressionSection } from '../sections/ExpressionSection'
/**
* ExpressionSection as a Field Hook Component
* This component replaces the entire 'expression' nested config section rendering
*/
export const ExpressionSectionHook: FieldHookComponent = ({ value, onChange }) => {
return (
<ExpressionSection
config={value as any}
onChange={(newConfig) => onChange?.(newConfig)}
/>
)
}

View File

@ -0,0 +1,15 @@
import type { FieldHookComponent } from '@/lib/field-hooks'
import { PersonalitySection } from '../sections/PersonalitySection'
/**
* PersonalitySection as a Field Hook Component
* This component replaces the entire 'personality' nested config section rendering
*/
export const PersonalitySectionHook: FieldHookComponent = ({ value, onChange }) => {
return (
<PersonalitySection
config={value as any}
onChange={(newConfig) => onChange?.(newConfig)}
/>
)
}

View File

@ -4,3 +4,8 @@
export { useAutoSave, useConfigAutoSave } from './useAutoSave'
export type { UseAutoSaveOptions, UseAutoSaveReturn, AutoSaveState } from './useAutoSave'
export { ChatSectionHook } from './ChatSectionHook'
export { PersonalitySectionHook } from './PersonalitySectionHook'
export { DebugSectionHook } from './DebugSectionHook'
export { ExpressionSectionHook } from './ExpressionSectionHook'
export { BotInfoSectionHook } from './BotInfoSectionHook'

View File

@ -58,9 +58,13 @@ import { SharePackDialog } from '@/components/share-pack-dialog'
// 导入模块化的类型定义和组件
import type { ModelInfo, ProviderConfig, ModelTaskConfig, TaskConfig } from './model/types'
import { TaskConfigCard, Pagination, ModelTable, ModelCardList } from './model/components'
import { Pagination, ModelTable, ModelCardList } from './model/components'
import { useModelTour, useModelFetcher, useModelAutoSave } from './model/hooks'
// 导入动态表单和 Hook 系统
import { DynamicConfigForm } from '@/components/dynamic-form'
import { fieldHooks } from '@/lib/field-hooks'
// 主导出组件:包装 RestartProvider
export function ModelConfigPage() {
return (
@ -75,7 +79,6 @@ function ModelConfigPageContent() {
const [models, setModels] = useState<ModelInfo[]>([])
const [providers, setProviders] = useState<string[]>([])
const [providerConfigs, setProviderConfigs] = useState<ProviderConfig[]>([])
const [modelNames, setModelNames] = useState<string[]>([])
const [taskConfig, setTaskConfig] = useState<ModelTaskConfig | null>(null)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
@ -179,7 +182,6 @@ function ModelConfigPageContent() {
const config = await getModelConfig()
const modelList = (config.models as ModelInfo[]) || []
setModels(modelList)
setModelNames(modelList.map((m) => m.name))
const providerList = (config.api_providers as ProviderConfig[]) || []
setProviders(providerList.map((p) => p.name))
@ -429,8 +431,6 @@ function ModelConfigPageContent() {
}
setModels(newModels)
// 立即更新模型名称列表
setModelNames(newModels.map((m) => m.name))
// 如果模型名称发生变化,更新任务配置中对该模型的引用
if (oldModelName && oldModelName !== modelToSave.name && taskConfig) {
@ -488,8 +488,6 @@ function ModelConfigPageContent() {
if (deletingIndex !== null) {
const newModels = models.filter((_, i) => i !== deletingIndex)
setModels(newModels)
// 立即更新模型名称列表
setModelNames(newModels.map((m) => m.name))
// 重新检查任务配置问题
checkTaskConfigIssues(taskConfig, newModels)
toast({
@ -542,8 +540,6 @@ function ModelConfigPageContent() {
const deletedCount = selectedModels.size
const newModels = models.filter((_, index) => !selectedModels.has(index))
setModels(newModels)
// 立即更新模型名称列表
setModelNames(newModels.map((m) => m.name))
// 重新检查任务配置问题
checkTaskConfigIssues(taskConfig, newModels)
setSelectedModels(new Set())
@ -554,53 +550,6 @@ function ModelConfigPageContent() {
})
}
// 更新任务配置
const updateTaskConfig = (
taskName: keyof ModelTaskConfig,
field: keyof TaskConfig,
value: string[] | number | string
) => {
if (!taskConfig) return
// 检测 embedding 模型列表变化
if (taskName === 'embedding' && field === 'model_list' && Array.isArray(value)) {
const previousModels = previousEmbeddingModelsRef.current
const newModels = value as string[]
// 判断是否有变化(添加、删除或替换)
const hasChanges =
previousModels.length !== newModels.length ||
previousModels.some(model => !newModels.includes(model)) ||
newModels.some(model => !previousModels.includes(model))
if (hasChanges && previousModels.length > 0) {
// 存储待更新的配置
pendingEmbeddingUpdateRef.current = { field, value }
// 显示警告对话框
setEmbeddingWarningOpen(true)
return
}
}
// 正常更新配置
const newTaskConfig = {
...taskConfig,
[taskName]: {
...taskConfig[taskName],
[field]: value,
},
}
setTaskConfig(newTaskConfig)
// 重新检查任务配置问题
checkTaskConfigIssues(newTaskConfig, models)
// 如果是 embedding 模型列表,更新 ref
if (taskName === 'embedding' && field === 'model_list' && Array.isArray(value)) {
previousEmbeddingModelsRef.current = [...(value as string[])]
}
}
// 确认更新嵌入模型
const handleConfirmEmbeddingChange = () => {
if (!taskConfig || !pendingEmbeddingUpdateRef.current) return
@ -918,101 +867,22 @@ function ModelConfigPageContent() {
</p>
{taskConfig && (
<div className="grid gap-4 sm:gap-6">
{/* Utils 任务 */}
<TaskConfigCard
title="组件模型 (utils)"
description="用于表情包、取名、关系、情绪变化等组件"
taskConfig={taskConfig.utils}
modelNames={modelNames}
onChange={(field, value) => updateTaskConfig('utils', field, value)}
dataTour="task-model-select"
/>
{/* Tool Use 任务 */}
<TaskConfigCard
title="工具调用模型 (tool_use)"
description="需要使用支持工具调用的模型"
taskConfig={taskConfig.tool_use}
modelNames={modelNames}
onChange={(field, value) => updateTaskConfig('tool_use', field, value)}
/>
{/* Replyer 任务 */}
<TaskConfigCard
title="首要回复模型 (replyer)"
description="用于表达器和表达方式学习"
taskConfig={taskConfig.replyer}
modelNames={modelNames}
onChange={(field, value) => updateTaskConfig('replyer', field, value)}
/>
{/* Planner 任务 */}
<TaskConfigCard
title="决策模型 (planner)"
description="负责决定麦麦该什么时候回复"
taskConfig={taskConfig.planner}
modelNames={modelNames}
onChange={(field, value) => updateTaskConfig('planner', field, value)}
/>
{/* VLM 任务 */}
<TaskConfigCard
title="图像识别模型 (vlm)"
description="视觉语言模型"
taskConfig={taskConfig.vlm}
modelNames={modelNames}
onChange={(field, value) => updateTaskConfig('vlm', field, value)}
hideTemperature
/>
{/* Voice 任务 */}
<TaskConfigCard
title="语音识别模型 (voice)"
description="语音转文字"
taskConfig={taskConfig.voice}
modelNames={modelNames}
onChange={(field, value) => updateTaskConfig('voice', field, value)}
hideTemperature
hideMaxTokens
/>
{/* Embedding 任务 */}
<TaskConfigCard
title="嵌入模型 (embedding)"
description="用于向量化"
taskConfig={taskConfig.embedding}
modelNames={modelNames}
onChange={(field, value) => updateTaskConfig('embedding', field, value)}
hideTemperature
hideMaxTokens
/>
{/* LPMM 相关任务 */}
<div className="space-y-4">
<h3 className="text-lg font-semibold">LPMM </h3>
<TaskConfigCard
title="实体提取模型 (lpmm_entity_extract)"
description="从文本中提取实体"
taskConfig={taskConfig.lpmm_entity_extract}
modelNames={modelNames}
onChange={(field, value) =>
updateTaskConfig('lpmm_entity_extract', field, value)
}
/>
<TaskConfigCard
title="RDF 构建模型 (lpmm_rdf_build)"
description="构建知识图谱"
taskConfig={taskConfig.lpmm_rdf_build}
modelNames={modelNames}
onChange={(field, value) =>
updateTaskConfig('lpmm_rdf_build', field, value)
}
/>
</div>
</div>
<DynamicConfigForm
schema={{
className: 'TaskConfig',
classDoc: '任务配置',
fields: [],
nested: {},
}}
values={{ taskConfig }}
onChange={(field, value) => {
if (field === 'taskConfig') {
setTaskConfig(value as ModelTaskConfig)
setHasUnsavedChanges(true)
}
}}
hooks={fieldHooks}
/>
)}
</TabsContent>
</Tabs>

View File

@ -403,15 +403,15 @@ function IndexPageContent() {
const chartConfig = {
requests: {
label: '请求数',
color: 'hsl(var(--chart-1))',
color: 'hsl(var(--color-chart-1))',
},
cost: {
label: '花费(¥)',
color: 'hsl(var(--chart-2))',
color: 'hsl(var(--color-chart-2))',
},
tokens: {
label: 'Tokens',
color: 'hsl(var(--chart-3))',
color: 'hsl(var(--color-chart-3))',
},
} satisfies ChartConfig
@ -738,17 +738,17 @@ function IndexPageContent() {
<CardContent>
<ChartContainer config={chartConfig} className="h-[300px] sm:h-[400px] w-full aspect-auto">
<LineChart data={hourly_data}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--muted-foreground) / 0.2)" />
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--color-muted-foreground) / 0.2)" />
<XAxis
dataKey="timestamp"
tickFormatter={(value) => formatDateTime(value)}
angle={-45}
textAnchor="end"
height={60}
stroke="hsl(var(--muted-foreground))"
tick={{ fill: 'hsl(var(--muted-foreground))' }}
stroke="hsl(var(--color-muted-foreground))"
tick={{ fill: 'hsl(var(--color-muted-foreground))' }}
/>
<YAxis stroke="hsl(var(--muted-foreground))" tick={{ fill: 'hsl(var(--muted-foreground))' }} />
<YAxis stroke="hsl(var(--color-muted-foreground))" tick={{ fill: 'hsl(var(--color-muted-foreground))' }} />
<ChartTooltip
content={<ChartTooltipContent labelFormatter={(value) => formatDateTime(value as string)} />}
/>
@ -772,17 +772,17 @@ function IndexPageContent() {
<CardContent>
<ChartContainer config={chartConfig} className="h-[250px] sm:h-[300px] w-full aspect-auto">
<BarChart data={hourly_data}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--muted-foreground) / 0.2)" />
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--color-muted-foreground) / 0.2)" />
<XAxis
dataKey="timestamp"
tickFormatter={(value) => formatDateTime(value)}
angle={-45}
textAnchor="end"
height={60}
stroke="hsl(var(--muted-foreground))"
tick={{ fill: 'hsl(var(--muted-foreground))' }}
stroke="hsl(var(--color-muted-foreground))"
tick={{ fill: 'hsl(var(--color-muted-foreground))' }}
/>
<YAxis stroke="hsl(var(--muted-foreground))" tick={{ fill: 'hsl(var(--muted-foreground))' }} />
<YAxis stroke="hsl(var(--color-muted-foreground))" tick={{ fill: 'hsl(var(--color-muted-foreground))' }} />
<ChartTooltip
content={<ChartTooltipContent labelFormatter={(value) => formatDateTime(value as string)} />}
/>
@ -800,17 +800,17 @@ function IndexPageContent() {
<CardContent>
<ChartContainer config={chartConfig} className="h-[250px] sm:h-[300px] w-full aspect-auto">
<BarChart data={hourly_data}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--muted-foreground) / 0.2)" />
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--color-muted-foreground) / 0.2)" />
<XAxis
dataKey="timestamp"
tickFormatter={(value) => formatDateTime(value)}
angle={-45}
textAnchor="end"
height={60}
stroke="hsl(var(--muted-foreground))"
tick={{ fill: 'hsl(var(--muted-foreground))' }}
stroke="hsl(var(--color-muted-foreground))"
tick={{ fill: 'hsl(var(--color-muted-foreground))' }}
/>
<YAxis stroke="hsl(var(--muted-foreground))" tick={{ fill: 'hsl(var(--muted-foreground))' }} />
<YAxis stroke="hsl(var(--color-muted-foreground))" tick={{ fill: 'hsl(var(--color-muted-foreground))' }} />
<ChartTooltip
content={<ChartTooltipContent labelFormatter={(value) => formatDateTime(value as string)} />}
/>
@ -889,7 +889,7 @@ function IndexPageContent() {
<div
className="w-3 h-3 rounded-full ml-2 flex-shrink-0"
style={{
backgroundColor: `hsl(var(--chart-${(index % 5) + 1}))`,
backgroundColor: `hsl(var(--color-chart-${(index % 5) + 1}))`,
}}
/>
</div>
@ -992,28 +992,28 @@ function IndexPageContent() {
config={{
requests: {
label: '请求数',
color: 'hsl(var(--chart-1))',
color: 'hsl(var(--color-chart-1))',
},
cost: {
label: '花费(¥)',
color: 'hsl(var(--chart-2))',
color: 'hsl(var(--color-chart-2))',
},
}}
className="h-[400px] sm:h-[500px] w-full aspect-auto"
>
<BarChart data={daily_data}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--muted-foreground) / 0.2)" />
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--color-muted-foreground) / 0.2)" />
<XAxis
dataKey="timestamp"
tickFormatter={(value) => {
const date = new Date(value)
return `${date.getMonth() + 1}/${date.getDate()}`
}}
stroke="hsl(var(--muted-foreground))"
tick={{ fill: 'hsl(var(--muted-foreground))' }}
stroke="hsl(var(--color-muted-foreground))"
tick={{ fill: 'hsl(var(--color-muted-foreground))' }}
/>
<YAxis yAxisId="left" stroke="hsl(var(--muted-foreground))" tick={{ fill: 'hsl(var(--muted-foreground))' }} />
<YAxis yAxisId="right" orientation="right" stroke="hsl(var(--muted-foreground))" tick={{ fill: 'hsl(var(--muted-foreground))' }} />
<YAxis yAxisId="left" stroke="hsl(var(--color-muted-foreground))" tick={{ fill: 'hsl(var(--color-muted-foreground))' }} />
<YAxis yAxisId="right" orientation="right" stroke="hsl(var(--color-muted-foreground))" tick={{ fill: 'hsl(var(--color-muted-foreground))' }} />
<ChartTooltip
content={
<ChartTooltipContent

View File

@ -602,20 +602,19 @@ function PluginConfigEditor({ plugin, onBack }: PluginConfigEditorProps) {
</AlertDescription>
</Alert>
<CodeEditor
value={sourceCode}
onChange={(value) => {
setSourceCode(value)
if (hasTomlError) {
setHasTomlError(false)
}
}}
language="toml"
theme="dark"
height="calc(100vh - 350px)"
minHeight="500px"
placeholder="TOML 配置内容"
/>
<CodeEditor
value={sourceCode}
onChange={(value) => {
setSourceCode(value)
if (hasTomlError) {
setHasTomlError(false)
}
}}
language="toml"
height="calc(100vh - 350px)"
minHeight="500px"
placeholder="TOML 配置内容"
/>
</div>
)}

File diff suppressed because it is too large Load Diff

View File

@ -16,29 +16,29 @@
/* 拖放区域样式 */
.uppy-Dashboard-AddFiles {
border: 2px dashed hsl(var(--border)) !important;
border: 2px dashed hsl(var(--color-border)) !important;
border-radius: 0.5rem !important;
background: hsl(var(--muted) / 0.3) !important;
background: hsl(var(--color-muted) / 0.3) !important;
transition: all 0.2s ease;
}
.uppy-Dashboard-AddFiles:hover {
border-color: hsl(var(--primary)) !important;
background: hsl(var(--muted) / 0.5) !important;
border-color: hsl(var(--color-primary)) !important;
background: hsl(var(--color-muted) / 0.5) !important;
}
.uppy-Dashboard-AddFiles-title {
color: hsl(var(--foreground)) !important;
color: hsl(var(--color-foreground)) !important;
font-weight: 500 !important;
}
.uppy-Dashboard-AddFiles-info {
color: hsl(var(--muted-foreground)) !important;
color: hsl(var(--color-muted-foreground)) !important;
}
/* 按钮样式 */
.uppy-Dashboard-browse {
color: hsl(var(--primary)) !important;
color: hsl(var(--color-primary)) !important;
font-weight: 500 !important;
}
@ -52,63 +52,63 @@
}
.uppy-Dashboard-Item {
border-bottom-color: hsl(var(--border)) !important;
border-bottom-color: hsl(var(--color-border)) !important;
}
.uppy-Dashboard-Item-name {
color: hsl(var(--foreground)) !important;
color: hsl(var(--color-foreground)) !important;
}
.uppy-Dashboard-Item-status {
color: hsl(var(--muted-foreground)) !important;
color: hsl(var(--color-muted-foreground)) !important;
}
/* 进度条样式 */
.uppy-StatusBar {
background: hsl(var(--muted)) !important;
border-top: 1px solid hsl(var(--border)) !important;
background: hsl(var(--color-muted)) !important;
border-top: 1px solid hsl(var(--color-border)) !important;
}
.uppy-StatusBar-progress {
background: hsl(var(--primary)) !important;
background: hsl(var(--color-primary)) !important;
}
.uppy-StatusBar-content {
color: hsl(var(--foreground)) !important;
color: hsl(var(--color-foreground)) !important;
}
.uppy-StatusBar-actionBtn--upload {
background: hsl(var(--primary)) !important;
color: hsl(var(--primary-foreground)) !important;
background: hsl(var(--color-primary)) !important;
color: hsl(var(--color-primary-foreground)) !important;
border-radius: 0.375rem !important;
font-weight: 500 !important;
padding: 0.5rem 1rem !important;
}
.uppy-StatusBar-actionBtn--upload:hover {
background: hsl(var(--primary) / 0.9) !important;
background: hsl(var(--color-primary) / 0.9) !important;
}
/* Note 提示文字样式 */
.uppy-Dashboard-note {
color: hsl(var(--muted-foreground)) !important;
color: hsl(var(--color-muted-foreground)) !important;
font-size: 0.75rem !important;
}
/* 暗色主题适配 */
[data-uppy-theme="dark"] .uppy-Dashboard-AddFiles,
.dark .uppy-Dashboard-AddFiles {
background: hsl(var(--muted) / 0.2) !important;
background: hsl(var(--color-muted) / 0.2) !important;
}
[data-uppy-theme="dark"] .uppy-Dashboard-AddFiles-title,
.dark .uppy-Dashboard-AddFiles-title {
color: hsl(var(--foreground)) !important;
color: hsl(var(--color-foreground)) !important;
}
[data-uppy-theme="dark"] .uppy-StatusBar,
.dark .uppy-StatusBar {
background: hsl(var(--muted) / 0.5) !important;
background: hsl(var(--color-muted) / 0.5) !important;
}
/* 移除 Uppy 自带的边框和阴影 */
@ -124,7 +124,7 @@
/* 删除按钮样式 */
.uppy-Dashboard-Item-action--remove {
color: hsl(var(--destructive)) !important;
color: hsl(var(--color-destructive)) !important;
}
.uppy-Dashboard-Item-action--remove:hover {
@ -137,7 +137,7 @@
}
.uppy-Dashboard-Item.is-error .uppy-Dashboard-Item-progress {
color: hsl(var(--destructive)) !important;
color: hsl(var(--color-destructive)) !important;
}
/* 滚动条样式 */
@ -150,10 +150,10 @@
}
.uppy-Dashboard-files::-webkit-scrollbar-thumb {
background: hsl(var(--muted-foreground) / 0.3);
background: hsl(var(--color-muted-foreground) / 0.3);
border-radius: 3px;
}
.uppy-Dashboard-files::-webkit-scrollbar-thumb:hover {
background: hsl(var(--muted-foreground) / 0.5);
background: hsl(var(--color-muted-foreground) / 0.5);
}

View File

@ -0,0 +1,22 @@
import '@testing-library/jest-dom/vitest'
globalThis.ResizeObserver = class ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
}
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: (query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: () => {},
removeListener: () => {},
addEventListener: () => {},
removeEventListener: () => {},
dispatchEvent: () => {},
}),
})

View File

@ -12,6 +12,8 @@ export type FieldType =
| 'object'
| 'textarea'
export type XWidgetType = 'slider' | 'select' | 'textarea' | 'switch' | 'custom'
export interface FieldSchema {
name: string
type: FieldType
@ -26,6 +28,9 @@ export interface FieldSchema {
type: string
}
properties?: ConfigSchema
'x-widget'?: XWidgetType
'x-icon'?: string
step?: number
}
export interface ConfigSchema {

View File

@ -0,0 +1 @@
declare module '*.css'

View File

@ -5,40 +5,61 @@ export default {
theme: {
extend: {
colors: {
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
border: 'hsl(var(--color-border))',
input: 'hsl(var(--color-input))',
ring: 'hsl(var(--color-ring))',
background: 'hsl(var(--color-background))',
foreground: 'hsl(var(--color-foreground))',
primary: {
DEFAULT: 'hsl(var(--primary))',
foreground: 'hsl(var(--primary-foreground))',
DEFAULT: 'hsl(var(--color-primary))',
foreground: 'hsl(var(--color-primary-foreground))',
},
secondary: {
DEFAULT: 'hsl(var(--secondary))',
foreground: 'hsl(var(--secondary-foreground))',
DEFAULT: 'hsl(var(--color-secondary))',
foreground: 'hsl(var(--color-secondary-foreground))',
},
muted: {
DEFAULT: 'hsl(var(--muted))',
foreground: 'hsl(var(--muted-foreground))',
DEFAULT: 'hsl(var(--color-muted))',
foreground: 'hsl(var(--color-muted-foreground))',
},
accent: {
DEFAULT: 'hsl(var(--accent))',
foreground: 'hsl(var(--accent-foreground))',
DEFAULT: 'hsl(var(--color-accent))',
foreground: 'hsl(var(--color-accent-foreground))',
},
card: {
DEFAULT: 'hsl(var(--card))',
foreground: 'hsl(var(--card-foreground))',
DEFAULT: 'hsl(var(--color-card))',
foreground: 'hsl(var(--color-card-foreground))',
},
popover: {
DEFAULT: 'hsl(var(--popover))',
foreground: 'hsl(var(--popover-foreground))',
DEFAULT: 'hsl(var(--color-popover))',
foreground: 'hsl(var(--color-popover-foreground))',
},
destructive: {
DEFAULT: 'hsl(var(--color-destructive))',
foreground: 'hsl(var(--color-destructive-foreground))',
},
},
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)',
lg: 'var(--visual-radius-lg)',
md: 'var(--visual-radius-md)',
sm: 'var(--visual-radius-sm)',
xl: 'var(--visual-radius-xl)',
full: 'var(--visual-radius-full)',
},
fontFamily: {
sans: 'var(--typography-font-family-base)',
mono: 'var(--typography-font-family-code)',
},
boxShadow: {
sm: 'var(--visual-shadow-sm)',
md: 'var(--visual-shadow-md)',
lg: 'var(--visual-shadow-lg)',
xl: 'var(--visual-shadow-xl)',
},
transitionDuration: {
fast: 'var(--animation-anim-duration-fast)',
normal: 'var(--animation-anim-duration-normal)',
slow: 'var(--animation-anim-duration-slow)',
},
keyframes: {
'slide-in-from-right': {

View File

@ -2,6 +2,7 @@
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
{ "path": "./tsconfig.node.json" },
{ "path": "./tsconfig.vitest.json" }
]
}

View File

@ -0,0 +1,7 @@
{
"extends": "./tsconfig.app.json",
"compilerOptions": {
"types": ["vite/client", "vitest/globals", "@testing-library/jest-dom"]
},
"include": ["src"]
}

View File

@ -23,6 +23,9 @@ export default defineConfig({
'@': path.resolve(__dirname, './src'),
},
},
optimizeDeps: {
include: ['react', 'react-dom'],
},
build: {
rollupOptions: {
output: {

View File

@ -0,0 +1,18 @@
/// <reference types="vitest" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/test/setup.ts',
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
})

View File

@ -1,2 +1 @@
"""Core helpers for MCP Bridge Plugin."""

View File

@ -167,4 +167,3 @@ def legacy_servers_list_to_claude_config(servers_list_json: str) -> str:
if not mcp_servers:
return ""
return json.dumps({"mcpServers": mcp_servers}, ensure_ascii=False, indent=2)

View File

@ -34,28 +34,31 @@ from enum import Enum
# 尝试导入 MaiBot 的 logger如果失败则使用标准 logging
try:
from src.common.logger import get_logger
logger = get_logger("mcp_client")
except ImportError:
# Fallback: 使用标准 logging
logger = logging.getLogger("mcp_client")
if not logger.handlers:
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('[%(levelname)s] %(name)s: %(message)s'))
handler.setFormatter(logging.Formatter("[%(levelname)s] %(name)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
class TransportType(Enum):
"""MCP 传输类型"""
STDIO = "stdio" # 本地进程通信
SSE = "sse" # Server-Sent Events (旧版 HTTP)
HTTP = "http" # HTTP Streamable (新版,推荐)
STDIO = "stdio" # 本地进程通信
SSE = "sse" # Server-Sent Events (旧版 HTTP)
HTTP = "http" # HTTP Streamable (新版,推荐)
STREAMABLE_HTTP = "streamable_http" # HTTP Streamable 的别名
@dataclass
class MCPToolInfo:
"""MCP 工具信息"""
name: str
description: str
input_schema: Dict[str, Any]
@ -65,6 +68,7 @@ class MCPToolInfo:
@dataclass
class MCPResourceInfo:
"""MCP 资源信息"""
uri: str
name: str
description: str
@ -75,6 +79,7 @@ class MCPResourceInfo:
@dataclass
class MCPPromptInfo:
"""MCP 提示模板信息"""
name: str
description: str
arguments: List[Dict[str, Any]] # [{name, description, required}]
@ -84,6 +89,7 @@ class MCPPromptInfo:
@dataclass
class MCPServerConfig:
"""MCP 服务器配置"""
name: str
enabled: bool = True
transport: TransportType = TransportType.STDIO
@ -99,6 +105,7 @@ class MCPServerConfig:
@dataclass
class MCPCallResult:
"""MCP 工具调用结果"""
success: bool
content: Any
error: Optional[str] = None
@ -108,8 +115,9 @@ class MCPCallResult:
class CircuitState(Enum):
"""断路器状态"""
CLOSED = "closed" # 正常状态,允许请求
OPEN = "open" # 熔断状态,拒绝请求
CLOSED = "closed" # 正常状态,允许请求
OPEN = "open" # 熔断状态,拒绝请求
HALF_OPEN = "half_open" # 半开状态,允许少量试探请求
@ -125,9 +133,9 @@ class CircuitBreaker:
"""
# 配置
failure_threshold: int = 5 # 连续失败多少次后熔断
recovery_timeout: float = 60.0 # 熔断后多久尝试恢复(秒)
half_open_max_calls: int = 1 # 半开状态最多允许几次试探调用
failure_threshold: int = 5 # 连续失败多少次后熔断
recovery_timeout: float = 60.0 # 熔断后多久尝试恢复(秒)
half_open_max_calls: int = 1 # 半开状态最多允许几次试探调用
# 状态
state: CircuitState = field(default=CircuitState.CLOSED)
@ -232,6 +240,7 @@ class CircuitBreaker:
@dataclass
class ToolCallStats:
"""工具调用统计"""
tool_key: str
total_calls: int = 0
success_calls: int = 0
@ -282,6 +291,7 @@ class ToolCallStats:
@dataclass
class ServerStats:
"""服务器统计"""
server_name: str
connect_count: int = 0 # 连接次数
disconnect_count: int = 0 # 断开次数
@ -442,9 +452,7 @@ class MCPClientSession:
return False
server_params = StdioServerParameters(
command=self.config.command,
args=self.config.args,
env=self.config.env if self.config.env else None
command=self.config.command, args=self.config.args, env=self.config.env if self.config.env else None
)
self._stdio_context = stdio_client(server_params)
@ -506,6 +514,7 @@ class MCPClientSession:
except Exception as e:
logger.error(f"[{self.server_name}] SSE 连接失败: {e}")
import traceback
logger.debug(f"[{self.server_name}] 详细错误: {traceback.format_exc()}")
await self._cleanup()
return False
@ -551,6 +560,7 @@ class MCPClientSession:
except Exception as e:
logger.error(f"[{self.server_name}] HTTP 连接失败: {e}")
import traceback
logger.debug(f"[{self.server_name}] 详细错误: {traceback.format_exc()}")
await self._cleanup()
return False
@ -568,8 +578,8 @@ class MCPClientSession:
tool_info = MCPToolInfo(
name=tool.name,
description=tool.description or f"MCP tool: {tool.name}",
input_schema=tool.inputSchema if hasattr(tool, 'inputSchema') else {},
server_name=self.server_name
input_schema=tool.inputSchema if hasattr(tool, "inputSchema") else {},
server_name=self.server_name,
)
self._tools.append(tool_info)
# 初始化工具统计
@ -591,10 +601,7 @@ class MCPClientSession:
return False
try:
result = await asyncio.wait_for(
self._session.list_resources(),
timeout=self.call_timeout
)
result = await asyncio.wait_for(self._session.list_resources(), timeout=self.call_timeout)
self._resources = []
for resource in result.resources:
@ -602,8 +609,8 @@ class MCPClientSession:
uri=str(resource.uri),
name=resource.name or str(resource.uri),
description=resource.description or "",
mime_type=resource.mimeType if hasattr(resource, 'mimeType') else None,
server_name=self.server_name
mime_type=resource.mimeType if hasattr(resource, "mimeType") else None,
server_name=self.server_name,
)
self._resources.append(resource_info)
logger.debug(f"[{self.server_name}] 发现资源: {resource_info.uri}")
@ -633,28 +640,27 @@ class MCPClientSession:
return False
try:
result = await asyncio.wait_for(
self._session.list_prompts(),
timeout=self.call_timeout
)
result = await asyncio.wait_for(self._session.list_prompts(), timeout=self.call_timeout)
self._prompts = []
for prompt in result.prompts:
# 解析参数
arguments = []
if hasattr(prompt, 'arguments') and prompt.arguments:
if hasattr(prompt, "arguments") and prompt.arguments:
for arg in prompt.arguments:
arguments.append({
"name": arg.name,
"description": arg.description or "",
"required": arg.required if hasattr(arg, 'required') else False,
})
arguments.append(
{
"name": arg.name,
"description": arg.description or "",
"required": arg.required if hasattr(arg, "required") else False,
}
)
prompt_info = MCPPromptInfo(
name=prompt.name,
description=prompt.description or f"MCP prompt: {prompt.name}",
arguments=arguments,
server_name=self.server_name
server_name=self.server_name,
)
self._prompts.append(prompt_info)
logger.debug(f"[{self.server_name}] 发现提示模板: {prompt.name}")
@ -686,35 +692,25 @@ class MCPClientSession:
start_time = time.time()
if not self._connected or not self._session:
return MCPCallResult(
success=False,
content=None,
error=f"服务器 {self.server_name} 未连接"
)
return MCPCallResult(success=False, content=None, error=f"服务器 {self.server_name} 未连接")
if not self._supports_resources:
return MCPCallResult(
success=False,
content=None,
error=f"服务器 {self.server_name} 不支持 Resources 功能"
)
return MCPCallResult(success=False, content=None, error=f"服务器 {self.server_name} 不支持 Resources 功能")
try:
result = await asyncio.wait_for(
self._session.read_resource(uri),
timeout=self.call_timeout
)
result = await asyncio.wait_for(self._session.read_resource(uri), timeout=self.call_timeout)
duration_ms = (time.time() - start_time) * 1000
# 处理返回内容
content_parts = []
for content in result.contents:
if hasattr(content, 'text'):
if hasattr(content, "text"):
content_parts.append(content.text)
elif hasattr(content, 'blob'):
elif hasattr(content, "blob"):
# 二进制数据,返回 base64 或提示
import base64
blob_data = content.blob
if len(blob_data) < 10000: # 小于 10KB 返回 base64
content_parts.append(f"[base64]{base64.b64encode(blob_data).decode()}")
@ -724,28 +720,18 @@ class MCPClientSession:
content_parts.append(str(content))
return MCPCallResult(
success=True,
content="\n".join(content_parts) if content_parts else "",
duration_ms=duration_ms
success=True, content="\n".join(content_parts) if content_parts else "", duration_ms=duration_ms
)
except asyncio.TimeoutError:
duration_ms = (time.time() - start_time) * 1000
return MCPCallResult(
success=False,
content=None,
error=f"读取资源超时({self.call_timeout}秒)",
duration_ms=duration_ms
success=False, content=None, error=f"读取资源超时({self.call_timeout}秒)", duration_ms=duration_ms
)
except Exception as e:
duration_ms = (time.time() - start_time) * 1000
logger.error(f"[{self.server_name}] 读取资源 {uri} 失败: {e}")
return MCPCallResult(
success=False,
content=None,
error=str(e),
duration_ms=duration_ms
)
return MCPCallResult(success=False, content=None, error=str(e), duration_ms=duration_ms)
async def get_prompt(self, name: str, arguments: Optional[Dict[str, str]] = None) -> MCPCallResult:
"""v1.2.0: 获取提示模板的内容
@ -760,23 +746,14 @@ class MCPClientSession:
start_time = time.time()
if not self._connected or not self._session:
return MCPCallResult(
success=False,
content=None,
error=f"服务器 {self.server_name} 未连接"
)
return MCPCallResult(success=False, content=None, error=f"服务器 {self.server_name} 未连接")
if not self._supports_prompts:
return MCPCallResult(
success=False,
content=None,
error=f"服务器 {self.server_name} 不支持 Prompts 功能"
)
return MCPCallResult(success=False, content=None, error=f"服务器 {self.server_name} 不支持 Prompts 功能")
try:
result = await asyncio.wait_for(
self._session.get_prompt(name, arguments=arguments or {}),
timeout=self.call_timeout
self._session.get_prompt(name, arguments=arguments or {}), timeout=self.call_timeout
)
duration_ms = (time.time() - start_time) * 1000
@ -784,10 +761,10 @@ class MCPClientSession:
# 处理返回的消息
messages = []
for msg in result.messages:
role = msg.role if hasattr(msg, 'role') else "unknown"
role = msg.role if hasattr(msg, "role") else "unknown"
content_text = ""
if hasattr(msg, 'content'):
if hasattr(msg.content, 'text'):
if hasattr(msg, "content"):
if hasattr(msg.content, "text"):
content_text = msg.content.text
elif isinstance(msg.content, str):
content_text = msg.content
@ -796,28 +773,18 @@ class MCPClientSession:
messages.append(f"[{role}]: {content_text}")
return MCPCallResult(
success=True,
content="\n\n".join(messages) if messages else "",
duration_ms=duration_ms
success=True, content="\n\n".join(messages) if messages else "", duration_ms=duration_ms
)
except asyncio.TimeoutError:
duration_ms = (time.time() - start_time) * 1000
return MCPCallResult(
success=False,
content=None,
error=f"获取提示模板超时({self.call_timeout}秒)",
duration_ms=duration_ms
success=False, content=None, error=f"获取提示模板超时({self.call_timeout}秒)", duration_ms=duration_ms
)
except Exception as e:
duration_ms = (time.time() - start_time) * 1000
logger.error(f"[{self.server_name}] 获取提示模板 {name} 失败: {e}")
return MCPCallResult(
success=False,
content=None,
error=str(e),
duration_ms=duration_ms
)
return MCPCallResult(success=False, content=None, error=str(e), duration_ms=duration_ms)
async def check_health(self) -> bool:
"""检查连接健康状态(心跳检测)
@ -829,10 +796,7 @@ class MCPClientSession:
try:
# 使用 list_tools 作为心跳检测
await asyncio.wait_for(
self._session.list_tools(),
timeout=10.0
)
await asyncio.wait_for(self._session.list_tools(), timeout=10.0)
self.stats.record_heartbeat()
return True
except Exception as e:
@ -849,12 +813,7 @@ class MCPClientSession:
# v1.7.0: 断路器检查
can_execute, reject_reason = self._circuit_breaker.can_execute()
if not can_execute:
return MCPCallResult(
success=False,
content=None,
error=f"{reject_reason}",
circuit_broken=True
)
return MCPCallResult(success=False, content=None, error=f"{reject_reason}", circuit_broken=True)
# 半开状态下增加试探计数
if self._circuit_breaker.state == CircuitState.HALF_OPEN:
@ -870,8 +829,7 @@ class MCPClientSession:
try:
result = await asyncio.wait_for(
self._session.call_tool(tool_name, arguments=arguments),
timeout=self.call_timeout
self._session.call_tool(tool_name, arguments=arguments), timeout=self.call_timeout
)
duration_ms = (time.time() - start_time) * 1000
@ -879,9 +837,9 @@ class MCPClientSession:
# 处理返回内容
content_parts = []
for content in result.content:
if hasattr(content, 'text'):
if hasattr(content, "text"):
content_parts.append(content.text)
elif hasattr(content, 'data'):
elif hasattr(content, "data"):
content_parts.append(f"[二进制数据: {len(content.data)} bytes]")
else:
content_parts.append(str(content))
@ -896,7 +854,7 @@ class MCPClientSession:
return MCPCallResult(
success=True,
content="\n".join(content_parts) if content_parts else "执行成功(无返回内容)",
duration_ms=duration_ms
duration_ms=duration_ms,
)
except asyncio.TimeoutError:
@ -939,25 +897,25 @@ class MCPClientSession:
self._supports_prompts = False # v1.2.0
try:
if hasattr(self, '_session_context') and self._session_context:
if hasattr(self, "_session_context") and self._session_context:
await self._session_context.__aexit__(None, None, None)
except Exception as e:
logger.debug(f"[{self.server_name}] 关闭会话时出错: {e}")
try:
if hasattr(self, '_stdio_context') and self._stdio_context:
if hasattr(self, "_stdio_context") and self._stdio_context:
await self._stdio_context.__aexit__(None, None, None)
except Exception as e:
logger.debug(f"[{self.server_name}] 关闭 stdio 连接时出错: {e}")
try:
if hasattr(self, '_http_context') and self._http_context:
if hasattr(self, "_http_context") and self._http_context:
await self._http_context.__aexit__(None, None, None)
except Exception as e:
logger.debug(f"[{self.server_name}] 关闭 HTTP 连接时出错: {e}")
try:
if hasattr(self, '_sse_context') and self._sse_context:
if hasattr(self, "_sse_context") and self._sse_context:
await self._sse_context.__aexit__(None, None, None)
except Exception as e:
logger.debug(f"[{self.server_name}] 关闭 SSE 连接时出错: {e}")
@ -1082,7 +1040,9 @@ class MCPClientManager:
return True
if attempt < retry_attempts:
logger.warning(f"服务器 {config.name} 连接失败,{retry_interval}秒后重试 ({attempt}/{retry_attempts})")
logger.warning(
f"服务器 {config.name} 连接失败,{retry_interval}秒后重试 ({attempt}/{retry_attempts})"
)
await asyncio.sleep(retry_interval)
logger.error(f"服务器 {config.name} 连接失败,已达最大重试次数 ({retry_attempts})")
@ -1213,11 +1173,7 @@ class MCPClientManager:
async def call_tool(self, tool_key: str, arguments: Dict[str, Any]) -> MCPCallResult:
"""调用 MCP 工具"""
if tool_key not in self._all_tools:
return MCPCallResult(
success=False,
content=None,
error=f"工具 {tool_key} 不存在"
)
return MCPCallResult(success=False, content=None, error=f"工具 {tool_key} 不存在")
tool_info, client = self._all_tools[tool_key]
@ -1273,16 +1229,12 @@ class MCPClientManager:
# 如果指定了服务器
if server_name:
if server_name not in self._clients:
return MCPCallResult(
success=False,
content=None,
error=f"服务器 {server_name} 不存在"
)
return MCPCallResult(success=False, content=None, error=f"服务器 {server_name} 不存在")
client = self._clients[server_name]
return await client.read_resource(uri)
# 自动查找拥有该资源的服务器
for resource_key, (resource_info, client) in self._all_resources.items():
for _resource_key, (resource_info, client) in self._all_resources.items():
if resource_info.uri == uri:
return await client.read_resource(uri)
@ -1293,14 +1245,11 @@ class MCPClientManager:
if result.success:
return result
return MCPCallResult(
success=False,
content=None,
error=f"未找到资源: {uri}"
)
return MCPCallResult(success=False, content=None, error=f"未找到资源: {uri}")
async def get_prompt(self, name: str, arguments: Optional[Dict[str, str]] = None,
server_name: Optional[str] = None) -> MCPCallResult:
async def get_prompt(
self, name: str, arguments: Optional[Dict[str, str]] = None, server_name: Optional[str] = None
) -> MCPCallResult:
"""v1.2.0: 获取提示模板内容
Args:
@ -1311,24 +1260,16 @@ class MCPClientManager:
# 如果指定了服务器
if server_name:
if server_name not in self._clients:
return MCPCallResult(
success=False,
content=None,
error=f"服务器 {server_name} 不存在"
)
return MCPCallResult(success=False, content=None, error=f"服务器 {server_name} 不存在")
client = self._clients[server_name]
return await client.get_prompt(name, arguments)
# 自动查找拥有该提示模板的服务器
for prompt_key, (prompt_info, client) in self._all_prompts.items():
for _prompt_key, (prompt_info, client) in self._all_prompts.items():
if prompt_info.name == name:
return await client.get_prompt(name, arguments)
return MCPCallResult(
success=False,
content=None,
error=f"未找到提示模板: {name}"
)
return MCPCallResult(success=False, content=None, error=f"未找到提示模板: {name}")
# ==================== 心跳检测 ====================
@ -1489,7 +1430,9 @@ class MCPClientManager:
"global": {
**self._global_stats,
"uptime_seconds": round(uptime, 2),
"calls_per_minute": round(self._global_stats["total_tool_calls"] / (uptime / 60), 2) if uptime > 0 else 0,
"calls_per_minute": round(self._global_stats["total_tool_calls"] / (uptime / 60), 2)
if uptime > 0
else 0,
},
"servers": server_stats,
"tools": tool_stats,

View File

@ -123,9 +123,11 @@ logger = get_logger("mcp_bridge_plugin")
# v1.4.0: 调用链路追踪
# ============================================================================
@dataclass
class ToolCallRecord:
"""工具调用记录"""
call_id: str
timestamp: float
tool_name: str
@ -208,9 +210,11 @@ tool_call_tracer = ToolCallTracer()
# v1.4.0: 工具调用缓存
# ============================================================================
@dataclass
class CacheEntry:
"""缓存条目"""
tool_name: str
args_hash: str
result: str
@ -347,6 +351,7 @@ tool_call_cache = ToolCallCache()
# v1.4.0: 工具权限控制
# ============================================================================
class PermissionChecker:
"""工具权限检查器"""
@ -479,6 +484,7 @@ permission_checker = PermissionChecker()
# 工具类型转换
# ============================================================================
def convert_json_type_to_tool_param_type(json_type: str) -> ToolParamType:
"""将 JSON Schema 类型转换为 MaiBot 的 ToolParamType"""
type_mapping = {
@ -492,7 +498,9 @@ def convert_json_type_to_tool_param_type(json_type: str) -> ToolParamType:
return type_mapping.get(json_type, ToolParamType.STRING)
def parse_mcp_parameters(input_schema: Dict[str, Any]) -> List[Tuple[str, ToolParamType, str, bool, Optional[List[str]]]]:
def parse_mcp_parameters(
input_schema: Dict[str, Any],
) -> List[Tuple[str, ToolParamType, str, bool, Optional[List[str]]]]:
"""解析 MCP 工具的参数 schema转换为 MaiBot 的参数格式"""
parameters = []
@ -534,6 +542,7 @@ def parse_mcp_parameters(input_schema: Dict[str, Any]) -> List[Tuple[str, ToolPa
# MCP 工具代理
# ============================================================================
class MCPToolProxy(BaseTool):
"""MCP 工具代理基类"""
@ -576,10 +585,7 @@ class MCPToolProxy(BaseTool):
# v1.4.0: 权限检查
if not permission_checker.check(self.name, chat_id, user_id, is_group):
logger.warning(f"权限拒绝: 工具 {self.name}, chat={chat_id}, user={user_id}")
return {
"name": self.name,
"content": f"⛔ 权限不足:工具 {self.name} 在当前场景下不可用"
}
return {"name": self.name, "content": f"⛔ 权限不足:工具 {self.name} 在当前场景下不可用"}
logger.debug(f"调用 MCP 工具: {self._mcp_tool_key}, 参数: {parsed_args}")
@ -749,15 +755,11 @@ class MCPToolProxy(BaseTool):
return None
async def _call_post_process_llm(
self,
prompt: str,
max_tokens: int,
settings: Dict[str, Any],
server_config: Optional[Dict[str, Any]]
self, prompt: str, max_tokens: int, settings: Dict[str, Any], server_config: Optional[Dict[str, Any]]
) -> Optional[str]:
"""调用 LLM 进行后处理"""
from src.config.config import model_config
from src.config.api_ada_configs import TaskConfig
from src.config.model_configs import TaskConfig
from src.llm_models.utils_model import LLMRequest
model_name = settings.get("post_process_model", "")
@ -811,10 +813,7 @@ class MCPToolProxy(BaseTool):
def create_mcp_tool_class(
tool_key: str,
tool_info: MCPToolInfo,
tool_prefix: str,
disabled: bool = False
tool_key: str, tool_info: MCPToolInfo, tool_prefix: str, disabled: bool = False
) -> Type[MCPToolProxy]:
"""根据 MCP 工具信息动态创建 BaseTool 子类"""
parameters = parse_mcp_parameters(tool_info.input_schema)
@ -837,7 +836,7 @@ def create_mcp_tool_class(
"_mcp_tool_key": tool_key,
"_mcp_original_name": tool_info.name,
"_mcp_server_name": tool_info.server_name,
}
},
)
return tool_class
@ -851,11 +850,7 @@ class MCPToolRegistry:
self._tool_infos: Dict[str, ToolInfo] = {}
def register_tool(
self,
tool_key: str,
tool_info: MCPToolInfo,
tool_prefix: str,
disabled: bool = False
self, tool_key: str, tool_info: MCPToolInfo, tool_prefix: str, disabled: bool = False
) -> Tuple[ToolInfo, Type[MCPToolProxy]]:
"""注册 MCP 工具"""
tool_class = create_mcp_tool_class(tool_key, tool_info, tool_prefix, disabled)
@ -902,6 +897,7 @@ _plugin_instance: Optional["MCPBridgePlugin"] = None
# 内置工具
# ============================================================================
class MCPReadResourceTool(BaseTool):
"""v1.2.0: MCP 资源读取工具"""
@ -973,6 +969,7 @@ class MCPGetPromptTool(BaseTool):
# v1.8.0: 工具链代理工具
# ============================================================================
class ToolChainProxyBase(BaseTool):
"""工具链代理基类"""
@ -1037,7 +1034,7 @@ def create_chain_tool_class(chain: ToolChainDefinition) -> Type[ToolChainProxyBa
"parameters": parameters,
"available_for_llm": True,
"_chain_name": chain.name,
}
},
)
return tool_class
@ -1095,7 +1092,13 @@ class MCPStatusTool(BaseTool):
name = "mcp_status"
description = "查询 MCP 桥接插件的状态,包括服务器连接状态、可用工具列表、工具链列表、资源列表、提示模板列表、调用统计、追踪记录等信息"
parameters = [
("query_type", ToolParamType.STRING, "查询类型", False, ["status", "tools", "chains", "resources", "prompts", "stats", "trace", "cache", "all"]),
(
"query_type",
ToolParamType.STRING,
"查询类型",
False,
["status", "tools", "chains", "resources", "prompts", "stats", "trace", "cache", "all"],
),
("server_name", ToolParamType.STRING, "指定服务器名称(可选)", False, None),
]
available_for_llm = True
@ -1132,10 +1135,7 @@ class MCPStatusTool(BaseTool):
if query_type in ("cache",):
result_parts.append(self._format_cache())
return {
"name": self.name,
"content": "\n\n".join(result_parts) if result_parts else "未知的查询类型"
}
return {"name": self.name, "content": "\n\n".join(result_parts) if result_parts else "未知的查询类型"}
def _format_status(self, server_name: Optional[str] = None) -> str:
status = mcp_manager.get_status()
@ -1147,14 +1147,14 @@ class MCPStatusTool(BaseTool):
lines.append(f" 心跳检测: {'运行中' if status['heartbeat_running'] else '已停止'}")
lines.append("\n🔌 服务器详情:")
for name, info in status['servers'].items():
for name, info in status["servers"].items():
if server_name and name != server_name:
continue
status_icon = "" if info['connected'] else ""
enabled_text = "" if info['enabled'] else " (已禁用)"
status_icon = "" if info["connected"] else ""
enabled_text = "" if info["enabled"] else " (已禁用)"
lines.append(f" {status_icon} {name}{enabled_text}")
lines.append(f" 传输: {info['transport']}, 工具数: {info['tools_count']}")
if info['consecutive_failures'] > 0:
if info["consecutive_failures"] > 0:
lines.append(f" ⚠️ 连续失败: {info['consecutive_failures']}")
return "\n".join(lines)
@ -1184,11 +1184,11 @@ class MCPStatusTool(BaseTool):
stats = mcp_manager.get_all_stats()
lines = ["📈 调用统计"]
g = stats['global']
g = stats["global"]
lines.append(f" 总调用次数: {g['total_tool_calls']}")
lines.append(f" 成功: {g['successful_calls']}, 失败: {g['failed_calls']}")
if g['total_tool_calls'] > 0:
success_rate = (g['successful_calls'] / g['total_tool_calls']) * 100
if g["total_tool_calls"] > 0:
success_rate = (g["successful_calls"] / g["total_tool_calls"]) * 100
lines.append(f" 成功率: {success_rate:.1f}%")
lines.append(f" 运行时间: {g['uptime_seconds']:.0f}")
@ -1201,7 +1201,7 @@ class MCPStatusTool(BaseTool):
lines = ["📦 可用 MCP 资源"]
by_server: Dict[str, List[MCPResourceInfo]] = {}
for key, (resource_info, _) in resources.items():
for _key, (resource_info, _) in resources.items():
if server_name and resource_info.server_name != server_name:
continue
if resource_info.server_name not in by_server:
@ -1222,7 +1222,7 @@ class MCPStatusTool(BaseTool):
lines = ["📝 可用 MCP 提示模板"]
by_server: Dict[str, List[MCPPromptInfo]] = {}
for key, (prompt_info, _) in prompts.items():
for _key, (prompt_info, _) in prompts.items():
if server_name and prompt_info.server_name != server_name:
continue
if prompt_info.server_name not in by_server:
@ -1277,7 +1277,7 @@ class MCPStatusTool(BaseTool):
lines.append(f" 描述: {chain.description[:50]}...")
lines.append(f" 步骤: {len(chain.steps)}")
for i, step in enumerate(chain.steps[:3]):
lines.append(f" {i+1}. {step.tool_name}")
lines.append(f" {i + 1}. {step.tool_name}")
if len(chain.steps) > 3:
lines.append(f" ... 还有 {len(chain.steps) - 3} 个步骤")
if chain.input_params:
@ -1294,6 +1294,7 @@ class MCPStatusTool(BaseTool):
# 命令处理
# ============================================================================
class MCPStatusCommand(BaseCommand):
"""MCP 状态查询命令 - 通过 /mcp 命令查看服务器状态"""
@ -1558,7 +1559,7 @@ class MCPStatusCommand(BaseCommand):
# 按服务器分组显示
by_server: Dict[str, List[Tuple[str, Any]]] = {}
for tool_key, tool_info, client in matched:
for tool_key, tool_info, _client in matched:
server_name = tool_info.server_name
if server_name not in by_server:
by_server[server_name] = []
@ -1644,8 +1645,9 @@ class MCPStatusCommand(BaseCommand):
_plugin_instance._load_tool_chains()
chains = tool_chain_manager.get_all_chains()
from src.plugin_system.core.component_registry import component_registry
registered = 0
for name, chain in tool_chain_manager.get_enabled_chains().items():
for name, _chain in tool_chain_manager.get_enabled_chains().items():
tool_name = f"chain_{name}".replace("-", "_").replace(".", "_")
if component_registry.get_component_info(tool_name, ComponentType.TOOL):
registered += 1
@ -1735,7 +1737,7 @@ class MCPStatusCommand(BaseCommand):
lines.append(f"📋 执行步骤 ({len(chain.steps)} 个):")
for i, step in enumerate(chain.steps):
optional_tag = " (可选)" if step.optional else ""
lines.append(f" {i+1}. {step.tool_name}{optional_tag}")
lines.append(f" {i + 1}. {step.tool_name}{optional_tag}")
if step.description:
lines.append(f" {step.description}")
if step.output_key:
@ -1786,7 +1788,7 @@ class MCPStatusCommand(BaseCommand):
if tools:
lines.append("\n🔧 可用工具:")
by_server = {}
for key, (info, _) in tools.items():
for _key, (info, _) in tools.items():
if server_name and info.server_name != server_name:
continue
by_server.setdefault(info.server_name, []).append(info.name)
@ -1983,6 +1985,7 @@ class MCPImportCommand(BaseCommand):
# 事件处理器
# ============================================================================
class MCPStartupHandler(BaseEventHandler):
"""MCP 启动事件处理器"""
@ -2037,6 +2040,7 @@ class MCPStopHandler(BaseEventHandler):
# 主插件类
# ============================================================================
@register_plugin
class MCPBridgePlugin(BasePlugin):
"""MCP 桥接插件 v2.0.0 - 将 MCP 服务器的工具桥接到 MaiBot"""
@ -2505,7 +2509,7 @@ class MCPBridgePlugin(BasePlugin):
label="📋 工具链列表",
input_type="textarea",
rows=20,
placeholder='''[
placeholder="""[
{
"name": "search_and_detail",
"description": "先搜索再获取详情",
@ -2515,7 +2519,7 @@ class MCPBridgePlugin(BasePlugin):
{"tool_name": "mcp_server_get_detail", "args_template": {"id": "${step.search_result}"}}
]
}
]''',
]""",
hint="每个工具链包含 name、description、input_params、steps",
order=30,
),
@ -2653,9 +2657,9 @@ mcp_bing_*""",
label="📜 高级权限规则(可选)",
input_type="textarea",
rows=10,
placeholder='''[
placeholder="""[
{"tool": "mcp_*_delete_*", "denied": ["qq:123456:group"]}
]''',
]""",
hint="格式: qq:ID:group/private/user工具名支持通配符 *",
order=10,
),
@ -2754,7 +2758,9 @@ mcp_bing_*""",
value = match1.group(2)
suffix = match1.group(3)
# 将转义的换行符还原为实际换行符
unescaped = value.replace("\\n", "\n").replace("\\t", "\t").replace('\\"', '"').replace("\\\\", "\\")
unescaped = (
value.replace("\\n", "\n").replace("\\t", "\t").replace('\\"', '"').replace("\\\\", "\\")
)
fixed_line = f'{prefix}"""{unescaped}"""{suffix}'
fixed_lines.append(fixed_line)
modified = True
@ -2948,11 +2954,13 @@ mcp_bing_*""",
logger.warning(f"快速添加工具链: 参数 JSON 格式错误: {args_str}")
args_template = {}
steps.append({
"tool_name": tool_name,
"args_template": args_template,
"output_key": output_key,
})
steps.append(
{
"tool_name": tool_name,
"args_template": args_template,
"output_key": output_key,
}
)
if not steps:
logger.warning("快速添加工具链: 没有有效的步骤")
@ -3056,7 +3064,9 @@ mcp_bing_*""",
if "tool_chains" not in self.config or not isinstance(self.config.get("tool_chains"), dict):
self.config["tool_chains"] = {}
self.config["tool_chains"]["chains_list"] = chains_json
logger.info("检测到旧版 Workflow 配置字段,已自动迁移为 tool_chains.chains_list请在 WebUI 保存一次以固化)")
logger.info(
"检测到旧版 Workflow 配置字段,已自动迁移为 tool_chains.chains_list请在 WebUI 保存一次以固化)"
)
chains_config = self.config.get("tool_chains", {})
if not isinstance(chains_config, dict):
@ -3153,10 +3163,7 @@ mcp_bing_*""",
# 应用过滤器
if filter_patterns:
matched = any(
fnmatch.fnmatch(tool_name, p) or tool_name == p
for p in filter_patterns
)
matched = any(fnmatch.fnmatch(tool_name, p) or tool_name == p for p in filter_patterns)
if filter_mode == "whitelist":
# 白名单模式:只注册匹配的
@ -3173,13 +3180,14 @@ mcp_bing_*""",
# 创建异步执行函数(使用闭包捕获 tool_key
def make_execute_func(tk: str):
async def execute_func(**kwargs) -> str:
async def _execute_func(**kwargs) -> str:
result = await mcp_manager.call_tool(tk, kwargs)
if result.success:
return result.content or "(无返回内容)"
else:
return f"工具调用失败: {result.error}"
return execute_func
return _execute_func
execute_func = make_execute_func(tool_key)
@ -3207,7 +3215,9 @@ mcp_bing_*""",
return registered_count
def _update_react_status_display(self, registered_tools: List[str], filter_mode: str, filter_patterns: List[str]) -> None:
def _update_react_status_display(
self, registered_tools: List[str], filter_mode: str, filter_patterns: List[str]
) -> None:
"""更新 ReAct 工具状态显示"""
if not registered_tools:
status_text = "(未注册任何工具)"
@ -3243,12 +3253,14 @@ mcp_bing_*""",
description = param_info.get("description", f"参数 {param_name}")
is_required = param_name in required
parameters.append({
"name": param_name,
"type": param_type,
"description": description,
"required": is_required,
})
parameters.append(
{
"name": param_name,
"type": param_type,
"description": description,
"required": is_required,
}
)
return parameters
@ -3276,7 +3288,7 @@ mcp_bing_*""",
for i, step in enumerate(chain.steps):
opt = " (可选)" if step.optional else ""
out = f"{step.output_key}" if step.output_key else ""
lines.append(f" {i+1}. {step.tool_name}{out}{opt}")
lines.append(f" {i + 1}. {step.tool_name}{out}{opt}")
lines.append("")
status_text = "\n".join(lines)
@ -3295,6 +3307,7 @@ mcp_bing_*""",
async def _async_connect_servers(self) -> None:
"""异步连接所有配置的 MCP 服务器v1.5.0: 并行连接优化)"""
import asyncio
settings = self.config.get("settings", {})
servers_config = self._load_mcp_servers_config()
@ -3380,10 +3393,7 @@ mcp_bing_*""",
# 并行执行所有连接
start_time = time.time()
results = await asyncio.gather(
*[connect_single_server(cfg) for cfg in enabled_configs],
return_exceptions=True
)
results = await asyncio.gather(*[connect_single_server(cfg) for cfg in enabled_configs], return_exceptions=True)
connect_duration = time.time() - start_time
# 统计连接结果
@ -3404,15 +3414,14 @@ mcp_bing_*""",
# 注册所有工具
from src.plugin_system.core.component_registry import component_registry
registered_count = 0
for tool_key, (tool_info, _) in mcp_manager.all_tools.items():
tool_name = tool_key.replace("-", "_").replace(".", "_")
is_disabled = tool_name in disabled_tools
info, tool_class = mcp_tool_registry.register_tool(
tool_key, tool_info, tool_prefix, disabled=is_disabled
)
info, tool_class = mcp_tool_registry.register_tool(tool_key, tool_info, tool_prefix, disabled=is_disabled)
info.plugin_name = self.plugin_name
if component_registry.register_component(info, tool_class):
@ -3433,7 +3442,9 @@ mcp_bing_*""",
react_count = self._register_tools_to_react()
self._initialized = True
logger.info(f"MCP 桥接插件初始化完成,已注册 {registered_count} 个工具,{chain_count} 个工具链,{react_count} 个 ReAct 工具")
logger.info(
f"MCP 桥接插件初始化完成,已注册 {registered_count} 个工具,{chain_count} 个工具链,{react_count} 个 ReAct 工具"
)
# 更新状态显示
self._update_status_display()
@ -3508,7 +3519,9 @@ mcp_bing_*""",
logger.info("检测到旧版 servers.list已自动迁移为 Claude mcpServers请在 WebUI 保存一次以固化)")
if not claude_json.strip():
self._last_servers_config_error = "未配置任何 MCP 服务器(请在 WebUI 的「MCP ServersClaude」粘贴 mcpServers JSON"
self._last_servers_config_error = (
"未配置任何 MCP 服务器(请在 WebUI 的「MCP ServersClaude」粘贴 mcpServers JSON"
)
return []
try:

View File

@ -22,15 +22,18 @@ from typing import Any, Dict, List, Optional, Tuple
try:
from src.common.logger import get_logger
logger = get_logger("mcp_tool_chain")
except ImportError:
import logging
logger = logging.getLogger("mcp_tool_chain")
@dataclass
class ToolChainStep:
"""工具链步骤"""
tool_name: str # 要调用的工具名(如 mcp_server_tool
args_template: Dict[str, Any] = field(default_factory=dict) # 参数模板,支持变量替换
output_key: str = "" # 输出存储的键名,供后续步骤引用
@ -60,6 +63,7 @@ class ToolChainStep:
@dataclass
class ToolChainDefinition:
"""工具链定义"""
name: str # 工具链名称(将作为组合工具的名称)
description: str # 工具链描述(供 LLM 理解)
steps: List[ToolChainStep] = field(default_factory=list) # 执行步骤
@ -90,6 +94,7 @@ class ToolChainDefinition:
@dataclass
class ChainExecutionResult:
"""工具链执行结果"""
success: bool
final_output: str # 最终输出(最后一个步骤的结果)
step_results: List[Dict[str, Any]] = field(default_factory=list) # 每个步骤的结果
@ -103,7 +108,7 @@ class ChainExecutionResult:
status = "" if step.get("success") else ""
tool = step.get("tool_name", "unknown")
duration = step.get("duration_ms", 0)
lines.append(f"{status} 步骤{i+1}: {tool} ({duration:.0f}ms)")
lines.append(f"{status} 步骤{i + 1}: {tool} ({duration:.0f}ms)")
if not step.get("success") and step.get("error"):
lines.append(f" 错误: {step['error'][:50]}")
return "\n".join(lines)
@ -113,7 +118,7 @@ class ToolChainExecutor:
"""工具链执行器"""
# 变量替换模式: ${step.output_key} 或 ${input.param_name} 或 ${prev}
VAR_PATTERN = re.compile(r'\$\{([^}]+)\}')
VAR_PATTERN = re.compile(r"\$\{([^}]+)\}")
def __init__(self, mcp_manager):
self._mcp_manager = mcp_manager
@ -201,7 +206,7 @@ class ToolChainExecutor:
tool_key = self._resolve_tool_key(step.tool_name)
if not tool_key:
step_result["error"] = f"工具 {step.tool_name} 不存在"
logger.warning(f"工具链步骤 {i+1}: 工具 {step.tool_name} 不存在")
logger.warning(f"工具链步骤 {i + 1}: 工具 {step.tool_name} 不存在")
if not step.optional:
step_results.append(step_result)
@ -209,13 +214,13 @@ class ToolChainExecutor:
success=False,
final_output="",
step_results=step_results,
error=f"步骤 {i+1}: 工具 {step.tool_name} 不存在",
error=f"步骤 {i + 1}: 工具 {step.tool_name} 不存在",
total_duration_ms=(time.time() - start_time) * 1000,
)
step_results.append(step_result)
continue
logger.debug(f"工具链步骤 {i+1}: 调用 {tool_key},参数: {resolved_args}")
logger.debug(f"工具链步骤 {i + 1}: 调用 {tool_key},参数: {resolved_args}")
# 调用工具
result = await self._mcp_manager.call_tool(tool_key, resolved_args)
@ -236,10 +241,10 @@ class ToolChainExecutor:
final_output = content
content_preview = content[:100] if content else "(空)"
logger.debug(f"工具链步骤 {i+1} 成功: {content_preview}...")
logger.debug(f"工具链步骤 {i + 1} 成功: {content_preview}...")
else:
step_result["error"] = result.error or "未知错误"
logger.warning(f"工具链步骤 {i+1} 失败: {result.error}")
logger.warning(f"工具链步骤 {i + 1} 失败: {result.error}")
if not step.optional:
step_results.append(step_result)
@ -247,7 +252,7 @@ class ToolChainExecutor:
success=False,
final_output="",
step_results=step_results,
error=f"步骤 {i+1} ({step.tool_name}) 失败: {result.error}",
error=f"步骤 {i + 1} ({step.tool_name}) 失败: {result.error}",
total_duration_ms=(time.time() - start_time) * 1000,
)
@ -255,7 +260,7 @@ class ToolChainExecutor:
step_duration = (time.time() - step_start) * 1000
step_result["duration_ms"] = step_duration
step_result["error"] = str(e)
logger.error(f"工具链步骤 {i+1} 异常: {e}")
logger.error(f"工具链步骤 {i + 1} 异常: {e}")
if not step.optional:
step_results.append(step_result)
@ -263,7 +268,7 @@ class ToolChainExecutor:
success=False,
final_output="",
step_results=step_results,
error=f"步骤 {i+1} ({step.tool_name}) 异常: {e}",
error=f"步骤 {i + 1} ({step.tool_name}) 异常: {e}",
total_duration_ms=(time.time() - start_time) * 1000,
)
@ -295,10 +300,7 @@ class ToolChainExecutor:
elif isinstance(value, dict):
resolved[key] = self._resolve_args(value, context)
elif isinstance(value, list):
resolved[key] = [
self._substitute_vars(v, context) if isinstance(v, str) else v
for v in value
]
resolved[key] = [self._substitute_vars(v, context) if isinstance(v, str) else v for v in value]
else:
resolved[key] = value
@ -306,6 +308,7 @@ class ToolChainExecutor:
def _substitute_vars(self, template: str, context: Dict[str, Any]) -> str:
"""替换字符串中的变量"""
def replacer(match):
var_path = match.group(1)
return self._get_var_value(var_path, context)
@ -552,7 +555,7 @@ class ToolChainManager:
try:
chain = ToolChainDefinition.from_dict(item)
if not chain.name:
errors.append(f"{i+1} 个工具链缺少名称")
errors.append(f"{i + 1} 个工具链缺少名称")
continue
if not chain.steps:
errors.append(f"工具链 {chain.name} 没有步骤")
@ -561,7 +564,7 @@ class ToolChainManager:
self.add_chain(chain)
loaded += 1
except Exception as e:
errors.append(f"{i+1} 个工具链解析失败: {e}")
errors.append(f"{i + 1} 个工具链解析失败: {e}")
return loaded, errors

View File

@ -238,7 +238,7 @@ class TestCommand(BaseCommand):
chat_stream=self.message.chat_stream,
reply_reason=reply_reason,
enable_chinese_typo=False,
extra_info=f"{reply_reason}用于测试bot的功能是否正常。请你按设定的人设表达一句\"测试正常\"",
extra_info=f'{reply_reason}用于测试bot的功能是否正常。请你按设定的人设表达一句"测试正常"',
)
if result_status:
# 发送生成的回复

View File

@ -0,0 +1,5 @@
{action_name}
动作描述:{action_description}
使用条件{parallel_text}
{action_require}
{{"action":"{action_name}",{action_parameters}, "target_message_id":"消息id(m+数字)"}}

View File

@ -0,0 +1,9 @@
{action_name}
动作描述:{action_description}
使用条件:
{action_require}
{{
"action": "{action_name}",{action_parameters},
"target_message_id":"触发action的消息id",
"reason":"触发action的原因"
}}

View File

@ -0,0 +1,77 @@
{time_block}
{name_block}
{chat_context_description},以下是具体的聊天内容
**聊天内容**
{chat_content_block}
**动作记录**
{actions_before_now_block}
**可用的action**
reply
动作描述:
进行回复,你可以自然的顺着正在进行的聊天内容进行回复或自然的提出一个问题
{{
"action": "reply",
"target_message_id":"想要回复的消息id",
"reason":"回复的原因"
}}
wait
动作描述:
暂时不再发言,等待指定时间。适用于以下情况:
- 你已经表达清楚一轮,想给对方留出空间
- 你感觉对方的话还没说完,或者自己刚刚发了好几条连续消息
- 你想要等待一定时间来让对方把话说完,或者等待对方反应
- 你想保持安静,专注"听"而不是马上回复
请你根据上下文来判断要等待多久,请你灵活判断:
- 如果你们交流间隔时间很短,聊的很频繁,不宜等待太久
- 如果你们交流间隔时间很长,聊的很少,可以等待较长时间
{{
"action": "wait",
"target_message_id":"想要作为这次等待依据的消息id通常是对方的最新消息",
"wait_seconds": 等待的秒数必填例如5 表示等待5秒,
"reason":"选择等待的原因"
}}
complete_talk
动作描述:
当前聊天暂时结束了,对方离开,没有更多话题了
你可以使用该动作来暂时休息,等待对方有新发言再继续:
- 多次wait之后对方迟迟不回复消息才用
- 如果对方只是短暂不回复应该使用wait而不是complete_talk
- 聊天内容显示当前聊天已经结束或者没有新内容时候选择complete_talk
选择此动作后,将不再继续循环思考,直到收到对方的新消息
{{
"action": "complete_talk",
"target_message_id":"触发完成对话的消息id通常是对方的最新消息",
"reason":"选择完成对话的原因"
}}
{action_options_text}
请选择合适的action并说明触发action的消息id和选择该action的原因。消息id格式:m+数字
先输出你的选择思考理由再输出你选择的action理由是一段平文本不要分点精简。
**动作选择要求**
请你根据聊天内容,用户的最新消息和以下标准选择合适的动作:
{plan_style}
{moderation_prompt}
请选择所有符合使用要求的action动作用json格式输出如果输出多个json每个json都要单独用```json包裹你可以重复使用同一个动作或不同动作:
**示例**
// 理由文本
```json
{{
"action":"动作名",
"target_message_id":"触发动作的消息id",
//对应参数
}}
```
```json
{{
"action":"动作名",
"target_message_id":"触发动作的消息id",
//对应参数
}}
```

View File

@ -0,0 +1 @@
你正在qq群里聊天下面是群里正在聊的内容:

View File

@ -0,0 +1 @@
正在群里聊天

Some files were not shown because too many files have changed in this diff Show More