mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge branch 'xinnan-tech:main' into sparkbot-zgc
This commit is contained in:
commit
2b66f5017f
76 changed files with 6768 additions and 478 deletions
66
.github/workflows/test.yml
vendored
Normal file
66
.github/workflows/test.yml
vendored
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
name: Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
python:
|
||||
name: Python (xiaozhi-server)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.10'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: 'main/xiaozhi-server/requirements.txt'
|
||||
- name: Install dependencies
|
||||
working-directory: main/xiaozhi-server
|
||||
run: |
|
||||
pip install -r requirements.txt
|
||||
pip install pytest pytest-asyncio freezegun
|
||||
- name: Run smoke test
|
||||
working-directory: main/xiaozhi-server
|
||||
run: |
|
||||
if [ -f tests/test_smoke.py ]; then
|
||||
pytest tests/test_smoke.py -x -q
|
||||
else
|
||||
echo "::warning::Slice 2 not done yet — tests/test_smoke.py missing"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
java:
|
||||
name: Java (manager-api)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '21'
|
||||
cache: 'maven'
|
||||
- name: Run tests
|
||||
working-directory: main/manager-api
|
||||
run: mvn -B -q test -DfailIfNoTests=false
|
||||
|
||||
web:
|
||||
name: Vue (manager-web)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: main/manager-web/package-lock.json
|
||||
- name: Run tests
|
||||
working-directory: main/manager-web
|
||||
run: |
|
||||
npm ci --no-audit --no-fund
|
||||
npm run test:unit
|
||||
21
Makefile
Normal file
21
Makefile
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
.PHONY: test test-fast test-python test-java test-web help
|
||||
|
||||
help:
|
||||
@echo "make test-fast - run all fast unit tests (default)"
|
||||
@echo "make test - alias for test-fast"
|
||||
@echo "make test-python - pytest in main/xiaozhi-server"
|
||||
@echo "make test-java - mvn test in main/manager-api"
|
||||
@echo "make test-web - npm run test:unit in main/manager-web"
|
||||
|
||||
test: test-fast
|
||||
|
||||
test-fast: test-python test-java test-web
|
||||
|
||||
test-python:
|
||||
cd main/xiaozhi-server && python -m pytest -x -q
|
||||
|
||||
test-java:
|
||||
cd main/manager-api && mvn -B -q test -DfailIfNoTests=false
|
||||
|
||||
test-web:
|
||||
cd main/manager-web && npm ci --no-audit --no-fund && npm test
|
||||
|
|
@ -70,7 +70,7 @@ xiaozhi-server
|
|||
|
||||
## 2. 配置项目文件
|
||||
|
||||
接下里,程序还不能直接运行,你需要配置一下,你到底使用的是什么模型。你可以看这个教程:
|
||||
接下来,程序还不能直接运行,你需要配置一下,你到底使用的是什么模型。你可以看这个教程:
|
||||
[跳转到配置项目文件](#配置项目)
|
||||
|
||||
配置完项目文件后,回到本教程继续往下。
|
||||
|
|
@ -119,7 +119,7 @@ docker rmi ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest
|
|||
如果确定使用`conda`,则安装好后,开始执行以下命令。
|
||||
|
||||
重要提示!windows 用户,可以通过安装`Anaconda`来管理环境。安装好`Anaconda`后,在`开始`那里搜索`anaconda`相关的关键词,
|
||||
找到`Anaconda Prpmpt`,使用管理员身份运行它。如下图。
|
||||
找到`Anaconda Prompt`,使用管理员身份运行它。如下图。
|
||||
|
||||

|
||||
|
||||
|
|
|
|||
|
|
@ -335,7 +335,7 @@ npm run serve
|
|||
如果确定使用`conda`,则安装好后,开始执行以下命令。
|
||||
|
||||
重要提示!windows 用户,可以通过安装`Anaconda`来管理环境。安装好`Anaconda`后,在`开始`那里搜索`anaconda`相关的关键词,
|
||||
找到`Anaconda Prpmpt`,使用管理员身份运行它。如下图。
|
||||
找到`Anaconda Prompt`,使用管理员身份运行它。如下图。
|
||||
|
||||

|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@
|
|||
`上下文源` 在小智在唤醒那一刻,获取外部系统的数据,并将其动态注入到大模型的系统提示词(System Prompt)中。
|
||||
让其做到唤醒时感知世界某个事物的状态。
|
||||
|
||||
它和MCP、记忆有本质的区别:`上下文源`是强制让小智感知世界的数据;`记忆(Mem)`是让他知道之前聊了什么内容;`MCP(functionc all)`是当需要调用某项能力/知识的时候使用调用。
|
||||
它和MCP、记忆有本质的区别:`上下文源`是强制让小智感知世界的数据;`记忆(Mem)`是让他知道之前聊了什么内容;`MCP(function_call)`是当需要调用某项能力/知识的时候使用调用。
|
||||
|
||||
通过这个功能,在小智唤醒的一刹那,“感知”到:
|
||||
- 人体健康传感器状态(体温、血压、血氧状态等)
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ cp 你原来的model.pt完整路径 /home/system/xiaozhi/xiaozhi-esp32-server/ma
|
|||
|
||||
# 第四步 建立三个自动编译文件
|
||||
|
||||
## 4.1 自动编译mananger-web模块
|
||||
## 4.1 自动编译manager-web模块
|
||||
在`/home/system/xiaozhi/`目录下,创建名字为`update_8001.sh`的文件,内容如下
|
||||
|
||||
```
|
||||
|
|
@ -106,7 +106,7 @@ fi
|
|||
|
||||
nohup java -jar xiaozhi-esp32-api.jar --spring.profiles.active=dev &
|
||||
|
||||
tail tail -f nohup.out
|
||||
tail -f nohup.out
|
||||
```
|
||||
|
||||
保存好后执行赋权命令
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ python download_models.py
|
|||
python -m tools.api_server --listen 0.0.0.0:6006
|
||||
```
|
||||
|
||||
然后用浏览器去到aotodl实例页面
|
||||
然后用浏览器去到autodl实例页面
|
||||
```
|
||||
https://autodl.com/console/instance/list
|
||||
```
|
||||
|
|
|
|||
|
|
@ -68,7 +68,7 @@ http://homeassistant.local:8123
|
|||
|
||||
然后在实体中搜索你相关控制的开关,结果出来后,在列表中,点击其中一个结果,这是会出现一个开关的界面。
|
||||
|
||||
在开关的界面,我们尝试点击开关,看看是开发会随着我们的点击开/关。如果能操作,说明是正常联网的。
|
||||
在开关的界面,我们尝试点击开关,看看是否会随着我们的点击开/关。如果能操作,说明是正常联网的。
|
||||
|
||||
接着在开关面板找到设置按钮,点击后,可以查看这个开关的`实体标识符`。
|
||||
|
||||
|
|
@ -107,7 +107,7 @@ http://homeassistant.local:8123
|
|||
|
||||
保存成功后,即可唤醒设备操作。
|
||||
|
||||
#### 3. 唤醒设别进行控制
|
||||
#### 3. 唤醒设备进行控制
|
||||
|
||||
尝试和esp32说,“打开XXX灯”
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
本教程分为4个阶段:准备阶段、配置阶段、克隆阶段、使用阶段。主要是介绍通过智控台配置火山双流式语音合成+音色克隆的过程。
|
||||
|
||||
## 第一阶段:准备阶段
|
||||
超级管理员先预先把火山引擎服务开通好,获取到App Id,Access Token。默认火上引擎会赠送一个音色资源。这个音色资源需要把它复制到本项目里。
|
||||
超级管理员先预先把火山引擎服务开通好,获取到App Id,Access Token。默认火山引擎会赠送一个音色资源。这个音色资源需要把它复制到本项目里。
|
||||
|
||||
如果你想克隆多个音色,需要购买开通多个音色资源。只要把每个音色资源的声音ID(S_xxxxx)复制到本项目。然后分配给系统的账号使用即可。以下是详细步骤:
|
||||
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@
|
|||
|
||||
打开完,找到页面中一个绿色的按钮,写着`Code`的按钮,点开它,然后你就看到`Download ZIP`的按钮。
|
||||
|
||||
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`mcp-calculatorr-main`
|
||||
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`mcp-calculator-main`
|
||||
你需要把它重命名成`mcp-calculator`。接下来,我们用命令行进入项目目录即安装依赖
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -113,7 +113,7 @@ server:
|
|||
|
||||
那我们需要先登录[智谱AI](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)网站,申请密钥。如果你之前已经申请过了密钥,可以复用这个密钥。
|
||||
|
||||
登录`智控台`,顶部菜单点击`模型配置`,在左侧栏点击`视觉打语言模型`,找到`VLLM_ChatGLMVLLM`,点击修改按钮,在弹框中,在`API密钥`输入你密钥,点击保存。
|
||||
登录`智控台`,顶部菜单点击`模型配置`,在左侧栏点击`视觉大语言模型`,找到`VLLM_ChatGLMVLLM`,点击修改按钮,在弹框中,在`API密钥`输入你密钥,点击保存。
|
||||
|
||||
保存成功后,去到你需要测试的智能体哪里,点击`配置角色`,在打开的内容里,查看`视觉大语言模型(VLLM)`是否选择了刚才的视觉模型。点击保存。
|
||||
|
||||
|
|
|
|||
|
|
@ -86,7 +86,7 @@ SERVER_SECRET=Te1st12134 # 服务器密钥,请保持和智控台(server.sec
|
|||
- 注意不要用简单的密码,比如`123456`、`test`等。
|
||||
- 注意不要用简单的密码,比如`123456`、`test`等。
|
||||
|
||||
`SERVER_SECRET` 是用生成websocket连接的认证信息。
|
||||
`SERVER_SECRET` 是用于生成websocket连接的认证信息。
|
||||
|
||||
1、如果你是全模块部署,且你的智控台的参数管理里`server.auth.enabled`设置成了`true`,那么,`SERVER_SECRET`需要和智控台(`server.secret`)保持一致。
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# ragflow 集成指南
|
||||
|
||||
本教程主要是是两部分
|
||||
本教程主要是两部分
|
||||
|
||||
- 一、如何部署ragflow
|
||||
- 二、如何在智控台配置ragflow接口
|
||||
|
|
@ -12,7 +12,7 @@
|
|||
|
||||
ragflow需要依赖`mysql`数据库。如果你之前已经部署`智控台`,说明你已经安装了`mysql`。你可以共用它。
|
||||
|
||||
你可以你试一下在宿主机使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。
|
||||
你可以试一下在宿主机使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。
|
||||
``` shell
|
||||
telnet 127.0.0.1 3306
|
||||
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@
|
|||
|
||||
声纹识别需要依赖`mysql`数据库。如果你之前已经部署`智控台`,说明你已经安装了`mysql`。你可以共用它。
|
||||
|
||||
你可以你试一下在宿主机使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。
|
||||
你可以试一下在宿主机使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。
|
||||
```
|
||||
telnet 127.0.0.1 3306
|
||||
```
|
||||
|
|
|
|||
|
|
@ -0,0 +1,22 @@
|
|||
UPDATE `ai_model_config`
|
||||
SET `config_json` = JSON_SET(`config_json`, '$.model_name', 'doubao-seed-2-0-lite-260215')
|
||||
WHERE `id` = 'LLM_DoubaoLLM'
|
||||
AND JSON_UNQUOTE(JSON_EXTRACT(`config_json`, '$.model_name')) IN (
|
||||
'doubao-1-5-pro-32k-250115'
|
||||
);
|
||||
|
||||
UPDATE `ai_model_config`
|
||||
SET `remark` = REPLACE(
|
||||
REPLACE(
|
||||
`remark`,
|
||||
'开通Doubao-1.5-pro服务',
|
||||
'开通 Doubao-Seed-2.0-Lite 服务'
|
||||
),
|
||||
'当前建议使用doubao-1-5-pro-32k-250115',
|
||||
'当前建议使用 doubao-seed-2-0-lite-260215'
|
||||
)
|
||||
WHERE `id` = 'LLM_DoubaoLLM'
|
||||
AND (
|
||||
`remark` LIKE '%Doubao-1.5-pro%'
|
||||
OR `remark` LIKE '%doubao-1-5-pro-32k-250115%'
|
||||
);
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
-- 阿里百炼流式 TTS 支持业务空间 WebSocket 地址
|
||||
|
||||
UPDATE `ai_model_provider`
|
||||
SET `fields` = JSON_ARRAY(
|
||||
JSON_OBJECT('key', 'api_key', 'type', 'string', 'label', 'API密钥'),
|
||||
JSON_OBJECT(
|
||||
'key', 'ws_url',
|
||||
'type', 'string',
|
||||
'label', 'WebSocket地址(含Workspace ID)',
|
||||
'default', 'wss://dashscope.aliyuncs.com/api-ws/v1/inference/'
|
||||
),
|
||||
JSON_OBJECT('key', 'output_dir', 'type', 'string', 'label', '输出目录'),
|
||||
JSON_OBJECT('key', 'model', 'type', 'string', 'label', '模型'),
|
||||
JSON_OBJECT('key', 'voice', 'type', 'string', 'label', '音色'),
|
||||
JSON_OBJECT('key', 'format', 'type', 'string', 'label', '音频格式'),
|
||||
JSON_OBJECT('key', 'sample_rate', 'type', 'number', 'label', '采样率'),
|
||||
JSON_OBJECT('key', 'volume', 'type', 'number', 'label', '音量'),
|
||||
JSON_OBJECT('key', 'rate', 'type', 'number', 'label', '语速'),
|
||||
JSON_OBJECT('key', 'pitch', 'type', 'number', 'label', '音调')
|
||||
)
|
||||
WHERE `id` = 'SYSTEM_TTS_AliBLStreamTTS';
|
||||
|
||||
UPDATE `ai_model_config`
|
||||
SET `config_json` = JSON_SET(
|
||||
`config_json`,
|
||||
'$.ws_url',
|
||||
COALESCE(
|
||||
NULLIF(JSON_UNQUOTE(JSON_EXTRACT(`config_json`, '$.ws_url')), ''),
|
||||
'wss://dashscope.aliyuncs.com/api-ws/v1/inference/'
|
||||
)
|
||||
)
|
||||
WHERE `id` = 'TTS_AliBLStreamTTS';
|
||||
|
||||
UPDATE `ai_model_config`
|
||||
SET `remark` = '阿里百炼流式 TTS 配置说明:
|
||||
1. API密钥填写当前业务空间可用的 DashScope API Key
|
||||
2. 公有模式可使用 wss://dashscope.aliyuncs.com/api-ws/v1/inference/
|
||||
3. 华北2(北京)业务空间填写 wss://<WorkspaceId>.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference
|
||||
4. 新加坡业务空间填写 wss://<WorkspaceId>.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference
|
||||
5. 将 <WorkspaceId> 替换为真实业务空间 ID;仅支持阿里云官方 WSS 推理地址
|
||||
6. 支持 CosyVoice 流式合成及音量、语速、音调配置'
|
||||
WHERE `id` = 'TTS_AliBLStreamTTS';
|
||||
|
|
@ -725,6 +725,13 @@ databaseChangeLog:
|
|||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202608061030.sql
|
||||
- changeSet:
|
||||
id: 202608061800
|
||||
author: cgd
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202608061800.sql
|
||||
- changeSet:
|
||||
id: 202608131030
|
||||
author: tykechen
|
||||
|
|
@ -732,3 +739,10 @@ databaseChangeLog:
|
|||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202608131030.sql
|
||||
- changeSet:
|
||||
id: 202609021000
|
||||
author: JacobNg1
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202609021000.sql
|
||||
|
|
|
|||
|
|
@ -0,0 +1,83 @@
|
|||
package xiaozhi.common.utils;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import cn.hutool.json.JSONObject;
|
||||
|
||||
class SensitiveDataUtilsTest {
|
||||
|
||||
@Test
|
||||
void isSensitiveField_recognizes_known_field_names() {
|
||||
assertTrue(SensitiveDataUtils.isSensitiveField("api_key"));
|
||||
assertTrue(SensitiveDataUtils.isSensitiveField("API_KEY"));
|
||||
assertTrue(SensitiveDataUtils.isSensitiveField("personal_access_token"));
|
||||
assertTrue(SensitiveDataUtils.isSensitiveField("secret"));
|
||||
assertTrue(SensitiveDataUtils.isSensitiveField("secret_key"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isSensitiveField_rejects_blank_and_unknown_field_names() {
|
||||
assertFalse(SensitiveDataUtils.isSensitiveField(""));
|
||||
assertFalse(SensitiveDataUtils.isSensitiveField(" "));
|
||||
assertFalse(SensitiveDataUtils.isSensitiveField(null));
|
||||
assertFalse(SensitiveDataUtils.isSensitiveField("not_a_secret"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maskMiddle_returns_input_unchanged_for_short_or_blank_values() {
|
||||
assertNull(SensitiveDataUtils.maskMiddle(null));
|
||||
assertEquals("", SensitiveDataUtils.maskMiddle(""));
|
||||
assertEquals("a", SensitiveDataUtils.maskMiddle("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maskMiddle_keeps_two_at_each_end_for_short_strings() {
|
||||
assertEquals("ab****yz", SensitiveDataUtils.maskMiddle("abcdefyz"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maskMiddle_keeps_four_at_each_end_for_long_strings() {
|
||||
String masked = SensitiveDataUtils.maskMiddle("verylongapikeyvalue123");
|
||||
assertTrue(masked.startsWith("very"));
|
||||
assertTrue(masked.endsWith("3123"));
|
||||
assertTrue(masked.contains("****"));
|
||||
assertEquals("verylongapikeyvalue123".length(), masked.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isMaskedValue_detects_masked_values() {
|
||||
assertTrue(SensitiveDataUtils.isMaskedValue("ab****yz"));
|
||||
assertTrue(SensitiveDataUtils.isMaskedValue("abc****def****ghi"));
|
||||
assertFalse(SensitiveDataUtils.isMaskedValue("plainstring"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isMaskedValue_rejects_blank_values() {
|
||||
assertFalse(SensitiveDataUtils.isMaskedValue(null));
|
||||
assertFalse(SensitiveDataUtils.isMaskedValue(""));
|
||||
assertFalse(SensitiveDataUtils.isMaskedValue(" "));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maskSensitiveFields_masks_known_sensitive_keys_only() {
|
||||
JSONObject source = new JSONObject();
|
||||
source.set("api_key", "sk-supersecretapikey");
|
||||
source.set("name", "alice");
|
||||
|
||||
JSONObject masked = SensitiveDataUtils.maskSensitiveFields(source);
|
||||
|
||||
String apiKey = (String) masked.get("api_key");
|
||||
assertTrue(apiKey.contains("****"));
|
||||
assertEquals("alice", masked.get("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maskSensitiveFields_returns_null_when_input_is_null() {
|
||||
assertNull(SensitiveDataUtils.maskSensitiveFields(null));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
package xiaozhi.modules.correctword.service.impl;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import xiaozhi.modules.agent.dao.AgentCorrectWordMappingDao;
|
||||
import xiaozhi.modules.agent.entity.AgentCorrectWordMappingEntity;
|
||||
import xiaozhi.modules.correctword.dao.CorrectWordFileDao;
|
||||
import xiaozhi.modules.correctword.dao.CorrectWordItemDao;
|
||||
import xiaozhi.modules.correctword.entity.CorrectWordFileEntity;
|
||||
import xiaozhi.modules.correctword.entity.CorrectWordItemEntity;
|
||||
import xiaozhi.modules.correctword.vo.CorrectWordFileVO;
|
||||
import xiaozhi.modules.correctword.vo.CorrectWordSimpleVO;
|
||||
|
||||
class CorrectWordFileServiceImplTest {
|
||||
|
||||
private static final String AGENT_ID = "agent-1";
|
||||
private static final String FILE_ID = "file-1";
|
||||
|
||||
private final CorrectWordFileDao fileDao = mock(CorrectWordFileDao.class);
|
||||
private final CorrectWordItemDao itemDao = mock(CorrectWordItemDao.class);
|
||||
private final AgentCorrectWordMappingDao mappingDao = mock(AgentCorrectWordMappingDao.class);
|
||||
private final CorrectWordFileServiceImpl service =
|
||||
new CorrectWordFileServiceImpl(fileDao, itemDao, mappingDao);
|
||||
|
||||
@Test
|
||||
void getAllItemsByAgentId_returns_empty_list_when_no_mappings() {
|
||||
when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(Collections.emptyList());
|
||||
|
||||
List<CorrectWordSimpleVO> result = service.getAllItemsByAgentId(AGENT_ID);
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
verify(itemDao, never()).selectList(org.mockito.ArgumentMatchers.any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllItemsByAgentId_returns_mapped_items_when_mappings_exist() {
|
||||
AgentCorrectWordMappingEntity mapping = new AgentCorrectWordMappingEntity();
|
||||
mapping.setFileId(FILE_ID);
|
||||
when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(List.of(mapping));
|
||||
|
||||
CorrectWordItemEntity item = new CorrectWordItemEntity();
|
||||
item.setSourceWord("hello");
|
||||
item.setTargetWord("hi");
|
||||
when(itemDao.selectList(org.mockito.ArgumentMatchers.any())).thenReturn(List.of(item));
|
||||
|
||||
List<CorrectWordSimpleVO> result = service.getAllItemsByAgentId(AGENT_ID);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("hello", result.get(0).getSourceWord());
|
||||
assertEquals("hi", result.get(0).getTargetWord());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllItemsByAgentId_returns_empty_list_when_mappings_are_null() {
|
||||
when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(null);
|
||||
|
||||
List<CorrectWordSimpleVO> result = service.getAllItemsByAgentId(AGENT_ID);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAgentCorrectWordFileIds_returns_empty_list_when_no_mappings() {
|
||||
when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(Collections.emptyList());
|
||||
|
||||
List<String> result = service.getAgentCorrectWordFileIds(AGENT_ID);
|
||||
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAgentCorrectWordFileIds_returns_file_ids_when_mappings_exist() {
|
||||
AgentCorrectWordMappingEntity m1 = new AgentCorrectWordMappingEntity();
|
||||
m1.setFileId("f1");
|
||||
AgentCorrectWordMappingEntity m2 = new AgentCorrectWordMappingEntity();
|
||||
m2.setFileId("f2");
|
||||
when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(List.of(m1, m2));
|
||||
|
||||
List<String> result = service.getAgentCorrectWordFileIds(AGENT_ID);
|
||||
|
||||
assertEquals(List.of("f1", "f2"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getFileContent_returns_null_when_entity_not_found() {
|
||||
when(fileDao.selectById(FILE_ID)).thenReturn(null);
|
||||
|
||||
CorrectWordFileVO result = service.getFileContent(FILE_ID);
|
||||
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getFileContent_returns_vo_when_entity_found() {
|
||||
CorrectWordFileEntity entity = new CorrectWordFileEntity();
|
||||
entity.setId(FILE_ID);
|
||||
entity.setFileName("dict.txt");
|
||||
entity.setWordCount(2);
|
||||
entity.setContent("hello|hi\nbye|goodbye");
|
||||
entity.setCreatedAt(new Date());
|
||||
when(fileDao.selectById(FILE_ID)).thenReturn(entity);
|
||||
|
||||
CorrectWordFileVO result = service.getFileContent(FILE_ID);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(FILE_ID, result.getId());
|
||||
assertEquals("dict.txt", result.getFileName());
|
||||
assertEquals(2, result.getWordCount().intValue());
|
||||
assertEquals(2, result.getContent().size());
|
||||
assertEquals("hello|hi", result.getContent().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteMappingsByAgentId_delegates_to_dao() {
|
||||
service.deleteMappingsByAgentId(AGENT_ID);
|
||||
|
||||
verify(mappingDao).deleteByAgentId(AGENT_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchDeleteFiles_skips_null_and_empty_ids() {
|
||||
List<String> ids = new ArrayList<>();
|
||||
ids.add(null);
|
||||
ids.add("");
|
||||
ids.add(" ");
|
||||
ids.add(FILE_ID);
|
||||
|
||||
service.batchDeleteFiles(ids);
|
||||
|
||||
verify(fileDao).deleteById(FILE_ID);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,233 @@
|
|||
package xiaozhi.modules.knowledge.rag;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
|
||||
import xiaozhi.common.exception.ErrorCode;
|
||||
import xiaozhi.common.exception.RenException;
|
||||
import xiaozhi.common.page.PageData;
|
||||
import xiaozhi.common.utils.MessageUtils;
|
||||
import xiaozhi.modules.knowledge.dto.KnowledgeFilesDTO;
|
||||
import xiaozhi.modules.knowledge.dto.dataset.DatasetDTO;
|
||||
import xiaozhi.modules.knowledge.dto.document.ChunkDTO;
|
||||
import xiaozhi.modules.knowledge.dto.document.DocumentDTO;
|
||||
import xiaozhi.modules.knowledge.dto.document.RetrievalDTO;
|
||||
|
||||
class KnowledgeBaseAdapterFactoryTest {
|
||||
|
||||
private static final String REGISTERED_TYPE = "kb-test-registered";
|
||||
private static final String UNKNOWN_TYPE = "kb-test-unknown";
|
||||
|
||||
@BeforeEach
|
||||
void resetCache() {
|
||||
KnowledgeBaseAdapterFactory.clearCache();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanupCache() {
|
||||
KnowledgeBaseAdapterFactory.clearCache();
|
||||
KnowledgeBaseAdapterFactory.removeCacheByType(REGISTERED_TYPE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAdapter_returns_non_null_instance_for_registered_type() {
|
||||
KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class);
|
||||
|
||||
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(REGISTERED_TYPE);
|
||||
|
||||
assertNotNull(adapter);
|
||||
assertEquals(REGISTERED_TYPE, adapter.getAdapterType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAdapter_returns_cached_instance_for_repeated_calls() {
|
||||
KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class);
|
||||
|
||||
KnowledgeBaseAdapter first = KnowledgeBaseAdapterFactory.getAdapter(REGISTERED_TYPE);
|
||||
KnowledgeBaseAdapter second = KnowledgeBaseAdapterFactory.getAdapter(REGISTERED_TYPE);
|
||||
|
||||
assertSame(first, second);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAdapter_throws_RenException_for_unknown_type() {
|
||||
try (MockedStatic<MessageUtils> messageUtils = mockStatic(MessageUtils.class)) {
|
||||
messageUtils.when(() -> MessageUtils.getMessage(anyInt())).thenReturn("mocked message");
|
||||
messageUtils.when(() -> MessageUtils.getMessage(anyInt(), any(String[].class)))
|
||||
.thenReturn("mocked message");
|
||||
|
||||
RenException ex = assertThrows(RenException.class,
|
||||
() -> KnowledgeBaseAdapterFactory.getAdapter(UNKNOWN_TYPE));
|
||||
|
||||
assertEquals(ErrorCode.RAG_ADAPTER_TYPE_NOT_SUPPORTED, ex.getCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void isAdapterTypeRegistered_returns_true_for_registered_types() {
|
||||
KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class);
|
||||
|
||||
assertTrue(KnowledgeBaseAdapterFactory.isAdapterTypeRegistered(REGISTERED_TYPE));
|
||||
assertTrue(KnowledgeBaseAdapterFactory.isAdapterTypeRegistered("ragflow"));
|
||||
assertFalse(KnowledgeBaseAdapterFactory.isAdapterTypeRegistered(UNKNOWN_TYPE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRegisteredAdapterTypes_contains_all_registered_types() {
|
||||
KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class);
|
||||
|
||||
Set<String> types = KnowledgeBaseAdapterFactory.getRegisteredAdapterTypes();
|
||||
|
||||
assertTrue(types.contains(REGISTERED_TYPE));
|
||||
assertTrue(types.contains("ragflow"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearCache_empties_cached_instance_count() {
|
||||
KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class);
|
||||
KnowledgeBaseAdapterFactory.getAdapter(REGISTERED_TYPE);
|
||||
|
||||
KnowledgeBaseAdapterFactory.clearCache();
|
||||
Map<String, Object> status = KnowledgeBaseAdapterFactory.getFactoryStatus();
|
||||
|
||||
assertEquals(0, status.get("cachedAdapterCount"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test stub adapter that satisfies the abstract API surface so the factory's
|
||||
* reflection-based instantiation works in the unit test.
|
||||
*/
|
||||
public static class StubAdapter extends KnowledgeBaseAdapter {
|
||||
@Override
|
||||
public String getAdapterType() {
|
||||
return REGISTERED_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize(Map<String, Object> config) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean validateConfig(Map<String, Object> config) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageData<KnowledgeFilesDTO> getDocumentList(String datasetId,
|
||||
DocumentDTO.ListReq req) {
|
||||
return new PageData<>(java.util.Collections.emptyList(), 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DocumentDTO.InfoVO getDocumentById(String datasetId, String documentId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public KnowledgeFilesDTO uploadDocument(DocumentDTO.UploadReq req) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageData<KnowledgeFilesDTO> getDocumentListByStatus(String datasetId,
|
||||
Integer status, Integer page, Integer limit) {
|
||||
return new PageData<>(java.util.Collections.emptyList(), 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteDocument(String datasetId, DocumentDTO.BatchIdReq req) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean parseDocuments(String datasetId, java.util.List<String> documentIds) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChunkDTO.ListVO listChunks(String datasetId, String documentId,
|
||||
ChunkDTO.ListReq req) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RetrievalDTO.ResultVO retrievalTest(RetrievalDTO.TestReq req) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean testConnection() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getStatus() {
|
||||
return java.util.Collections.emptyMap();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getSupportedConfig() {
|
||||
return java.util.Collections.emptyMap();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getDefaultConfig() {
|
||||
return java.util.Collections.emptyMap();
|
||||
}
|
||||
|
||||
@Override
|
||||
public DatasetDTO.InfoVO createDataset(DatasetDTO.CreateReq req) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DatasetDTO.InfoVO updateDataset(String datasetId, DatasetDTO.UpdateReq req) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DatasetDTO.BatchOperationVO deleteDataset(DatasetDTO.BatchIdReq req) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer getDocumentCount(String datasetId) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DatasetDTO.InfoVO getDatasetInfo(String datasetId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postStream(String endpoint, Object body, Consumer<String> onData) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postSearchBotAsk(Map<String, Object> config, Object body,
|
||||
Consumer<String> onData) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postAgentBotCompletion(Map<String, Object> config, String agentId,
|
||||
Object body, Consumer<String> onData) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -8,10 +8,10 @@
|
|||
- 劣势:只能使用 2 组图片来切换选中和非选中状态,修改颜色只能重新换图片(或者用 iconfont)。
|
||||
- 2 `有缓存自定义 tabbar`,使用 `switchTab` 切换 tabbar,`tabbar` 页面有缓存。使用了第三方 UI 库的 `tabbar` 组件,并隐藏了原生 `tabbar` 的显示。
|
||||
- 优势:可以随意配置自己想要的 `svg icon`,切换字体颜色方便。有缓存。可以实现各种花里胡哨的动效等。
|
||||
- 劣势:首次点击 tababr 会闪烁。
|
||||
- 劣势:首次点击 tabbar 会闪烁。
|
||||
- 3 `无缓存自定义 tabbar`,使用 `navigateTo` 切换 `tabbar`,`tabbar` 页面无缓存。使用了第三方 UI 库的 `tabbar` 组件。
|
||||
- 优势:可以随意配置自己想要的 svg icon,切换字体颜色方便。可以实现各种花里胡哨的动效等。
|
||||
- 劣势:首次点击 `tababr` 会闪烁,无缓存。
|
||||
- 劣势:首次点击 `tabbar` 会闪烁,无缓存。
|
||||
|
||||
|
||||
> 注意:花里胡哨的效果需要自己实现,本模版不提供。
|
||||
|
|
|
|||
3042
main/manager-web/package-lock.json
generated
3042
main/manager-web/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -7,7 +7,9 @@
|
|||
"check:i18n": "node scripts/check-i18n.js",
|
||||
"test:snapshot": "node --test src/components/agentSnapshotDisplayUtils.test.mjs src/apis/module/agentSnapshotApi.test.mjs",
|
||||
"build": "vue-cli-service build",
|
||||
"test:unit": "node --test tests/*.test.mjs",
|
||||
"test:contract": "node --test tests/*Contract.test.mjs",
|
||||
"test:unit": "vitest run",
|
||||
"test": "npm run test:contract && npm run test:unit",
|
||||
"analyze": "cross-env ANALYZE=true vue-cli-service build"
|
||||
},
|
||||
"dependencies": {
|
||||
|
|
@ -16,10 +18,12 @@
|
|||
"dotenv": "^16.5.0",
|
||||
"element-ui": "^2.15.14",
|
||||
"flyio": "^0.6.14",
|
||||
"highlight.js": "^11.12.0",
|
||||
"normalize.css": "^8.0.1",
|
||||
"opus-decoder": "^0.7.7",
|
||||
"opus-recorder": "^8.0.5",
|
||||
"sm-crypto": "^0.3.13",
|
||||
"v-code-diff": "^1.16.0",
|
||||
"vue": "^2.6.14",
|
||||
"vue-axios": "^3.5.2",
|
||||
"vue-i18n": "^8.28.2",
|
||||
|
|
@ -30,12 +34,16 @@
|
|||
"devDependencies": {
|
||||
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
|
||||
"@babel/plugin-transform-runtime": "^7.26.10",
|
||||
"@vitest/coverage-v8": "^1.6.0",
|
||||
"@vue/cli-plugin-router": "~5.0.0",
|
||||
"@vue/cli-plugin-vuex": "~5.0.0",
|
||||
"@vue/cli-service": "~5.0.0",
|
||||
"@vue/test-utils": "^1.3.6",
|
||||
"compression-webpack-plugin": "^11.1.0",
|
||||
"jsdom": "^24.1.0",
|
||||
"sass": "^1.32.7",
|
||||
"sass-loader": "^12.0.0",
|
||||
"vitest": "^1.6.0",
|
||||
"vue-template-compiler": "^2.6.14",
|
||||
"webpack-bundle-analyzer": "^4.10.2",
|
||||
"workbox-webpack-plugin": "^7.3.0"
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
<el-dialog
|
||||
:title="$t('agentSnapshot.title')"
|
||||
:visible="visible"
|
||||
width="860px"
|
||||
width="960px"
|
||||
class="agent-snapshot-dialog"
|
||||
:before-close="guardRestoreInFlightClose"
|
||||
:close-on-click-modal="!restoring"
|
||||
|
|
@ -126,7 +126,7 @@
|
|||
<el-dialog
|
||||
:title="detailDialogTitle"
|
||||
:visible.sync="detailVisible"
|
||||
width="860px"
|
||||
width="960px"
|
||||
class="snapshot-detail-dialog"
|
||||
>
|
||||
<template slot="title">
|
||||
|
|
@ -269,8 +269,21 @@
|
|||
</div>
|
||||
<div v-else class="value-empty">{{ $t('agentSnapshot.noFunctionChange') }}</div>
|
||||
</div>
|
||||
<div v-else-if="shouldUseCodeDiff(item)" class="diff-code-wrapper">
|
||||
<CodeDiff
|
||||
:old-string="item.beforeText"
|
||||
:new-string="item.afterText"
|
||||
:language="codeDiffLanguage(item)"
|
||||
output-format="side-by-side"
|
||||
diff-style="word"
|
||||
:context="8"
|
||||
max-height="320px"
|
||||
:filename="item.beforeTitle"
|
||||
:new-filename="item.afterTitle"
|
||||
/>
|
||||
</div>
|
||||
<div v-else class="diff-values" :class="{ 'is-complex': item.complex }">
|
||||
<div class="diff-pane diff-before">
|
||||
<div class="diff-pane diff-before 1">
|
||||
<div class="diff-pane-title">{{ item.beforeTitle }}</div>
|
||||
<div class="diff-value" :class="valueClass(item)">
|
||||
<div
|
||||
|
|
@ -306,7 +319,7 @@
|
|||
<el-dialog
|
||||
:title="restorePreviewTitle"
|
||||
:visible.sync="restorePreviewVisible"
|
||||
width="860px"
|
||||
width="960px"
|
||||
class="snapshot-detail-dialog"
|
||||
:before-close="guardRestoreInFlightClose"
|
||||
:close-on-click-modal="!restoring"
|
||||
|
|
@ -401,8 +414,21 @@
|
|||
</div>
|
||||
<div v-else class="value-empty">{{ $t('agentSnapshot.noFunctionChange') }}</div>
|
||||
</div>
|
||||
<div v-else-if="shouldUseCodeDiff(item)" class="diff-code-wrapper">
|
||||
<CodeDiff
|
||||
:old-string="item.beforeText"
|
||||
:new-string="item.afterText"
|
||||
:language="codeDiffLanguage(item)"
|
||||
output-format="side-by-side"
|
||||
diff-style="word"
|
||||
:context="8"
|
||||
max-height="320px"
|
||||
:filename="item.beforeTitle"
|
||||
:new-filename="item.afterTitle"
|
||||
/>
|
||||
</div>
|
||||
<div v-else class="diff-values" :class="{ 'is-complex': item.complex }">
|
||||
<div class="diff-pane diff-before">
|
||||
<div class="diff-pane diff-before 2">
|
||||
<div class="diff-pane-title">{{ item.beforeTitle }}</div>
|
||||
<div class="diff-value" :class="valueClass(item)">
|
||||
<div
|
||||
|
|
@ -485,6 +511,8 @@
|
|||
import Api from "@/apis/api";
|
||||
import correctWord from "@/apis/module/correctWord";
|
||||
import { formatDate } from "@/utils/date";
|
||||
import { CodeDiff, hljs } from "v-code-diff";
|
||||
import markdown from "highlight.js/lib/languages/markdown";
|
||||
import {
|
||||
hasValidCurrentStateToken,
|
||||
normalizeSnapshotOrderedValue,
|
||||
|
|
@ -492,6 +520,8 @@ import {
|
|||
SNAPSHOT_SECRET_REDACTED
|
||||
} from "./agentSnapshotDisplayUtils.mjs";
|
||||
|
||||
hljs.registerLanguage("markdown", markdown);
|
||||
|
||||
const FALLBACK_PLUGIN_NAME_KEYS = {
|
||||
SYSTEM_PLUGIN_WEATHER: "agentSnapshot.plugin.SYSTEM_PLUGIN_WEATHER",
|
||||
SYSTEM_PLUGIN_MUSIC: "agentSnapshot.plugin.SYSTEM_PLUGIN_MUSIC",
|
||||
|
|
@ -559,6 +589,9 @@ const CHAT_HISTORY_CONF_LABEL_KEYS = {
|
|||
};
|
||||
export default {
|
||||
name: "AgentSnapshotDialog",
|
||||
components: {
|
||||
CodeDiff
|
||||
},
|
||||
props: {
|
||||
visible: {
|
||||
type: Boolean,
|
||||
|
|
@ -1543,6 +1576,18 @@ export default {
|
|||
}
|
||||
return "text";
|
||||
},
|
||||
shouldUseCodeDiff(item) {
|
||||
return Boolean(
|
||||
item &&
|
||||
!item.single &&
|
||||
(item.displayType === "markdown" || item.complex || item.field === "summaryMemory")
|
||||
);
|
||||
},
|
||||
codeDiffLanguage(item) {
|
||||
return item?.displayType === "markdown" || item?.field === "summaryMemory"
|
||||
? "markdown"
|
||||
: "json";
|
||||
},
|
||||
valueClass(item) {
|
||||
return [`is-${item.displayType || "text"}`];
|
||||
},
|
||||
|
|
@ -2067,10 +2112,20 @@ export default {
|
|||
@import '@/styles/global.scss';
|
||||
|
||||
::v-deep .el-dialog {
|
||||
margin-top: 6vh !important;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
margin: 32px auto !important;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
max-height: calc(100vh - 64px);
|
||||
}
|
||||
|
||||
::v-deep .el-dialog__wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
::v-deep .el-dialog__header {
|
||||
|
|
@ -2139,6 +2194,7 @@ export default {
|
|||
}
|
||||
|
||||
::v-deep .el-dialog__body {
|
||||
overflow-y: auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
|
|
@ -2273,7 +2329,7 @@ export default {
|
|||
|
||||
.snapshot-diff {
|
||||
min-height: 220px;
|
||||
max-height: 62vh;
|
||||
max-height: 68vh;
|
||||
overflow: auto;
|
||||
padding-right: 2px;
|
||||
@include scrollbar-style;
|
||||
|
|
@ -2341,6 +2397,12 @@ export default {
|
|||
border-left: 0;
|
||||
}
|
||||
|
||||
.diff-code-wrapper {
|
||||
padding: 0 14px 1px;
|
||||
text-align: left;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.diff-pane-title {
|
||||
margin-bottom: 8px;
|
||||
color: #3d4566;
|
||||
|
|
@ -2388,6 +2450,43 @@ export default {
|
|||
text-align: left;
|
||||
}
|
||||
|
||||
::v-deep .code-diff-view,
|
||||
::v-deep .code-diff-view .blob-num,
|
||||
::v-deep .code-diff-view .blob-code-inner,
|
||||
::v-deep .code-diff-view .file-header {
|
||||
font-family: Avenir, Helvetica, Arial, sans-serif;
|
||||
}
|
||||
|
||||
::v-deep .code-diff-view::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
::v-deep .code-diff-view::-webkit-scrollbar-thumb {
|
||||
background: #a1c9fd;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
::v-deep .code-diff-view::-webkit-scrollbar-track {
|
||||
background: #f0f3fe;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
::v-deep .code-diff-view .blob-code-inner {
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
::v-deep .code-diff-view .hljs-emphasis,
|
||||
::v-deep .code-diff-view em {
|
||||
font-style: normal !important;
|
||||
}
|
||||
|
||||
::v-deep .code-diff-view .diff-table .blob-code-deletion .x,
|
||||
::v-deep .code-diff-view .diff-table .blob-code-addition .x {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.function-change-view {
|
||||
padding: 16px;
|
||||
background: #fff;
|
||||
|
|
|
|||
|
|
@ -490,7 +490,7 @@ export default {
|
|||
'device.firmwareVersion': 'Firmware-Version',
|
||||
'device.bindTime': 'Bindungszeit',
|
||||
'device.lastConversation': 'Letzte Konversation',
|
||||
'device.remark': 'Bemerkung',
|
||||
'device.alias': 'Gerätealias',
|
||||
'device.autoUpdate': 'Automatische Aktualisierung',
|
||||
'device.operation': 'Operation',
|
||||
'device.search': 'Suchen',
|
||||
|
|
@ -505,9 +505,9 @@ export default {
|
|||
'device.confirmBatchUnbind': 'Sind Sie sicher, dass Sie {count} ausgewählte Geräte entbinden möchten?',
|
||||
'device.batchUnbindSuccess': 'Erfolgreich {count} Geräte entbunden',
|
||||
'device.batchUnbindError': 'Fehler beim Massen-Entbinden aufgetreten',
|
||||
'device.remarkTooLong': 'Bemerkung darf 64 Zeichen nicht überschreiten',
|
||||
'device.remarkSaved': 'Bemerkung erfolgreich gespeichert',
|
||||
'device.remarkSaveFailed': 'Speichern der Bemerkung fehlgeschlagen',
|
||||
'device.aliasTooLong': 'Gerätealias darf 64 Zeichen nicht überschreiten',
|
||||
'device.aliasSaved': 'Gerätealias erfolgreich gespeichert',
|
||||
'device.aliasSaveFailed': 'Speichern des Gerätealias fehlgeschlagen',
|
||||
'device.confirmUnbind': 'Sind Sie sicher, dass Sie dieses Gerät entbinden möchten?',
|
||||
'device.unbindSuccess': 'Gerät erfolgreich entbunden',
|
||||
'device.unbindFailed': 'Entbinden des Geräts fehlgeschlagen',
|
||||
|
|
@ -752,8 +752,10 @@ export default {
|
|||
'paramManagement.search': 'Suchen',
|
||||
'paramManagement.paramCode': 'Parameter-Code',
|
||||
'paramManagement.paramValue': 'Parameter-Wert',
|
||||
'paramManagement.valueType': 'Typ',
|
||||
'paramManagement.remark': 'Bemerkung',
|
||||
'paramManagement.operation': 'Operation',
|
||||
'paramManagement.select': 'Auswahl',
|
||||
'paramManagement.hide': 'Ausblenden',
|
||||
'paramManagement.view': 'Anzeigen',
|
||||
'paramManagement.deselectAll': 'Alle abwählen',
|
||||
|
|
@ -761,11 +763,29 @@ export default {
|
|||
'paramManagement.add': 'Hinzufügen',
|
||||
'paramManagement.delete': 'Löschen',
|
||||
'paramManagement.edit': 'Bearbeiten',
|
||||
'paramManagement.refresh': 'Aktualisieren',
|
||||
'paramManagement.itemsPerPage': 'Einträge/Seite',
|
||||
'paramManagement.firstPage': 'Erste Seite',
|
||||
'paramManagement.prevPage': 'Vorherige Seite',
|
||||
'paramManagement.nextPage': 'Nächste Seite',
|
||||
'paramManagement.totalRecords': 'Insgesamt {total} Datensätze',
|
||||
'paramManagement.totalRecords': '{total} insgesamt',
|
||||
'paramManagement.selectedCount': '{count} ausgewählt',
|
||||
'paramManagement.groupHint': 'Nach Namespace gruppiert',
|
||||
'paramManagement.emptyResult': 'Keine passenden Parameter',
|
||||
'paramManagement.group.all': 'Alle',
|
||||
'paramManagement.group.server': 'Server',
|
||||
'paramManagement.group.plugins': 'Plugins',
|
||||
'paramManagement.group.log': 'Logging',
|
||||
'paramManagement.group.session': 'Sitzung',
|
||||
'paramManagement.group.general': 'Allgemein',
|
||||
'paramManagement.subgroup.root': 'Basis',
|
||||
'paramManagement.subgroup.auth': 'Auth',
|
||||
'paramManagement.subgroup.connection': 'Verbindung',
|
||||
'paramManagement.subgroup.registry': 'Registry',
|
||||
'paramManagement.subgroup.resilience': 'Resilience',
|
||||
'paramManagement.subgroup.metrics': 'Metriken',
|
||||
'paramManagement.subgroup.tracing': 'Tracing',
|
||||
'paramManagement.subgroup.plugin': 'Plugin · {name}',
|
||||
'paramManagement.addParam': 'Parameter hinzufügen',
|
||||
'paramManagement.editParam': 'Parameter bearbeiten',
|
||||
'paramManagement.getParamsListFailed': 'Parameterliste konnte nicht abgerufen werden',
|
||||
|
|
|
|||
|
|
@ -490,7 +490,7 @@ export default {
|
|||
'device.firmwareVersion': 'Firmware Version',
|
||||
'device.bindTime': 'Binding Time',
|
||||
'device.lastConversation': 'Last Conversation',
|
||||
'device.remark': 'Remark',
|
||||
'device.alias': 'Device Alias',
|
||||
'device.autoUpdate': 'Auto Update',
|
||||
'device.operation': 'Operation',
|
||||
'device.search': 'Search',
|
||||
|
|
@ -505,9 +505,9 @@ export default {
|
|||
'device.confirmBatchUnbind': 'Are you sure you want to unbind {count} selected devices?',
|
||||
'device.batchUnbindSuccess': 'Successfully unbound {count} devices',
|
||||
'device.batchUnbindError': 'Error occurred during batch unbinding',
|
||||
'device.remarkTooLong': 'Remark cannot exceed 64 characters',
|
||||
'device.remarkSaved': 'Remark saved successfully',
|
||||
'device.remarkSaveFailed': 'Failed to save remark',
|
||||
'device.aliasTooLong': 'Device alias cannot exceed 64 characters',
|
||||
'device.aliasSaved': 'Device alias saved successfully',
|
||||
'device.aliasSaveFailed': 'Failed to save device alias',
|
||||
'device.confirmUnbind': 'Are you sure you want to unbind this device?',
|
||||
'device.unbindSuccess': 'Device unbound successfully',
|
||||
'device.unbindFailed': 'Failed to unbind device',
|
||||
|
|
@ -752,8 +752,10 @@ export default {
|
|||
'paramManagement.search': 'Search',
|
||||
'paramManagement.paramCode': 'Parameter Code',
|
||||
'paramManagement.paramValue': 'Parameter Value',
|
||||
'paramManagement.valueType': 'Type',
|
||||
'paramManagement.remark': 'Remark',
|
||||
'paramManagement.operation': 'Operation',
|
||||
'paramManagement.select': 'Select',
|
||||
'paramManagement.hide': 'Hide',
|
||||
'paramManagement.view': 'View',
|
||||
'paramManagement.deselectAll': 'Deselect All',
|
||||
|
|
@ -761,11 +763,29 @@ export default {
|
|||
'paramManagement.add': 'Add',
|
||||
'paramManagement.delete': 'Delete',
|
||||
'paramManagement.edit': 'Edit',
|
||||
'paramManagement.refresh': 'Refresh',
|
||||
'paramManagement.itemsPerPage': 'items/page',
|
||||
'paramManagement.firstPage': 'First Page',
|
||||
'paramManagement.prevPage': 'Previous Page',
|
||||
'paramManagement.nextPage': 'Next Page',
|
||||
'paramManagement.totalRecords': 'Total {total} records',
|
||||
'paramManagement.totalRecords': '{total} total',
|
||||
'paramManagement.selectedCount': '{count} selected',
|
||||
'paramManagement.groupHint': 'Grouped by namespace',
|
||||
'paramManagement.emptyResult': 'No matching parameters',
|
||||
'paramManagement.group.all': 'All',
|
||||
'paramManagement.group.server': 'Server',
|
||||
'paramManagement.group.plugins': 'Plugins',
|
||||
'paramManagement.group.log': 'Logging',
|
||||
'paramManagement.group.session': 'Session',
|
||||
'paramManagement.group.general': 'General',
|
||||
'paramManagement.subgroup.root': 'Basics',
|
||||
'paramManagement.subgroup.auth': 'Auth',
|
||||
'paramManagement.subgroup.connection': 'Connection',
|
||||
'paramManagement.subgroup.registry': 'Registry',
|
||||
'paramManagement.subgroup.resilience': 'Resilience',
|
||||
'paramManagement.subgroup.metrics': 'Metrics',
|
||||
'paramManagement.subgroup.tracing': 'Tracing',
|
||||
'paramManagement.subgroup.plugin': 'Plugin · {name}',
|
||||
'paramManagement.addParam': 'Add Parameter',
|
||||
'paramManagement.editParam': 'Edit Parameter',
|
||||
'paramManagement.getParamsListFailed': 'Failed to get parameter list',
|
||||
|
|
|
|||
|
|
@ -490,7 +490,7 @@ export default {
|
|||
'device.firmwareVersion': 'Versão do Firmware',
|
||||
'device.bindTime': 'Data de Vinculação',
|
||||
'device.lastConversation': 'Última Conversa',
|
||||
'device.remark': 'Observação',
|
||||
'device.alias': 'Alias do dispositivo',
|
||||
'device.autoUpdate': 'Atualização Automática',
|
||||
'device.operation': 'Operação',
|
||||
'device.search': 'Pesquisar',
|
||||
|
|
@ -505,9 +505,9 @@ export default {
|
|||
'device.confirmBatchUnbind': 'Tem certeza de que deseja desvincular {count} dispositivos selecionados?',
|
||||
'device.batchUnbindSuccess': '{count} dispositivos desvinculados com sucesso',
|
||||
'device.batchUnbindError': 'Ocorreu um erro durante a desvinculação em lote',
|
||||
'device.remarkTooLong': 'A observação não pode exceder 64 caracteres',
|
||||
'device.remarkSaved': 'Observação salva com sucesso',
|
||||
'device.remarkSaveFailed': 'Falha ao salvar observação',
|
||||
'device.aliasTooLong': 'O alias do dispositivo não pode exceder 64 caracteres',
|
||||
'device.aliasSaved': 'Alias do dispositivo salvo com sucesso',
|
||||
'device.aliasSaveFailed': 'Falha ao salvar o alias do dispositivo',
|
||||
'device.confirmUnbind': 'Tem certeza de que deseja desvincular este dispositivo?',
|
||||
'device.unbindSuccess': 'Dispositivo desvinculado com sucesso',
|
||||
'device.unbindFailed': 'Falha ao desvincular dispositivo',
|
||||
|
|
@ -752,8 +752,10 @@ export default {
|
|||
'paramManagement.search': 'Pesquisar',
|
||||
'paramManagement.paramCode': 'Código do Parâmetro',
|
||||
'paramManagement.paramValue': 'Valor do Parâmetro',
|
||||
'paramManagement.valueType': 'Tipo',
|
||||
'paramManagement.remark': 'Observação',
|
||||
'paramManagement.operation': 'Operação',
|
||||
'paramManagement.select': 'Selecionar',
|
||||
'paramManagement.hide': 'Ocultar',
|
||||
'paramManagement.view': 'Visualizar',
|
||||
'paramManagement.deselectAll': 'Desmarcar Tudo',
|
||||
|
|
@ -761,11 +763,29 @@ export default {
|
|||
'paramManagement.add': 'Adicionar',
|
||||
'paramManagement.delete': 'Excluir',
|
||||
'paramManagement.edit': 'Editar',
|
||||
'paramManagement.refresh': 'Atualizar',
|
||||
'paramManagement.itemsPerPage': 'itens/página',
|
||||
'paramManagement.firstPage': 'Primeira Página',
|
||||
'paramManagement.prevPage': 'Página Anterior',
|
||||
'paramManagement.nextPage': 'Próxima Página',
|
||||
'paramManagement.totalRecords': 'Total de {total} registros',
|
||||
'paramManagement.totalRecords': '{total} no total',
|
||||
'paramManagement.selectedCount': '{count} selecionados',
|
||||
'paramManagement.groupHint': 'Agrupado por namespace',
|
||||
'paramManagement.emptyResult': 'Nenhum parâmetro correspondente',
|
||||
'paramManagement.group.all': 'Todos',
|
||||
'paramManagement.group.server': 'Servidor',
|
||||
'paramManagement.group.plugins': 'Plugins',
|
||||
'paramManagement.group.log': 'Logs',
|
||||
'paramManagement.group.session': 'Sessão',
|
||||
'paramManagement.group.general': 'Geral',
|
||||
'paramManagement.subgroup.root': 'Básico',
|
||||
'paramManagement.subgroup.auth': 'Auth',
|
||||
'paramManagement.subgroup.connection': 'Conexão',
|
||||
'paramManagement.subgroup.registry': 'Registry',
|
||||
'paramManagement.subgroup.resilience': 'Resilience',
|
||||
'paramManagement.subgroup.metrics': 'Métricas',
|
||||
'paramManagement.subgroup.tracing': 'Tracing',
|
||||
'paramManagement.subgroup.plugin': 'Plugin · {name}',
|
||||
'paramManagement.addParam': 'Adicionar Parâmetro',
|
||||
'paramManagement.editParam': 'Editar Parâmetro',
|
||||
'paramManagement.getParamsListFailed': 'Falha ao obter lista de parâmetros',
|
||||
|
|
|
|||
|
|
@ -490,7 +490,7 @@ export default {
|
|||
'device.firmwareVersion': 'Phiên bản firmware',
|
||||
'device.bindTime': 'Thời gian liên kết',
|
||||
'device.lastConversation': 'Cuộc trò chuyện cuối',
|
||||
'device.remark': 'Ghi chú',
|
||||
'device.alias': 'Bí danh thiết bị',
|
||||
'device.autoUpdate': 'Tự động cập nhật',
|
||||
'device.operation': 'Thao tác',
|
||||
'device.search': 'Tìm kiếm',
|
||||
|
|
@ -505,9 +505,9 @@ export default {
|
|||
'device.confirmBatchUnbind': 'Bạn có chắc chắn muốn hủy liên kết {count} thiết bị đã chọn?',
|
||||
'device.batchUnbindSuccess': 'Đã hủy liên kết thành công {count} thiết bị',
|
||||
'device.batchUnbindError': 'Đã xảy ra lỗi khi hủy liên kết hàng loạt',
|
||||
'device.remarkTooLong': 'Ghi chú không được vượt quá 64 ký tự',
|
||||
'device.remarkSaved': 'Đã lưu ghi chú thành công',
|
||||
'device.remarkSaveFailed': 'Lưu ghi chú thất bại',
|
||||
'device.aliasTooLong': 'Bí danh thiết bị không được vượt quá 64 ký tự',
|
||||
'device.aliasSaved': 'Đã lưu bí danh thiết bị thành công',
|
||||
'device.aliasSaveFailed': 'Lưu bí danh thiết bị thất bại',
|
||||
'device.confirmUnbind': 'Bạn có chắc chắn muốn hủy liên kết thiết bị này?',
|
||||
'device.unbindSuccess': 'Đã hủy liên kết thiết bị thành công',
|
||||
'device.unbindFailed': 'Hủy liên kết thiết bị thất bại',
|
||||
|
|
@ -752,8 +752,10 @@ export default {
|
|||
'paramManagement.search': 'Tìm kiếm',
|
||||
'paramManagement.paramCode': 'Mã tham số',
|
||||
'paramManagement.paramValue': 'Giá trị tham số',
|
||||
'paramManagement.valueType': 'Loại',
|
||||
'paramManagement.remark': 'Ghi chú',
|
||||
'paramManagement.operation': 'Thao tác',
|
||||
'paramManagement.select': 'Chọn',
|
||||
'paramManagement.hide': 'Ẩn',
|
||||
'paramManagement.view': 'Xem',
|
||||
'paramManagement.deselectAll': 'Bỏ chọn tất cả',
|
||||
|
|
@ -761,11 +763,29 @@ export default {
|
|||
'paramManagement.add': 'Thêm',
|
||||
'paramManagement.delete': 'Xóa',
|
||||
'paramManagement.edit': 'Chỉnh sửa',
|
||||
'paramManagement.refresh': 'Làm mới',
|
||||
'paramManagement.itemsPerPage': 'mục/trang',
|
||||
'paramManagement.firstPage': 'Trang đầu',
|
||||
'paramManagement.prevPage': 'Trang trước',
|
||||
'paramManagement.nextPage': 'Trang sau',
|
||||
'paramManagement.totalRecords': 'Tổng cộng {total} bản ghi',
|
||||
'paramManagement.totalRecords': 'Tổng {total}',
|
||||
'paramManagement.selectedCount': 'Đã chọn {count}',
|
||||
'paramManagement.groupHint': 'Nhóm theo namespace',
|
||||
'paramManagement.emptyResult': 'Không có tham số phù hợp',
|
||||
'paramManagement.group.all': 'Tất cả',
|
||||
'paramManagement.group.server': 'Máy chủ',
|
||||
'paramManagement.group.plugins': 'Plugin',
|
||||
'paramManagement.group.log': 'Nhật ký',
|
||||
'paramManagement.group.session': 'Phiên',
|
||||
'paramManagement.group.general': 'Chung',
|
||||
'paramManagement.subgroup.root': 'Cơ bản',
|
||||
'paramManagement.subgroup.auth': 'Xác thực',
|
||||
'paramManagement.subgroup.connection': 'Kết nối',
|
||||
'paramManagement.subgroup.registry': 'Đăng ký',
|
||||
'paramManagement.subgroup.resilience': 'Resilience',
|
||||
'paramManagement.subgroup.metrics': 'Chỉ số',
|
||||
'paramManagement.subgroup.tracing': 'Tracing',
|
||||
'paramManagement.subgroup.plugin': 'Plugin · {name}',
|
||||
'paramManagement.addParam': 'Thêm tham số',
|
||||
'paramManagement.editParam': 'Chỉnh sửa tham số',
|
||||
'paramManagement.getParamsListFailed': 'Không thể lấy danh sách tham số',
|
||||
|
|
|
|||
|
|
@ -490,7 +490,7 @@ export default {
|
|||
'device.firmwareVersion': '固件版本',
|
||||
'device.bindTime': '绑定时间',
|
||||
'device.lastConversation': '最后对话',
|
||||
'device.remark': '备注',
|
||||
'device.alias': '设备别名',
|
||||
'device.autoUpdate': '自动升级',
|
||||
'device.operation': '操作',
|
||||
'device.search': '搜索',
|
||||
|
|
@ -505,9 +505,9 @@ export default {
|
|||
'device.confirmBatchUnbind': '确认要解绑选中的 {count} 台设备吗?',
|
||||
'device.batchUnbindSuccess': '成功解绑 {count} 台设备',
|
||||
'device.batchUnbindError': '批量解绑过程中出现错误',
|
||||
'device.remarkTooLong': '备注不能超过 64 字符',
|
||||
'device.remarkSaved': '备注已保存',
|
||||
'device.remarkSaveFailed': '备注保存失败',
|
||||
'device.aliasTooLong': '设备别名不能超过 64 字符',
|
||||
'device.aliasSaved': '设备别名已保存',
|
||||
'device.aliasSaveFailed': '设备别名保存失败',
|
||||
'device.confirmUnbind': '确认要解绑该设备吗?',
|
||||
'device.unbindSuccess': '设备解绑成功',
|
||||
'device.unbindFailed': '设备解绑失败',
|
||||
|
|
@ -752,8 +752,10 @@ export default {
|
|||
'paramManagement.search': '搜索',
|
||||
'paramManagement.paramCode': '参数编码',
|
||||
'paramManagement.paramValue': '参数值',
|
||||
'paramManagement.valueType': '类型',
|
||||
'paramManagement.remark': '备注',
|
||||
'paramManagement.operation': '操作',
|
||||
'paramManagement.select': '选择',
|
||||
'paramManagement.hide': '隐藏',
|
||||
'paramManagement.view': '查看',
|
||||
'paramManagement.deselectAll': '取消全选',
|
||||
|
|
@ -761,11 +763,29 @@ export default {
|
|||
'paramManagement.add': '新增',
|
||||
'paramManagement.delete': '删除',
|
||||
'paramManagement.edit': '编辑',
|
||||
'paramManagement.refresh': '刷新',
|
||||
'paramManagement.itemsPerPage': '条/页',
|
||||
'paramManagement.firstPage': '首页',
|
||||
'paramManagement.prevPage': '上一页',
|
||||
'paramManagement.nextPage': '下一页',
|
||||
'paramManagement.totalRecords': '共{total}条记录',
|
||||
'paramManagement.totalRecords': '共{total}条',
|
||||
'paramManagement.selectedCount': '已选 {count} 项',
|
||||
'paramManagement.groupHint': '按命名空间聚合展示',
|
||||
'paramManagement.emptyResult': '没有匹配的参数',
|
||||
'paramManagement.group.all': '全部',
|
||||
'paramManagement.group.server': '服务端',
|
||||
'paramManagement.group.plugins': '插件',
|
||||
'paramManagement.group.log': '日志',
|
||||
'paramManagement.group.session': '会话',
|
||||
'paramManagement.group.general': '通用',
|
||||
'paramManagement.subgroup.root': '基础配置',
|
||||
'paramManagement.subgroup.auth': '鉴权',
|
||||
'paramManagement.subgroup.connection': '连接',
|
||||
'paramManagement.subgroup.registry': '实例注册',
|
||||
'paramManagement.subgroup.resilience': '韧性 / 熔断',
|
||||
'paramManagement.subgroup.metrics': '指标',
|
||||
'paramManagement.subgroup.tracing': '链路追踪',
|
||||
'paramManagement.subgroup.plugin': '插件 · {name}',
|
||||
'paramManagement.addParam': '新增参数',
|
||||
'paramManagement.editParam': '编辑参数',
|
||||
'paramManagement.getParamsListFailed': '获取参数列表失败',
|
||||
|
|
|
|||
|
|
@ -490,7 +490,7 @@ export default {
|
|||
'device.firmwareVersion': '固件版本',
|
||||
'device.bindTime': '綁定時間',
|
||||
'device.lastConversation': '最後對話',
|
||||
'device.remark': '備註',
|
||||
'device.alias': '設備別名',
|
||||
'device.autoUpdate': '自動升級',
|
||||
'device.operation': '操作',
|
||||
'device.search': '搜索',
|
||||
|
|
@ -505,9 +505,9 @@ export default {
|
|||
'device.confirmBatchUnbind': '確認要解綁選中的 {count} 台設備嗎?',
|
||||
'device.batchUnbindSuccess': '成功解綁 {count} 台設備',
|
||||
'device.batchUnbindError': '批量解綁過程中出現錯誤',
|
||||
'device.remarkTooLong': '備註不能超過 64 字符',
|
||||
'device.remarkSaved': '備註已保存',
|
||||
'device.remarkSaveFailed': '備註保存失敗',
|
||||
'device.aliasTooLong': '設備別名不能超過 64 字符',
|
||||
'device.aliasSaved': '設備別名已保存',
|
||||
'device.aliasSaveFailed': '設備別名保存失敗',
|
||||
'device.confirmUnbind': '確認要解綁該設備嗎?',
|
||||
'device.unbindSuccess': '設備解綁成功',
|
||||
'device.unbindFailed': '設備解綁失敗',
|
||||
|
|
@ -752,8 +752,10 @@ export default {
|
|||
'paramManagement.search': '搜索',
|
||||
'paramManagement.paramCode': '參數編碼',
|
||||
'paramManagement.paramValue': '參數值',
|
||||
'paramManagement.valueType': '類型',
|
||||
'paramManagement.remark': '備註',
|
||||
'paramManagement.operation': '操作',
|
||||
'paramManagement.select': '選擇',
|
||||
'paramManagement.hide': '隱藏',
|
||||
'paramManagement.view': '查看',
|
||||
'paramManagement.deselectAll': '取消全選',
|
||||
|
|
@ -761,11 +763,29 @@ export default {
|
|||
'paramManagement.add': '新增',
|
||||
'paramManagement.delete': '刪除',
|
||||
'paramManagement.edit': '編輯',
|
||||
'paramManagement.refresh': '重新整理',
|
||||
'paramManagement.itemsPerPage': '條/頁',
|
||||
'paramManagement.firstPage': '首頁',
|
||||
'paramManagement.prevPage': '上一頁',
|
||||
'paramManagement.nextPage': '下一頁',
|
||||
'paramManagement.totalRecords': '共{total}條記錄',
|
||||
'paramManagement.totalRecords': '共{total}條',
|
||||
'paramManagement.selectedCount': '已選 {count} 項',
|
||||
'paramManagement.groupHint': '依命名空間聚合顯示',
|
||||
'paramManagement.emptyResult': '沒有符合的參數',
|
||||
'paramManagement.group.all': '全部',
|
||||
'paramManagement.group.server': '服務端',
|
||||
'paramManagement.group.plugins': '外掛',
|
||||
'paramManagement.group.log': '日誌',
|
||||
'paramManagement.group.session': '會話',
|
||||
'paramManagement.group.general': '通用',
|
||||
'paramManagement.subgroup.root': '基礎設定',
|
||||
'paramManagement.subgroup.auth': '鑑權',
|
||||
'paramManagement.subgroup.connection': '連線',
|
||||
'paramManagement.subgroup.registry': '實例註冊',
|
||||
'paramManagement.subgroup.resilience': '韌性 / 熔斷',
|
||||
'paramManagement.subgroup.metrics': '指標',
|
||||
'paramManagement.subgroup.tracing': '鏈路追蹤',
|
||||
'paramManagement.subgroup.plugin': '外掛 · {name}',
|
||||
'paramManagement.addParam': '新增參數',
|
||||
'paramManagement.editParam': '編輯參數',
|
||||
'paramManagement.getParamsListFailed': '獲取參數列表失敗',
|
||||
|
|
|
|||
|
|
@ -846,21 +846,20 @@ export default {
|
|||
font-size: 12px;
|
||||
color: #686f85;
|
||||
text-align: left;
|
||||
gap: 4px;
|
||||
|
||||
.online {
|
||||
margin-left: 4px;
|
||||
color: #686f85;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
|
||||
.status-dot {
|
||||
margin-top: -3px;
|
||||
margin-right: 4px;
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
background: #4eb36c;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -871,12 +870,11 @@ export default {
|
|||
gap: 4px;
|
||||
|
||||
.status-dot {
|
||||
margin-top: -3px;
|
||||
margin-right: 4px;
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
background: #999;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,13 +40,13 @@
|
|||
<el-tag v-if="scope.row.deviceStatus === 'online'" type="success">{{ $t('device.online') }}</el-tag>
|
||||
<el-tag v-else type="danger">{{ $t('device.offline') }}</el-tag>
|
||||
</template>
|
||||
<template slot="remark" slot-scope="scope">
|
||||
<el-input v-show="scope.row.isEdit" v-model="scope.row.remark" size="mini" maxlength="64" show-word-limit
|
||||
@blur="onRemarkBlur(scope.row)" @keyup.enter.native="onRemarkEnter(scope.row)" />
|
||||
<span v-show="!scope.row.isEdit" class="remark-view">
|
||||
<template slot="alias" slot-scope="scope">
|
||||
<el-input v-show="scope.row.isEdit" v-model="scope.row.alias" size="mini" maxlength="64" show-word-limit
|
||||
@blur="onAliasBlur(scope.row)" @keyup.enter.native="onAliasEnter(scope.row)" />
|
||||
<span v-show="!scope.row.isEdit" class="alias-view">
|
||||
<i class="el-icon-edit" @click="scope.row.isEdit = true" style="cursor: pointer;"></i>
|
||||
<span @click="scope.row.isEdit = true">
|
||||
{{ scope.row.remark || '-' }}
|
||||
{{ scope.row.alias || '-' }}
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
|
|
@ -170,7 +170,7 @@ export default {
|
|||
if (this.mqttServiceAvailable) {
|
||||
columns.push({ prop: 'deviceStatus', label: this.$t('device.deviceStatus'), align: 'center' });
|
||||
}
|
||||
columns.push({ prop: 'remark', label: this.$t('device.remark'), align: 'center' });
|
||||
columns.push({ prop: 'alias', label: this.$t('device.alias'), align: 'center' });
|
||||
columns.push({ prop: 'otaSwitch', label: this.$t('device.autoUpdate'), align: 'center' });
|
||||
return columns;
|
||||
},
|
||||
|
|
@ -262,39 +262,39 @@ export default {
|
|||
handleManualAddDevice() {
|
||||
this.manualAddDeviceDialogVisible = true;
|
||||
},
|
||||
submitRemark(row) {
|
||||
submitAlias(row) {
|
||||
if (row._submitting) return;
|
||||
|
||||
const text = (row.remark || '').trim();
|
||||
const text = (row.alias || '').trim();
|
||||
if (text.length > 64) {
|
||||
this.$message.warning(this.$t('device.remarkTooLong'));
|
||||
this.$message.warning(this.$t('device.aliasTooLong'));
|
||||
return;
|
||||
}
|
||||
if (text === row._originalRemark) {
|
||||
if (text === row._originalAlias) {
|
||||
return;
|
||||
}
|
||||
|
||||
row._submitting = true;
|
||||
this.updateDeviceInfo(row.device_id, { alias: text }, (ok, resp) => {
|
||||
if (ok) {
|
||||
row._originalRemark = text;
|
||||
this.$message.success(this.$t('device.remarkSaved'));
|
||||
row._originalAlias = text;
|
||||
this.$message.success(this.$t('device.aliasSaved'));
|
||||
} else {
|
||||
row.remark = row._originalRemark;
|
||||
this.$message.error(resp.msg || this.$t('device.remarkSaveFailed'));
|
||||
row.alias = row._originalAlias;
|
||||
this.$message.error(resp.msg || this.$t('device.aliasSaveFailed'));
|
||||
}
|
||||
row._submitting = false;
|
||||
});
|
||||
},
|
||||
onRemarkBlur(row) {
|
||||
onAliasBlur(row) {
|
||||
row.isEdit = false;
|
||||
setTimeout(() => {
|
||||
this.submitRemark(row);
|
||||
this.submitAlias(row);
|
||||
}, 100);
|
||||
},
|
||||
onRemarkEnter(row) {
|
||||
onAliasEnter(row) {
|
||||
row.isEdit = false;
|
||||
this.submitRemark(row);
|
||||
this.submitAlias(row);
|
||||
},
|
||||
handleUnbind(device_id) {
|
||||
this.$confirm(this.$t('device.confirmUnbind'), this.$t('message.warning'), {
|
||||
|
|
@ -346,8 +346,8 @@ export default {
|
|||
macAddress: device.macAddress,
|
||||
bindTime: formatCreateDate(device.createDateTimestamp, device.createDate),
|
||||
lastConversation: formatTimestamp(device.lastConnectedAtTimestamp),
|
||||
remark: device.alias,
|
||||
_originalRemark: device.alias,
|
||||
alias: device.alias,
|
||||
_originalAlias: device.alias,
|
||||
isEdit: false,
|
||||
_submitting: false,
|
||||
otaSwitch: device.autoUpdate === 1,
|
||||
|
|
|
|||
|
|
@ -148,6 +148,8 @@
|
|||
:title="$t('knowledgeFileUpload.uploadDocument')"
|
||||
:visible.sync="uploadDialogVisible"
|
||||
width="800px"
|
||||
:close-on-click-modal="false"
|
||||
:confirmLoading="uploading"
|
||||
@close="handleUploadDialogClose"
|
||||
@confirm="handleBatchUploadSubmit"
|
||||
>
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
91
main/manager-web/tests/date.test.mjs
Normal file
91
main/manager-web/tests/date.test.mjs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import * as date from '../src/utils/date.js';
|
||||
|
||||
describe('date utilities', () => {
|
||||
it('module loads and exports functions', () => {
|
||||
expect(date).toBeDefined();
|
||||
expect(Object.keys(date).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
describe('isDate', () => {
|
||||
it('returns false for null and undefined', () => {
|
||||
expect(date.isDate(null)).toBe(false);
|
||||
expect(date.isDate(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for an invalid date string', () => {
|
||||
expect(date.isDate('not-a-date')).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true for valid date strings', () => {
|
||||
expect(date.isDate('2026-09-02')).toBe(true);
|
||||
expect(date.isDate('2026-09-02T10:00:00Z')).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true for Date objects', () => {
|
||||
expect(date.isDate(new Date())).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isDateObject', () => {
|
||||
it('returns true only for Date instances', () => {
|
||||
expect(date.isDateObject(new Date())).toBe(true);
|
||||
expect(date.isDateObject('2026-09-02')).toBe(false);
|
||||
expect(date.isDateObject(1234567890)).toBe(false);
|
||||
expect(date.isDateObject(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('toDate', () => {
|
||||
it('returns null for falsy values', () => {
|
||||
expect(date.toDate(null)).toBe(null);
|
||||
expect(date.toDate(undefined)).toBe(null);
|
||||
expect(date.toDate('')).toBe(null);
|
||||
});
|
||||
|
||||
it('returns null for invalid input', () => {
|
||||
expect(date.toDate('not-a-date')).toBe(null);
|
||||
});
|
||||
|
||||
it('returns a Date for valid input', () => {
|
||||
const result = date.toDate('2026-09-02');
|
||||
expect(result).toBeInstanceOf(Date);
|
||||
expect(result.getFullYear()).toBe(2026);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatDate', () => {
|
||||
it('returns empty string for invalid input', () => {
|
||||
expect(date.formatDate(null)).toBe('');
|
||||
expect(date.formatDate('not-a-date')).toBe('');
|
||||
});
|
||||
|
||||
it('formats with the default pattern', () => {
|
||||
const result = date.formatDate('2026-09-02T10:20:30Z');
|
||||
expect(result).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
|
||||
});
|
||||
|
||||
it('supports a custom format pattern', () => {
|
||||
const result = date.formatDate(new Date(2026, 8, 2, 13, 4, 5), 'yyyy/MM/dd');
|
||||
expect(result).toBe('2026/09/02');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatAddDate', () => {
|
||||
it('returns empty string when input is not a date', () => {
|
||||
expect(date.formatAddDate(null, 'yyyy-MM-dd', 5)).toBe('');
|
||||
});
|
||||
|
||||
it('returns formatted date unchanged when addDay is falsy', () => {
|
||||
// The implementation has a quirk: `if (!addDay)` adds the days (the condition is inverted),
|
||||
// so passing 0 with a date input still applies it (no-op since 0).
|
||||
const result = date.formatAddDate('2026-09-02', 'yyyy-MM-dd', 0);
|
||||
expect(result).toBe('2026-09-02');
|
||||
});
|
||||
|
||||
it('formats with the default pattern when none given', () => {
|
||||
const result = date.formatAddDate(new Date(2026, 8, 2, 13, 4, 5), '', 0);
|
||||
expect(result).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,52 +1,75 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
compareTimestamps,
|
||||
formatCreateDate,
|
||||
formatTimestamp,
|
||||
hasTimestampValue,
|
||||
parseTimestamp,
|
||||
parseLegacyDate,
|
||||
formatTimestamp,
|
||||
formatCreateDate,
|
||||
compareTimestamps,
|
||||
} from '../src/utils/deviceTime.mjs';
|
||||
|
||||
const TIMESTAMP = 1783689702000;
|
||||
|
||||
test('accepts epoch milliseconds as a number or numeric string', () => {
|
||||
assert.equal(parseTimestamp(TIMESTAMP), TIMESTAMP);
|
||||
assert.equal(parseTimestamp(String(TIMESTAMP)), TIMESTAMP);
|
||||
assert.equal(parseTimestamp(` ${TIMESTAMP} `), TIMESTAMP);
|
||||
describe('hasTimestampValue', () => {
|
||||
it('returns false for null', () => expect(hasTimestampValue(null)).toBe(false));
|
||||
it('returns false for undefined', () => expect(hasTimestampValue(undefined)).toBe(false));
|
||||
it('returns false for empty string', () => expect(hasTimestampValue('')).toBe(false));
|
||||
it('returns false for whitespace-only string', () => expect(hasTimestampValue(' ')).toBe(false));
|
||||
it('returns true for number', () => expect(hasTimestampValue(1234567890)).toBe(true));
|
||||
it('returns true for non-empty string', () => expect(hasTimestampValue('2026-09-02')).toBe(true));
|
||||
});
|
||||
|
||||
test('rejects missing, invalid and non-scalar timestamp values', () => {
|
||||
const invalidValues = [null, undefined, '', ' ', 'invalid', true, {}, [], Infinity, Number.MAX_VALUE];
|
||||
|
||||
invalidValues.forEach(value => assert.equal(parseTimestamp(value), null));
|
||||
assert.equal(formatTimestamp('invalid'), '-');
|
||||
describe('parseTimestamp', () => {
|
||||
it('returns null for null', () => expect(parseTimestamp(null)).toBe(null));
|
||||
it('returns null for empty string', () => expect(parseTimestamp('')).toBe(null));
|
||||
it('parses numeric string', () => {
|
||||
const ts = parseTimestamp('1234567890000');
|
||||
expect(typeof ts).toBe('number');
|
||||
expect(ts).toBe(1234567890000);
|
||||
});
|
||||
it('returns null for non-numeric string', () => expect(parseTimestamp('not-a-date')).toBe(null));
|
||||
it('parses number directly', () => expect(parseTimestamp(1234567890000)).toBe(1234567890000));
|
||||
});
|
||||
|
||||
test('falls back to the legacy createDate only when the timestamp is missing', () => {
|
||||
const legacyDate = '2026-07-10 21:21:42';
|
||||
const formatter = timestamp => `local:${timestamp}`;
|
||||
|
||||
assert.equal(formatCreateDate(undefined, legacyDate, formatter), legacyDate);
|
||||
assert.equal(formatCreateDate('', legacyDate, formatter), legacyDate);
|
||||
assert.equal(formatCreateDate('invalid', legacyDate, formatter), '-');
|
||||
assert.equal(formatCreateDate(String(TIMESTAMP), legacyDate, formatter), `local:${TIMESTAMP}`);
|
||||
describe('parseLegacyDate', () => {
|
||||
it('returns null for empty', () => expect(parseLegacyDate('')).toBe(null));
|
||||
it('parses ISO date string', () => {
|
||||
const ts = parseLegacyDate('2026-09-02T10:00:00Z');
|
||||
expect(typeof ts).toBe('number');
|
||||
expect(ts).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
test('formats the same instant consistently in each browser time zone', () => {
|
||||
const formatter = timeZone => timestamp => new Date(timestamp).toLocaleString('en-US', { timeZone });
|
||||
|
||||
for (const timeZone of ['Asia/Shanghai', 'America/Sao_Paulo']) {
|
||||
assert.equal(
|
||||
formatTimestamp(TIMESTAMP, formatter(timeZone)),
|
||||
formatTimestamp(String(TIMESTAMP), formatter(timeZone)),
|
||||
);
|
||||
}
|
||||
describe('formatTimestamp', () => {
|
||||
it('returns dash for null', () => expect(formatTimestamp(null)).toBe('-'));
|
||||
it('uses default formatter', () => {
|
||||
const out = formatTimestamp(0);
|
||||
expect(typeof out).toBe('string');
|
||||
expect(out).not.toBe('-');
|
||||
});
|
||||
it('accepts custom formatter', () => {
|
||||
expect(formatTimestamp(0, () => 'CUSTOM')).toBe('CUSTOM');
|
||||
});
|
||||
});
|
||||
|
||||
test('sorts valid epoch values first and leaves invalid values at the end', () => {
|
||||
const timestamps = [null, TIMESTAMP + 1, undefined, TIMESTAMP];
|
||||
|
||||
assert.deepEqual(timestamps.sort(compareTimestamps), [TIMESTAMP, TIMESTAMP + 1, null, undefined]);
|
||||
assert.equal(compareTimestamps(null, undefined), 0);
|
||||
describe('formatCreateDate', () => {
|
||||
it('falls back to legacy date when timestamp missing', () => {
|
||||
expect(formatCreateDate(null, 'fallback')).toBe('fallback');
|
||||
});
|
||||
it('falls back to dash when both missing', () => {
|
||||
expect(formatCreateDate(null, null)).toBe('-');
|
||||
});
|
||||
});
|
||||
|
||||
describe('compareTimestamps', () => {
|
||||
it('returns negative when first < second', () => {
|
||||
expect(compareTimestamps(100, 200)).toBeLessThan(0);
|
||||
});
|
||||
it('returns positive when first > second', () => {
|
||||
expect(compareTimestamps(200, 100)).toBeGreaterThan(0);
|
||||
});
|
||||
it('returns 0 when both equal', () => {
|
||||
expect(compareTimestamps(100, 100)).toBe(0);
|
||||
});
|
||||
it('treats invalid as greater than nothing', () => {
|
||||
expect(compareTimestamps(100, NaN)).toBeLessThan(0);
|
||||
});
|
||||
});
|
||||
52
main/manager-web/tests/deviceTimeContract.test.mjs
Normal file
52
main/manager-web/tests/deviceTimeContract.test.mjs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
compareTimestamps,
|
||||
formatCreateDate,
|
||||
formatTimestamp,
|
||||
parseTimestamp,
|
||||
} from '../src/utils/deviceTime.mjs';
|
||||
|
||||
const TIMESTAMP = 1783689702000;
|
||||
|
||||
test('accepts epoch milliseconds as a number or numeric string', () => {
|
||||
assert.equal(parseTimestamp(TIMESTAMP), TIMESTAMP);
|
||||
assert.equal(parseTimestamp(String(TIMESTAMP)), TIMESTAMP);
|
||||
assert.equal(parseTimestamp(` ${TIMESTAMP} `), TIMESTAMP);
|
||||
});
|
||||
|
||||
test('rejects missing, invalid and non-scalar timestamp values', () => {
|
||||
const invalidValues = [null, undefined, '', ' ', 'invalid', true, {}, [], Infinity, Number.MAX_VALUE];
|
||||
|
||||
invalidValues.forEach(value => assert.equal(parseTimestamp(value), null));
|
||||
assert.equal(formatTimestamp('invalid'), '-');
|
||||
});
|
||||
|
||||
test('falls back to the legacy createDate only when the timestamp is missing', () => {
|
||||
const legacyDate = '2026-07-10 21:21:42';
|
||||
const formatter = timestamp => `local:${timestamp}`;
|
||||
|
||||
assert.equal(formatCreateDate(undefined, legacyDate, formatter), legacyDate);
|
||||
assert.equal(formatCreateDate('', legacyDate, formatter), legacyDate);
|
||||
assert.equal(formatCreateDate('invalid', legacyDate, formatter), '-');
|
||||
assert.equal(formatCreateDate(String(TIMESTAMP), legacyDate, formatter), `local:${TIMESTAMP}`);
|
||||
});
|
||||
|
||||
test('formats the same instant consistently in each browser time zone', () => {
|
||||
const formatter = timeZone => timestamp => new Date(timestamp).toLocaleString('en-US', { timeZone });
|
||||
|
||||
for (const timeZone of ['Asia/Shanghai', 'America/Sao_Paulo']) {
|
||||
assert.equal(
|
||||
formatTimestamp(TIMESTAMP, formatter(timeZone)),
|
||||
formatTimestamp(String(TIMESTAMP), formatter(timeZone)),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('sorts valid epoch values first and leaves invalid values at the end', () => {
|
||||
const timestamps = [null, TIMESTAMP + 1, undefined, TIMESTAMP];
|
||||
|
||||
assert.deepEqual(timestamps.sort(compareTimestamps), [TIMESTAMP, TIMESTAMP + 1, null, undefined]);
|
||||
assert.equal(compareTimestamps(null, undefined), 0);
|
||||
});
|
||||
99
main/manager-web/tests/featureManager.test.mjs
Normal file
99
main/manager-web/tests/featureManager.test.mjs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
|
||||
// Mock the heavy dependencies before importing the module under test.
|
||||
vi.mock('@/apis/api', () => ({
|
||||
default: {
|
||||
user: {
|
||||
getPubConfig: vi.fn(),
|
||||
},
|
||||
admin: {
|
||||
updateParam: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
default: {
|
||||
commit: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import featureManager from '../src/utils/featureManager.js';
|
||||
|
||||
describe('featureManager', () => {
|
||||
beforeEach(() => {
|
||||
// Reset to defaults so each test starts from a clean feature set.
|
||||
featureManager.resetToDefault();
|
||||
});
|
||||
|
||||
it('module loads and exports the singleton', () => {
|
||||
expect(featureManager).toBeDefined();
|
||||
expect(typeof featureManager.getCurrentConfig).toBe('function');
|
||||
});
|
||||
|
||||
it('resetToDefault populates the seven default feature flags', () => {
|
||||
const features = featureManager.getCurrentConfig();
|
||||
const keys = Object.keys(features).sort();
|
||||
expect(keys).toEqual([
|
||||
'addressBook',
|
||||
'asr',
|
||||
'knowledgeBase',
|
||||
'mcpAccessPoint',
|
||||
'vad',
|
||||
'voiceClone',
|
||||
'voiceprintRecognition',
|
||||
]);
|
||||
// Every default feature should start disabled.
|
||||
for (const key of keys) {
|
||||
expect(features[key].enabled).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('setFeatureStatus returns false for an unknown feature key', () => {
|
||||
expect(featureManager.setFeatureStatus('notARealFeature', true)).toBe(false);
|
||||
});
|
||||
|
||||
it('setFeatureStatus enables and disables a known feature', () => {
|
||||
expect(featureManager.setFeatureStatus('asr', true)).toBe(true);
|
||||
expect(featureManager.isFeatureEnabled('asr')).toBe(true);
|
||||
|
||||
expect(featureManager.setFeatureStatus('asr', false)).toBe(true);
|
||||
expect(featureManager.isFeatureEnabled('asr')).toBe(false);
|
||||
});
|
||||
|
||||
it('enableFeature / disableFeature / toggleFeature update state', () => {
|
||||
featureManager.enableFeature('voiceprintRecognition');
|
||||
expect(featureManager.getFeatureStatus('voiceprintRecognition')).toBe(true);
|
||||
|
||||
featureManager.disableFeature('voiceprintRecognition');
|
||||
expect(featureManager.getFeatureStatus('voiceprintRecognition')).toBe(false);
|
||||
|
||||
featureManager.toggleFeature('knowledgeBase');
|
||||
expect(featureManager.getFeatureStatus('knowledgeBase')).toBe(true);
|
||||
featureManager.toggleFeature('knowledgeBase');
|
||||
expect(featureManager.getFeatureStatus('knowledgeBase')).toBe(false);
|
||||
});
|
||||
|
||||
it('getConfig returns a flat object of booleans', () => {
|
||||
const config = featureManager.getConfig();
|
||||
expect(Object.keys(config).sort()).toEqual([
|
||||
'addressBook',
|
||||
'asr',
|
||||
'knowledgeBase',
|
||||
'mcpAccessPoint',
|
||||
'vad',
|
||||
'voiceClone',
|
||||
'voiceprintRecognition',
|
||||
]);
|
||||
for (const key of Object.keys(config)) {
|
||||
expect(typeof config[key]).toBe('boolean');
|
||||
}
|
||||
});
|
||||
|
||||
it('getEnabledFeatures lists only enabled keys', () => {
|
||||
featureManager.enableFeature('asr');
|
||||
featureManager.enableFeature('vad');
|
||||
const enabled = featureManager.getEnabledFeatures().sort();
|
||||
expect(enabled).toEqual(['asr', 'vad']);
|
||||
});
|
||||
});
|
||||
56
main/manager-web/tests/format.test.mjs
Normal file
56
main/manager-web/tests/format.test.mjs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import * as format from '../src/utils/format.js';
|
||||
|
||||
describe('format utilities', () => {
|
||||
it('module loads and exports functions', () => {
|
||||
expect(format).toBeDefined();
|
||||
expect(Object.keys(format).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
describe('formatDate', () => {
|
||||
it('returns empty string for falsy values', () => {
|
||||
expect(format.formatDate(null)).toBe('');
|
||||
expect(format.formatDate(undefined)).toBe('');
|
||||
expect(format.formatDate('')).toBe('');
|
||||
expect(format.formatDate(0)).toBe('');
|
||||
});
|
||||
|
||||
it('formats a Date object as YYYY-MM-DD HH:mm:ss', () => {
|
||||
const date = new Date(2026, 8, 2, 13, 4, 5); // Sep 2, 2026 13:04:05 (local)
|
||||
expect(format.formatDate(date)).toBe('2026-09-02 13:04:05');
|
||||
});
|
||||
|
||||
it('accepts ISO date strings', () => {
|
||||
expect(format.formatDate('2026-01-15T08:30:00Z')).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
|
||||
});
|
||||
|
||||
it('zero-pads single digit components', () => {
|
||||
const date = new Date(2026, 0, 5, 7, 8, 9); // Jan 5, 2026 07:08:09
|
||||
expect(format.formatDate(date)).toBe('2026-01-05 07:08:09');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatFileSize', () => {
|
||||
it('returns 0 B for falsy values', () => {
|
||||
expect(format.formatFileSize(0)).toBe('0 B');
|
||||
expect(format.formatFileSize(null)).toBe('0 B');
|
||||
expect(format.formatFileSize(undefined)).toBe('0 B');
|
||||
});
|
||||
|
||||
it('formats bytes in B', () => {
|
||||
expect(format.formatFileSize(512)).toBe('512 B');
|
||||
});
|
||||
|
||||
it('formats kilobytes', () => {
|
||||
expect(format.formatFileSize(1024)).toBe('1 KB');
|
||||
expect(format.formatFileSize(1536)).toBe('1.5 KB');
|
||||
});
|
||||
|
||||
it('formats megabytes and above', () => {
|
||||
expect(format.formatFileSize(1024 * 1024)).toBe('1 MB');
|
||||
expect(format.formatFileSize(2.5 * 1024 * 1024)).toBe('2.5 MB');
|
||||
expect(format.formatFileSize(1024 ** 3)).toBe('1 GB');
|
||||
expect(format.formatFileSize(1024 ** 4)).toBe('1 TB');
|
||||
});
|
||||
});
|
||||
});
|
||||
22
main/manager-web/vitest.config.js
Normal file
22
main/manager-web/vitest.config.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { defineConfig } from 'vitest/config';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
globals: false,
|
||||
include: ['tests/**/*.test.{js,mjs}'],
|
||||
exclude: ['tests/*Contract.test.mjs', 'node_modules/**'],
|
||||
passWithNoTests: true,
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
reporter: ['text', 'html'],
|
||||
include: ['src/utils/**', 'src/store/**'],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
|
@ -246,7 +246,7 @@ selected_module:
|
|||
# 不想开通意图识别,就设置成:nointent
|
||||
# 意图识别可使用intent_llm。优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间,支持控制音量大小等iot操作
|
||||
# 意图识别可使用function_call,缺点:需要所选择的LLM支持function_call,优点:按需调用工具、速度快,理论上能全部操作所有iot指令
|
||||
# 默认免费的ChatGLMLLM就已经支持function_call,但是如果像追求稳定建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-1-5-pro-32k-250115
|
||||
# 默认免费的ChatGLMLLM就已经支持function_call,但是如果像追求稳定建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-seed-2-0-lite-260215
|
||||
Intent: function_call
|
||||
|
||||
# 意图识别,是用于理解用户意图的模块,例如:播放音乐
|
||||
|
|
@ -638,12 +638,12 @@ LLM:
|
|||
DoubaoLLM:
|
||||
# 定义LLM API类型
|
||||
type: openai
|
||||
# 先开通服务,打开以下网址,开通的服务搜索Doubao-1.5-pro,开通它
|
||||
# 先开通服务,打开以下网址,开通的服务搜索Doubao-Seed-2.0-Lite,开通它
|
||||
# 开通地址:https://console.volcengine.com/ark/region:ark+cn-beijing/openManagement?LLM=%7B%7D&OpenTokenDrawer=false
|
||||
# 免费额度500000token
|
||||
# 开通后,进入这里获取密钥:https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey?apikey=%7B%7D
|
||||
base_url: https://ark.cn-beijing.volces.com/api/v3
|
||||
model_name: doubao-1-5-pro-32k-250115
|
||||
model_name: doubao-seed-2-0-lite-260215
|
||||
api_key: 你的doubao web key
|
||||
DeepSeekLLM:
|
||||
# 定义LLM API类型
|
||||
|
|
@ -1139,6 +1139,8 @@ TTS:
|
|||
# cosyvoice-v3和部分音色需要申请开通
|
||||
type: alibl_stream
|
||||
api_key: 你的api_key
|
||||
# 默认兼容旧地址;业务空间请替换为 wss://<WorkspaceId>.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference
|
||||
ws_url: wss://dashscope.aliyuncs.com/api-ws/v1/inference/
|
||||
model: "cosyvoice-v2"
|
||||
voice: "longcheng_v2"
|
||||
output_dir: tmp/
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import os
|
||||
import base64
|
||||
import functools
|
||||
import threading
|
||||
from typing import Optional, Dict
|
||||
|
||||
import httpx
|
||||
|
|
@ -19,15 +21,18 @@ class DeviceBindException(Exception):
|
|||
|
||||
class ManageApiClient:
|
||||
_instance = None
|
||||
_instance_lock = threading.Lock() # 保护 _instance 与 _closed 的读写
|
||||
_async_clients = {} # 为每个事件循环存储独立的客户端
|
||||
_secret = None
|
||||
_closed = False # safe_close() 后置为 True,关闭后不再创建新连接
|
||||
|
||||
def __new__(cls, config):
|
||||
"""单例模式确保全局唯一实例,并支持传入配置参数"""
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
cls._init_client(config)
|
||||
return cls._instance
|
||||
with cls._instance_lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
cls._init_client(config)
|
||||
return cls._instance
|
||||
|
||||
@classmethod
|
||||
def _init_client(cls, config):
|
||||
|
|
@ -48,6 +53,7 @@ class ManageApiClient:
|
|||
cls.retry_delay = cls.config.get("retry_delay", 10) # 初始重试延迟(秒)
|
||||
# 不在这里创建 AsyncClient,延迟到实际使用时创建
|
||||
cls._async_clients = {}
|
||||
cls._closed = False
|
||||
|
||||
@classmethod
|
||||
async def _ensure_async_client(cls):
|
||||
|
|
@ -58,24 +64,29 @@ class ManageApiClient:
|
|||
loop = asyncio.get_running_loop()
|
||||
loop_id = id(loop)
|
||||
|
||||
# 为每个事件循环创建独立的客户端
|
||||
if loop_id not in cls._async_clients:
|
||||
# 服务端可能主动关闭连接,httpx 连接池无法正确检测和清理
|
||||
limits = httpx.Limits(
|
||||
max_keepalive_connections=0, # 禁用 keep-alive,每次都新建连接
|
||||
)
|
||||
cls._async_clients[loop_id] = httpx.AsyncClient(
|
||||
base_url=cls.config.get("url"),
|
||||
headers={
|
||||
"User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})",
|
||||
"Accept": "application/json",
|
||||
"Authorization": "Bearer " + cls._secret,
|
||||
},
|
||||
timeout=cls.config.get("timeout", 30),
|
||||
limits=limits, # 使用限制
|
||||
trust_env=False,
|
||||
)
|
||||
return cls._async_clients[loop_id]
|
||||
# 检查关闭状态与创建连接池必须是同一个临界区,避免 safe_close()
|
||||
# 清空连接池后又有请求将新客户端写回。
|
||||
with cls._instance_lock:
|
||||
if cls._closed:
|
||||
raise Exception("ManageApiClient已关闭,不再创建新的HTTP客户端")
|
||||
|
||||
if loop_id not in cls._async_clients:
|
||||
# 服务端可能主动关闭连接,httpx 连接池无法正确检测和清理
|
||||
limits = httpx.Limits(
|
||||
max_keepalive_connections=0, # 禁用 keep-alive,每次都新建连接
|
||||
)
|
||||
cls._async_clients[loop_id] = httpx.AsyncClient(
|
||||
base_url=cls.config.get("url"),
|
||||
headers={
|
||||
"User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})",
|
||||
"Accept": "application/json",
|
||||
"Authorization": "Bearer " + cls._secret,
|
||||
},
|
||||
timeout=cls.config.get("timeout", 30),
|
||||
limits=limits, # 使用限制
|
||||
trust_env=False,
|
||||
)
|
||||
return cls._async_clients[loop_id]
|
||||
except RuntimeError:
|
||||
# 如果没有运行中的事件循环,创建一个临时的
|
||||
raise Exception("必须在异步上下文中调用")
|
||||
|
|
@ -148,32 +159,80 @@ class ManageApiClient:
|
|||
# 不重试,直接抛出异常
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def _get_instance(cls):
|
||||
"""线程安全地获取单例实例引用
|
||||
|
||||
调用方应使用返回的局部引用,而不是判空后再次读取
|
||||
ManageApiClient._instance:即使随后 safe_close() 将 _instance
|
||||
置为 None,已获取的引用仍指向原对象,从而消除"判空之后、
|
||||
使用之前实例被置空"的 TOCTOU 竞态窗口。
|
||||
"""
|
||||
with cls._instance_lock:
|
||||
return cls._instance
|
||||
|
||||
@classmethod
|
||||
def safe_close(cls):
|
||||
"""安全关闭所有异步连接池"""
|
||||
import asyncio
|
||||
|
||||
for client in list(cls._async_clients.values()):
|
||||
with cls._instance_lock:
|
||||
cls._closed = True
|
||||
clients = list(cls._async_clients.values())
|
||||
cls._async_clients.clear()
|
||||
cls._instance = None
|
||||
|
||||
for client in clients:
|
||||
try:
|
||||
asyncio.run(client.aclose())
|
||||
except Exception:
|
||||
pass
|
||||
cls._async_clients.clear()
|
||||
cls._instance = None
|
||||
|
||||
|
||||
async def get_server_config() -> Optional[Dict]:
|
||||
def api_guard(error_msg: str = None, raise_when_closed: bool = False):
|
||||
"""装饰器:统一获取单例实例、判空与异常兜底
|
||||
|
||||
- 通过 _get_instance() 一次性获取实例局部引用,注入为被装饰函数的
|
||||
第一个参数,消除与 safe_close() 之间的 TOCTOU 竞态窗口;
|
||||
- 实例未初始化或已关闭时:raise_when_closed=True 抛出明确异常
|
||||
(用于启动路径函数),否则静默返回 None(用于守护线程路径);
|
||||
- error_msg 不为 None 时捕获请求异常、打印日志并返回 None;
|
||||
为 None 时异常原样抛出,由调用方处理。
|
||||
"""
|
||||
|
||||
def decorator(func):
|
||||
@functools.wraps(func)
|
||||
async def wrapper(*args, **kwargs):
|
||||
instance = ManageApiClient._get_instance()
|
||||
if instance is None:
|
||||
if raise_when_closed:
|
||||
raise Exception("ManageApiClient未初始化或已关闭")
|
||||
return None
|
||||
if error_msg is None:
|
||||
return await func(instance, *args, **kwargs)
|
||||
try:
|
||||
return await func(instance, *args, **kwargs)
|
||||
except Exception as e:
|
||||
print(f"{error_msg}: {e}")
|
||||
return None
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
@api_guard(raise_when_closed=True)
|
||||
async def get_server_config(instance) -> Optional[Dict]:
|
||||
"""获取服务器基础配置"""
|
||||
return await ManageApiClient._instance._execute_async_request(
|
||||
"POST", "/config/server-base"
|
||||
)
|
||||
return await instance._execute_async_request("POST", "/config/server-base")
|
||||
|
||||
|
||||
@api_guard(raise_when_closed=True)
|
||||
async def get_agent_models(
|
||||
mac_address: str, client_id: str, selected_module: Dict
|
||||
instance, mac_address: str, client_id: str, selected_module: Dict
|
||||
) -> Optional[Dict]:
|
||||
"""获取代理模型配置"""
|
||||
return await ManageApiClient._instance._execute_async_request(
|
||||
return await instance._execute_async_request(
|
||||
"POST",
|
||||
"/config/agent-models",
|
||||
json={
|
||||
|
|
@ -184,80 +243,63 @@ async def get_agent_models(
|
|||
)
|
||||
|
||||
|
||||
async def get_correct_words(mac_address: str) -> Optional[Dict]:
|
||||
@api_guard("获取替换词失败")
|
||||
async def get_correct_words(instance, mac_address: str) -> Optional[Dict]:
|
||||
"""获取智能体替换词"""
|
||||
try:
|
||||
return await ManageApiClient._instance._execute_async_request(
|
||||
"POST", "/config/correct-words",
|
||||
json={"macAddress": mac_address}
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"获取替换词失败: {e}")
|
||||
return None
|
||||
return await instance._execute_async_request(
|
||||
"POST", "/config/correct-words",
|
||||
json={"macAddress": mac_address}
|
||||
)
|
||||
|
||||
|
||||
async def generate_and_save_chat_summary(session_id: str) -> Optional[Dict]:
|
||||
"""生成并保存聊天记录总结"""
|
||||
try:
|
||||
return await ManageApiClient._instance._execute_async_request(
|
||||
"POST",
|
||||
f"/agent/chat-summary/{session_id}/save",
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"生成并保存聊天记录总结失败: {e}")
|
||||
return None
|
||||
@api_guard("生成并保存聊天记录总结失败")
|
||||
async def generate_and_save_chat_summary(instance, session_id: str) -> Optional[Dict]:
|
||||
"""生成并保存聊天记录总结(守护线程中调用,服务已关闭时静默返回 None)"""
|
||||
return await instance._execute_async_request(
|
||||
"POST",
|
||||
f"/agent/chat-summary/{session_id}/save",
|
||||
)
|
||||
|
||||
|
||||
async def generate_and_save_chat_title(session_id: str) -> Optional[Dict]:
|
||||
"""生成并保存聊天标题"""
|
||||
try:
|
||||
return await ManageApiClient._instance._execute_async_request(
|
||||
"POST",
|
||||
f"/agent/chat-title/{session_id}/generate",
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"生成并保存聊天标题失败: {e}")
|
||||
return None
|
||||
@api_guard("生成并保存聊天标题失败")
|
||||
async def generate_and_save_chat_title(instance, session_id: str) -> Optional[Dict]:
|
||||
"""生成并保存聊天标题(守护线程中调用,服务已关闭时静默返回 None)"""
|
||||
return await instance._execute_async_request(
|
||||
"POST",
|
||||
f"/agent/chat-title/{session_id}/generate",
|
||||
)
|
||||
|
||||
|
||||
@api_guard("TTS上报失败")
|
||||
async def report(
|
||||
mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time
|
||||
instance, mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time
|
||||
) -> Optional[Dict]:
|
||||
"""异步聊天记录上报"""
|
||||
if not content or not ManageApiClient._instance:
|
||||
return None
|
||||
try:
|
||||
return await ManageApiClient._instance._execute_async_request(
|
||||
"POST",
|
||||
f"/agent/chat-history/report",
|
||||
json={
|
||||
"macAddress": mac_address,
|
||||
"sessionId": session_id,
|
||||
"chatType": chat_type,
|
||||
"content": content,
|
||||
"reportTime": report_time,
|
||||
"audioBase64": (
|
||||
base64.b64encode(audio).decode("utf-8") if audio else None
|
||||
),
|
||||
},
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"TTS上报失败: {e}")
|
||||
if not content:
|
||||
return None
|
||||
return await instance._execute_async_request(
|
||||
"POST",
|
||||
f"/agent/chat-history/report",
|
||||
json={
|
||||
"macAddress": mac_address,
|
||||
"sessionId": session_id,
|
||||
"chatType": chat_type,
|
||||
"content": content,
|
||||
"reportTime": report_time,
|
||||
"audioBase64": (
|
||||
base64.b64encode(audio).decode("utf-8") if audio else None
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def lookup_address_book(caller_mac: str, nickname: str) -> Optional[Dict]:
|
||||
@api_guard("通讯录查找失败")
|
||||
async def lookup_address_book(instance, caller_mac: str, nickname: str) -> Optional[Dict]:
|
||||
"""根据昵称查找目标设备"""
|
||||
if not ManageApiClient._instance:
|
||||
return None
|
||||
try:
|
||||
return await ManageApiClient._instance._execute_async_request(
|
||||
"GET",
|
||||
f"/device/address-book/lookup?callerMac={caller_mac}&nickname={nickname}",
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"通讯录查找失败: {e}")
|
||||
return None
|
||||
return await instance._execute_async_request(
|
||||
"GET",
|
||||
f"/device/address-book/lookup?callerMac={caller_mac}&nickname={nickname}",
|
||||
)
|
||||
|
||||
|
||||
def init_service(config):
|
||||
|
|
|
|||
|
|
@ -279,7 +279,10 @@ class ConnectionHandler:
|
|||
"""保存记忆并关闭连接"""
|
||||
try:
|
||||
# 守护线程1:独立生成标题(不依赖记忆模型)
|
||||
if self.session_id:
|
||||
# 仅在服务端开启 chat_history 上报时才触发标题生成,
|
||||
# 否则服务端无法按 session_id 反查到对应的 agent/chat_history,
|
||||
# 会抛出"智能体未找到"错误
|
||||
if self.session_id and self.chat_history_conf != 0:
|
||||
def generate_title_task():
|
||||
try:
|
||||
loop = asyncio.new_event_loop()
|
||||
|
|
|
|||
|
|
@ -54,14 +54,16 @@ async def handleHelloMessage(conn: "ConnectionHandler", msg_json):
|
|||
if features.get("mcp"):
|
||||
conn.logger.bind(tag=TAG).debug("客户端支持MCP")
|
||||
conn.mcp_client = MCPClient()
|
||||
# 发送初始化
|
||||
asyncio.create_task(send_mcp_initialize_message(conn))
|
||||
if features.get("aec"):
|
||||
conn.logger.bind(tag=TAG).debug("客户端启用了服务端AEC")
|
||||
conn.client_aec = True
|
||||
|
||||
await conn.websocket.send(json.dumps(conn.welcome_msg))
|
||||
|
||||
# The device waits for the server hello before processing MCP messages.
|
||||
if features and features.get("mcp"):
|
||||
asyncio.create_task(send_mcp_initialize_message(conn))
|
||||
|
||||
|
||||
async def checkWakeupWords(conn: "ConnectionHandler", text):
|
||||
enable_wakeup_words_response_cache = conn.config[
|
||||
|
|
|
|||
|
|
@ -64,16 +64,19 @@ async def _wait_for_audio_completion(conn: "ConnectionHandler"):
|
|||
"""
|
||||
if hasattr(conn, "audio_rate_controller") and conn.audio_rate_controller:
|
||||
rate_controller = conn.audio_rate_controller
|
||||
send_delay_ms = conn.config.get("tts_audio_send_delay", 0)
|
||||
conn.logger.bind(tag=TAG).debug(
|
||||
f"等待音频发送完成,队列中还有 {len(rate_controller.queue)} 个包"
|
||||
)
|
||||
await rate_controller.queue_empty_event.wait()
|
||||
|
||||
# 等待预缓冲包播放完成
|
||||
# 前N个包直接发送,增加2个网络抖动包,需要额外等待它们在客户端播放完成
|
||||
frame_duration_ms = rate_controller.frame_duration
|
||||
pre_buffer_playback_time = (PRE_BUFFER_COUNT + 2) * frame_duration_ms / 1000.0
|
||||
await asyncio.sleep(pre_buffer_playback_time)
|
||||
if send_delay_ms > 0:
|
||||
# 自定义节奏:等待最后帧在客户端播放完成
|
||||
playback_time = 2 * rate_controller.interval_ms / 1000.0
|
||||
else:
|
||||
# 默认节奏:前 N 帧预缓冲已直接发出,需要等待它们播放完成
|
||||
playback_time = (PRE_BUFFER_COUNT + 2) * rate_controller.interval_ms / 1000.0
|
||||
await asyncio.sleep(playback_time)
|
||||
|
||||
conn.logger.bind(tag=TAG).debug("音频发送完成")
|
||||
|
||||
|
|
@ -127,12 +130,12 @@ async def sendAudio(
|
|||
if audios is None or len(audios) == 0:
|
||||
return
|
||||
|
||||
send_delay = conn.config.get("tts_audio_send_delay", -1) / 1000.0
|
||||
send_delay_ms = conn.config.get("tts_audio_send_delay", 0)
|
||||
is_single_packet = isinstance(audios, bytes)
|
||||
|
||||
# 初始化或获取 RateController
|
||||
rate_controller, flow_control = _get_or_create_rate_controller(
|
||||
conn, frame_duration, is_single_packet
|
||||
conn, frame_duration, is_single_packet, send_delay_ms
|
||||
)
|
||||
|
||||
# 统一转换为列表处理
|
||||
|
|
@ -140,12 +143,12 @@ async def sendAudio(
|
|||
|
||||
# 发送音频包
|
||||
await _send_audio_with_rate_control(
|
||||
conn, audio_list, rate_controller, flow_control, send_delay
|
||||
conn, audio_list, rate_controller, flow_control, send_delay_ms
|
||||
)
|
||||
|
||||
|
||||
def _get_or_create_rate_controller(
|
||||
conn: "ConnectionHandler", frame_duration, is_single_packet
|
||||
conn: "ConnectionHandler", frame_duration, is_single_packet, send_delay_ms=0
|
||||
):
|
||||
"""
|
||||
获取或创建 RateController 和 flow_control
|
||||
|
|
@ -154,6 +157,7 @@ def _get_or_create_rate_controller(
|
|||
conn: 连接对象
|
||||
frame_duration: 帧时长
|
||||
is_single_packet: 是否单包模式(True: TTS流式单包, False: 批量包)
|
||||
send_delay_ms: 自定义发送间隔(毫秒)。
|
||||
|
||||
Returns:
|
||||
(rate_controller, flow_control)
|
||||
|
|
@ -183,7 +187,9 @@ def _get_or_create_rate_controller(
|
|||
if need_reset:
|
||||
# 创建或获取 rate_controller
|
||||
if not hasattr(conn, "audio_rate_controller"):
|
||||
conn.audio_rate_controller = AudioRateController(frame_duration)
|
||||
conn.audio_rate_controller = AudioRateController(
|
||||
frame_duration, send_delay=send_delay_ms
|
||||
)
|
||||
else:
|
||||
conn.audio_rate_controller.reset()
|
||||
|
||||
|
|
@ -225,7 +231,7 @@ def _start_background_sender(conn: "ConnectionHandler", rate_controller, flow_co
|
|||
|
||||
|
||||
async def _send_audio_with_rate_control(
|
||||
conn: "ConnectionHandler", audio_list, rate_controller, flow_control, send_delay
|
||||
conn: "ConnectionHandler", audio_list, rate_controller, flow_control, send_delay_ms
|
||||
):
|
||||
"""
|
||||
使用 rate_controller 发送音频包
|
||||
|
|
@ -235,7 +241,7 @@ async def _send_audio_with_rate_control(
|
|||
audio_list: 音频包列表
|
||||
rate_controller: 速率控制器
|
||||
flow_control: 流控状态
|
||||
send_delay: 固定延迟(秒),-1表示使用动态流控
|
||||
send_delay_ms: 自定义发送间隔(毫秒)。
|
||||
"""
|
||||
for packet in audio_list:
|
||||
if conn.client_abort:
|
||||
|
|
@ -243,16 +249,15 @@ async def _send_audio_with_rate_control(
|
|||
|
||||
conn.last_activity_time = time.time() * 1000
|
||||
|
||||
# 预缓冲:前N个包直接发送
|
||||
if flow_control["packet_count"] < PRE_BUFFER_COUNT:
|
||||
await _do_send_audio(conn, packet, flow_control)
|
||||
elif send_delay > 0:
|
||||
# 固定延迟模式
|
||||
await asyncio.sleep(send_delay)
|
||||
await _do_send_audio(conn, packet, flow_control)
|
||||
else:
|
||||
# 动态流控模式:仅添加到队列,由后台循环负责发送
|
||||
if send_delay_ms > 0:
|
||||
# 自定义节奏模式:所有包入队按 send_delay 发(关闭预缓冲)
|
||||
rate_controller.add_audio(packet)
|
||||
else:
|
||||
# 默认节奏模式(60ms/包):前 N 包预缓冲直接发,后续入队由后台任务按 interval_ms 节奏发
|
||||
if flow_control["packet_count"] < PRE_BUFFER_COUNT:
|
||||
await _do_send_audio(conn, packet, flow_control)
|
||||
else:
|
||||
rate_controller.add_audio(packet)
|
||||
|
||||
|
||||
async def _do_send_audio(conn: "ConnectionHandler", opus_packet, flow_control):
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ EMOTION_EMOJI_MAP = {
|
|||
# "<|Cough|>": "🤧",
|
||||
# }
|
||||
|
||||
def lang_tag_filter(text: str) -> dict | str:
|
||||
def lang_tag_filter(text: str) -> dict:
|
||||
"""
|
||||
解析 FunASR 识别结果,按顺序提取标签和纯文本内容
|
||||
|
||||
|
|
@ -33,8 +33,8 @@ def lang_tag_filter(text: str) -> dict | str:
|
|||
text: ASR 识别的原始文本,可能包含多种标签
|
||||
|
||||
Returns:
|
||||
dict: {"language": "zh", "emotion": "SAD", "emoji": "😔", "content": "你好"} 如果有标签
|
||||
str: 纯文本,如果没有标签
|
||||
dict: {"language": "zh", "emotion": "SAD", "emoji": "😔", "content": "你好"} 如果有标签,
|
||||
{"content": "纯文本"} 如果没有标签
|
||||
|
||||
Examples:
|
||||
FunASR 输出格式:<|语种|><|情绪|><|事件|><|其他选项|>原文
|
||||
|
|
@ -43,7 +43,7 @@ def lang_tag_filter(text: str) -> dict | str:
|
|||
>>> lang_tag_filter("<|en|><|HAPPY|><|Speech|><|withitn|>Hello hello.")
|
||||
{"language": "en", "emotion": "HAPPY", "emoji": "🙂", "content": "Hello hello."}
|
||||
>>> lang_tag_filter("plain text")
|
||||
"plain text"
|
||||
{"content": "plain text"}
|
||||
"""
|
||||
# 提取所有标签(按顺序)
|
||||
tag_pattern = r"<\|([^|]+)\|>"
|
||||
|
|
@ -52,9 +52,9 @@ def lang_tag_filter(text: str) -> dict | str:
|
|||
# 移除所有 <|...|> 格式的标签,获取纯文本
|
||||
clean_text = re.sub(tag_pattern, "", text).strip()
|
||||
|
||||
# 如果没有标签,直接返回纯文本
|
||||
# 保持返回结构一致,避免调用方把纯文本误当成字典访问。
|
||||
if not all_tags:
|
||||
return clean_text
|
||||
return {"content": clean_text}
|
||||
|
||||
# 按照 FunASR 的固定顺序提取标签,返回 dict
|
||||
language = all_tags[0] if len(all_tags) > 0 else "zh"
|
||||
|
|
@ -76,4 +76,3 @@ def lang_tag_filter(text: str) -> dict | str:
|
|||
# result["event"] = EVENT_EMOJI_MAP[event]
|
||||
|
||||
return result
|
||||
|
||||
|
|
|
|||
|
|
@ -7,10 +7,10 @@ import asyncio
|
|||
import traceback
|
||||
import websockets
|
||||
|
||||
from asyncio import Task
|
||||
from typing import Callable, Any
|
||||
from config.logger import setup_logging
|
||||
from core.utils.tts import MarkdownCleaner
|
||||
from core.utils.alibl_endpoint import build_ws_connect_options, resolve_ws_url
|
||||
from core.providers.tts.base import TTSProviderBase
|
||||
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
||||
|
||||
|
|
@ -33,10 +33,10 @@ class TTSProvider(TTSProviderBase):
|
|||
self.api_key = config.get("api_key")
|
||||
if not self.api_key:
|
||||
raise ValueError("api_key is required for CosyVoice TTS")
|
||||
self.report_on_last = True
|
||||
|
||||
# WebSocket配置
|
||||
self.ws_url = "wss://dashscope.aliyuncs.com/api-ws/v1/inference/"
|
||||
self.ws_url = resolve_ws_url(config.get("ws_url"))
|
||||
self.ws_connect_options = build_ws_connect_options(self.tts_timeout)
|
||||
self.ws = None
|
||||
self._monitor_task = None
|
||||
self.activate_session = False
|
||||
|
|
@ -89,6 +89,7 @@ class TTSProvider(TTSProviderBase):
|
|||
ping_interval=30,
|
||||
ping_timeout=10,
|
||||
close_timeout=10,
|
||||
**self.ws_connect_options,
|
||||
)
|
||||
|
||||
logger.bind(tag=TAG).debug("WebSocket连接建立成功")
|
||||
|
|
@ -356,18 +357,15 @@ class TTSProvider(TTSProviderBase):
|
|||
|
||||
if event == "task-started":
|
||||
logger.bind(tag=TAG).debug("TTS任务启动成功~")
|
||||
self.tts_audio_queue.put((SentenceType.FIRST, [], None))
|
||||
elif event == "result-generated":
|
||||
# 发送缓存的数据
|
||||
tts_text = self.get_tts_text(self.conn.sentence_id)
|
||||
if tts_text:
|
||||
logger.bind(tag=TAG).info(
|
||||
f"句子语音生成成功: {tts_text}"
|
||||
)
|
||||
self.tts_audio_queue.put(
|
||||
(SentenceType.FIRST, [], tts_text)
|
||||
)
|
||||
self.clear_tts_text(self.conn.sentence_id)
|
||||
output = data.get("payload", {}).get("output", {})
|
||||
if output.get("type") == "sentence-begin":
|
||||
original_text = output.get("original_text")
|
||||
self.tts_text = self._restore_original_text(original_text)
|
||||
logger.bind(tag=TAG).debug(f"句子语音生成开始: {self.tts_text}")
|
||||
self.tts_audio_queue.put((SentenceType.FIRST, [], self.tts_text))
|
||||
elif output.get("type") == "sentence-end":
|
||||
logger.bind(tag=TAG).info(f"句子语音生成成功: {self.tts_text}")
|
||||
elif event == "task-finished":
|
||||
logger.bind(tag=TAG).debug("TTS任务完成~")
|
||||
self.activate_session = False
|
||||
|
|
@ -444,6 +442,7 @@ class TTSProvider(TTSProviderBase):
|
|||
ping_timeout=10,
|
||||
close_timeout=10,
|
||||
max_size=10 * 1024 * 1024,
|
||||
**self.ws_connect_options,
|
||||
)
|
||||
|
||||
try:
|
||||
|
|
|
|||
48
main/xiaozhi-server/core/utils/alibl_endpoint.py
Normal file
48
main/xiaozhi-server/core/utils/alibl_endpoint.py
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import re
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
DEFAULT_WS_URL = "wss://dashscope.aliyuncs.com/api-ws/v1/inference/"
|
||||
INFERENCE_PATH = "/api-ws/v1/inference"
|
||||
HOSTNAME_PATTERN = re.compile(r"^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$")
|
||||
HAPPY_EYEBALLS_DELAY = 0.25
|
||||
|
||||
|
||||
def build_ws_connect_options(open_timeout):
|
||||
return {
|
||||
"open_timeout": open_timeout,
|
||||
"happy_eyeballs_delay": HAPPY_EYEBALLS_DELAY,
|
||||
"interleave": 1,
|
||||
}
|
||||
|
||||
|
||||
def resolve_ws_url(value):
|
||||
ws_url = str(value or DEFAULT_WS_URL).strip()
|
||||
parsed = urlsplit(ws_url)
|
||||
hostname = (parsed.hostname or "").lower()
|
||||
is_dashscope = hostname in {
|
||||
"dashscope.aliyuncs.com",
|
||||
"dashscope-intl.aliyuncs.com",
|
||||
}
|
||||
is_workspace = hostname.endswith(".maas.aliyuncs.com")
|
||||
|
||||
try:
|
||||
port = parsed.port
|
||||
except ValueError:
|
||||
port = -1
|
||||
|
||||
if (
|
||||
parsed.scheme.lower() != "wss"
|
||||
or not HOSTNAME_PATTERN.fullmatch(hostname)
|
||||
or not (is_dashscope or is_workspace)
|
||||
or parsed.path.rstrip("/") != INFERENCE_PATH
|
||||
or parsed.query
|
||||
or parsed.fragment
|
||||
or parsed.username
|
||||
or parsed.password
|
||||
or port not in {None, 443}
|
||||
):
|
||||
raise ValueError(
|
||||
"ws_url must be an official Alibaba Cloud WSS inference endpoint"
|
||||
)
|
||||
return ws_url
|
||||
|
|
@ -13,12 +13,16 @@ class AudioRateController:
|
|||
解决高并发下的时间累积误差问题
|
||||
"""
|
||||
|
||||
def __init__(self, frame_duration=60):
|
||||
def __init__(self, frame_duration=60, send_delay=0):
|
||||
"""
|
||||
Args:
|
||||
frame_duration: 单个音频帧时长(毫秒),默认60ms
|
||||
send_delay: 自定义发送间隔(毫秒)。
|
||||
0 = 按 frame_duration 节奏发;
|
||||
>0 = 按 send_delay 节奏发(主线程不入队延迟,无预缓冲)
|
||||
"""
|
||||
self.frame_duration = frame_duration
|
||||
# 流控间隔(毫秒):send_delay > 0 时用配置值,否则用 frame_duration
|
||||
self.interval_ms = send_delay if send_delay > 0 else frame_duration
|
||||
self.queue = deque()
|
||||
self.play_position = 0 # 虚拟播放位置(毫秒)
|
||||
self.start_timestamp = None # 开始时间戳(只读,不修改)
|
||||
|
|
@ -51,7 +55,7 @@ class AudioRateController:
|
|||
if len(self.queue) == 0 and self.play_position > 0:
|
||||
elapsed_since_empty = (time.monotonic() - self._last_queue_empty_time) * 1000
|
||||
# 只有间隔超过1帧时长,才认为是真正的"暂停恢复"
|
||||
if elapsed_since_empty >= self.frame_duration:
|
||||
if elapsed_since_empty >= self.interval_ms:
|
||||
self.start_timestamp = time.monotonic() - (self.play_position / 1000)
|
||||
self.logger.bind(tag=TAG).debug(
|
||||
f"队列从空恢复,重置时间戳,当前播放位置: {self.play_position}ms,间隔: {elapsed_since_empty:.0f}ms"
|
||||
|
|
@ -71,7 +75,7 @@ class AudioRateController:
|
|||
"""
|
||||
if len(self.queue) == 0 and self.play_position > 0:
|
||||
elapsed_since_empty = (time.monotonic() - self._last_queue_empty_time) * 1000
|
||||
if elapsed_since_empty >= self.frame_duration:
|
||||
if elapsed_since_empty >= self.interval_ms:
|
||||
self.start_timestamp = time.monotonic() - (self.play_position / 1000)
|
||||
self.logger.bind(tag=TAG).debug(
|
||||
f"队列从空恢复,重置时间戳,当前播放位置: {self.play_position}ms,间隔: {elapsed_since_empty:.0f}ms"
|
||||
|
|
@ -138,7 +142,7 @@ class AudioRateController:
|
|||
|
||||
# 时间已到,从队列移除并发送
|
||||
self.queue.popleft()
|
||||
self.play_position += self.frame_duration
|
||||
self.play_position += self.interval_ms
|
||||
try:
|
||||
await send_audio_callback(opus_packet)
|
||||
except Exception as e:
|
||||
|
|
|
|||
|
|
@ -74,7 +74,11 @@ class WebSocketServer:
|
|||
port = int(server_config.get("port", 8000))
|
||||
|
||||
async with websockets.serve(
|
||||
self._handle_connection, host, port, process_request=self._http_response
|
||||
self._handle_connection,
|
||||
host,
|
||||
port,
|
||||
process_request=self._http_response,
|
||||
ping_interval=None,
|
||||
):
|
||||
await asyncio.Future()
|
||||
|
||||
|
|
|
|||
|
|
@ -18,8 +18,8 @@ description = "大语言模型性能测试"
|
|||
|
||||
|
||||
class LLMPerformanceTester:
|
||||
def __init__(self):
|
||||
self.config = load_config()
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
# 使用更符合智能体场景的测试内容,包含系统提示词
|
||||
self.system_prompt = self._load_system_prompt()
|
||||
self.test_sentences = self.config.get("module_test", {}).get(
|
||||
|
|
@ -536,7 +536,8 @@ class LLMPerformanceTester:
|
|||
|
||||
|
||||
async def main():
|
||||
tester = LLMPerformanceTester()
|
||||
config = await load_config()
|
||||
tester = LLMPerformanceTester(config)
|
||||
await tester.run()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -24,8 +24,8 @@ except ImportError:
|
|||
dashscope = None
|
||||
|
||||
class BaseASRTester:
|
||||
def __init__(self, config_key: str):
|
||||
self.config = load_config()
|
||||
def __init__(self, config_key: str, config):
|
||||
self.config = config
|
||||
self.config_key = config_key
|
||||
self.asr_config = self.config.get("ASR", {}).get(config_key, {})
|
||||
self.test_audio_files = self._load_test_audio_files()
|
||||
|
|
@ -63,8 +63,8 @@ class BaseASRTester:
|
|||
|
||||
|
||||
class DoubaoStreamASRTester(BaseASRTester):
|
||||
def __init__(self):
|
||||
super().__init__("DoubaoStreamASR")
|
||||
def __init__(self, config):
|
||||
super().__init__("DoubaoStreamASR", config)
|
||||
from core.providers.asr.doubao_stream import ASRProvider as DoubaoStreamProvider
|
||||
self.provider = DoubaoStreamProvider(self.asr_config, delete_audio_file=False)
|
||||
|
||||
|
|
@ -128,8 +128,8 @@ class DoubaoStreamASRTester(BaseASRTester):
|
|||
|
||||
|
||||
class QwenASRFlashTester(BaseASRTester):
|
||||
def __init__(self):
|
||||
super().__init__("Qwen3ASRFlash")
|
||||
def __init__(self, config):
|
||||
super().__init__("Qwen3ASRFlash", config)
|
||||
|
||||
async def _test_single(self, audio_file_info):
|
||||
temp_file_path = None
|
||||
|
|
@ -213,8 +213,8 @@ class QwenASRFlashTester(BaseASRTester):
|
|||
|
||||
|
||||
class XunfeiStreamASRTester(BaseASRTester):
|
||||
def __init__(self):
|
||||
super().__init__("XunfeiStreamASR")
|
||||
def __init__(self, config):
|
||||
super().__init__("XunfeiStreamASR", config)
|
||||
|
||||
def _create_url(self):
|
||||
url = "wss://iat-api.xfyun.cn/v2/iat"
|
||||
|
|
@ -325,13 +325,14 @@ class XunfeiStreamASRTester(BaseASRTester):
|
|||
|
||||
return self._calculate_result("讯飞流式ASR", latencies, test_count)
|
||||
class ASRPerformanceSuite:
|
||||
def __init__(self):
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
self.testers = []
|
||||
self.results = []
|
||||
|
||||
def register_tester(self, tester_class):
|
||||
try:
|
||||
tester = tester_class()
|
||||
tester = tester_class(self.config)
|
||||
self.testers.append(tester)
|
||||
print(f"已注册测试器: {tester.config_key}")
|
||||
except Exception as e:
|
||||
|
|
@ -390,7 +391,8 @@ async def main():
|
|||
parser.add_argument("--count", type=int, default=5, help="测试次数")
|
||||
args = parser.parse_args()
|
||||
|
||||
suite = ASRPerformanceSuite()
|
||||
config = await load_config()
|
||||
suite = ASRPerformanceSuite(config)
|
||||
suite.register_tester(DoubaoStreamASRTester)
|
||||
suite.register_tester(QwenASRFlashTester)
|
||||
suite.register_tester(XunfeiStreamASRTester)
|
||||
|
|
|
|||
|
|
@ -11,11 +11,15 @@ import asyncio
|
|||
from urllib.parse import urlparse, urlencode
|
||||
from tabulate import tabulate
|
||||
from config.settings import load_config
|
||||
from core.utils.alibl_endpoint import (
|
||||
build_ws_connect_options as build_alibl_ws_connect_options,
|
||||
resolve_ws_url as resolve_alibl_ws_url,
|
||||
)
|
||||
|
||||
description = "流式TTS语音合成首词耗时测试"
|
||||
class StreamTTSPerformanceTester:
|
||||
def __init__(self):
|
||||
self.config = load_config()
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
self.test_texts = [
|
||||
"你好,这是一句话。"
|
||||
]
|
||||
|
|
@ -108,8 +112,11 @@ class StreamTTSPerformanceTester:
|
|||
voice = tts_config.get("voice", "longxiaochun_v2")
|
||||
format_type = tts_config.get("format", "pcm")
|
||||
sample_rate = int(tts_config.get("sample_rate", "24000"))
|
||||
connect_options = build_alibl_ws_connect_options(
|
||||
float(self.config.get("tts_timeout", 15))
|
||||
)
|
||||
|
||||
ws_url = "wss://dashscope.aliyuncs.com/api-ws/v1/inference/"
|
||||
ws_url = resolve_alibl_ws_url(tts_config.get("ws_url"))
|
||||
headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"X-DashScope-DataInspection": "enable",
|
||||
|
|
@ -124,6 +131,7 @@ class StreamTTSPerformanceTester:
|
|||
ping_timeout=10,
|
||||
close_timeout=10,
|
||||
max_size=10 * 1024 * 1024,
|
||||
**connect_options,
|
||||
) as ws:
|
||||
session_id = uuid.uuid4().hex
|
||||
|
||||
|
|
@ -663,7 +671,8 @@ async def main():
|
|||
parser.add_argument("--count", type=int, default=5, help="每个TTS服务的测试次数")
|
||||
|
||||
args = parser.parse_args()
|
||||
await StreamTTSPerformanceTester().run(args.text, args.count)
|
||||
config = await load_config()
|
||||
await StreamTTSPerformanceTester(config).run(args.text, args.count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
|
|
@ -18,8 +18,8 @@ description = "非流式语音合成性能测试"
|
|||
|
||||
|
||||
class TTSPerformanceTester:
|
||||
def __init__(self):
|
||||
self.config = load_config()
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
self.test_sentences = self.config.get("module_test", {}).get(
|
||||
"test_sentences",
|
||||
[
|
||||
|
|
@ -190,10 +190,10 @@ class TTSPerformanceTester:
|
|||
|
||||
# 为了performance_tester.py的调用需求
|
||||
async def main():
|
||||
tester = TTSPerformanceTester()
|
||||
config = await load_config()
|
||||
tester = TTSPerformanceTester(config)
|
||||
await tester.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
tester = TTSPerformanceTester()
|
||||
asyncio.run(tester.run())
|
||||
asyncio.run(main())
|
||||
|
|
|
|||
|
|
@ -15,8 +15,8 @@ description = "视觉识别模型性能测试"
|
|||
|
||||
|
||||
class AsyncVisionPerformanceTester:
|
||||
def __init__(self):
|
||||
self.config = load_config()
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
|
||||
self.test_images = [
|
||||
"../../docs/images/demo1.png",
|
||||
|
|
@ -184,7 +184,8 @@ class AsyncVisionPerformanceTester:
|
|||
|
||||
|
||||
async def main():
|
||||
tester = AsyncVisionPerformanceTester()
|
||||
config = await load_config()
|
||||
tester = AsyncVisionPerformanceTester(config)
|
||||
await tester.run()
|
||||
|
||||
|
||||
|
|
|
|||
10
main/xiaozhi-server/pyproject.toml
Normal file
10
main/xiaozhi-server/pyproject.toml
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
testpaths = ["tests"]
|
||||
python_files = ["test_*.py"]
|
||||
python_classes = ["Test*"]
|
||||
python_functions = ["test_*"]
|
||||
addopts = "-ra"
|
||||
filterwarnings = [
|
||||
"ignore::DeprecationWarning",
|
||||
]
|
||||
|
|
@ -7,7 +7,7 @@ numpy==1.26.4
|
|||
websockets==14.2
|
||||
#--------- 以下是可升级的依赖
|
||||
pyyml==0.0.2
|
||||
silero_vad==6.1.0
|
||||
silero_vad==6.2.1
|
||||
opuslib_next==1.1.5
|
||||
pydub==0.25.1
|
||||
funasr==1.2.7
|
||||
|
|
@ -25,19 +25,18 @@ cozepy==0.20.0
|
|||
mem0ai==1.0.0
|
||||
powermem>=0.3.1
|
||||
bs4==0.0.2
|
||||
modelscope==1.32.0
|
||||
modelscope==1.39.1
|
||||
sherpa_onnx==1.12.29
|
||||
mcp==1.22.0
|
||||
cnlunar==0.2.0
|
||||
PySocks==1.7.1
|
||||
dashscope==1.25.2
|
||||
baidu-aip==4.16.13
|
||||
chardet==5.2.0
|
||||
aioconsole==0.8.2
|
||||
markitdown==0.1.3
|
||||
mcp-proxy==0.10.0
|
||||
PyJWT==2.10.1
|
||||
psutil==7.1.3
|
||||
portalocker==3.2.0
|
||||
portalocker==3.2.0 # 暂留 3.x:4.x 与 qdrant-client<1.20 的 portalocker<4.0 约束冲突 (PR #3360)
|
||||
Jinja2==3.1.6
|
||||
vosk==0.3.45
|
||||
0
main/xiaozhi-server/tests/__init__.py
Normal file
0
main/xiaozhi-server/tests/__init__.py
Normal file
0
main/xiaozhi-server/tests/config/__init__.py
Normal file
0
main/xiaozhi-server/tests/config/__init__.py
Normal file
45
main/xiaozhi-server/tests/config/test_config_loader.py
Normal file
45
main/xiaozhi-server/tests/config/test_config_loader.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
"""Tests for the recursive config merge in config/config_loader.py."""
|
||||
from config.config_loader import merge_configs
|
||||
|
||||
|
||||
def test_merge_simple_override():
|
||||
default = {"a": 1, "b": 2}
|
||||
custom = {"b": 99}
|
||||
assert merge_configs(default, custom) == {"a": 1, "b": 99}
|
||||
|
||||
|
||||
def test_merge_adds_new_key():
|
||||
default = {"a": 1}
|
||||
custom = {"b": 2}
|
||||
assert merge_configs(default, custom) == {"a": 1, "b": 2}
|
||||
|
||||
|
||||
def test_merge_recursive_dict():
|
||||
default = {"x": {"a": 1, "b": 2}}
|
||||
custom = {"x": {"b": 99}}
|
||||
assert merge_configs(default, custom) == {"x": {"a": 1, "b": 99}}
|
||||
|
||||
|
||||
def test_merge_deep_recursive():
|
||||
default = {"a": {"b": {"c": 1, "d": 2}}}
|
||||
custom = {"a": {"b": {"c": 99}}}
|
||||
assert merge_configs(default, custom) == {"a": {"b": {"c": 99, "d": 2}}}
|
||||
|
||||
|
||||
def test_merge_replaces_non_dict_with_dict():
|
||||
default = {"a": 1}
|
||||
custom = {"a": {"nested": True}}
|
||||
assert merge_configs(default, custom) == {"a": {"nested": True}}
|
||||
|
||||
|
||||
def test_merge_replaces_dict_with_non_dict():
|
||||
default = {"a": {"nested": True}}
|
||||
custom = {"a": 1}
|
||||
assert merge_configs(default, custom) == {"a": 1}
|
||||
|
||||
|
||||
def test_merge_does_not_mutate_defaults():
|
||||
default = {"a": {"b": 1}}
|
||||
custom = {"a": {"c": 2}}
|
||||
merge_configs(default, custom)
|
||||
assert default == {"a": {"b": 1}} # unchanged
|
||||
445
main/xiaozhi-server/tests/conftest.py
Normal file
445
main/xiaozhi-server/tests/conftest.py
Normal file
|
|
@ -0,0 +1,445 @@
|
|||
"""Pytest configuration — must run BEFORE any test imports project modules.
|
||||
|
||||
Adds the xiaozhi-server directory to sys.path so the existing implicit
|
||||
relative imports (`from core.utils.textUtils import ...`) resolve.
|
||||
|
||||
External-API mock toggle (default: mocked)
|
||||
-------------------------------------------
|
||||
The dep-upgrade orchestrator and CI run this test suite *without* any
|
||||
real API credentials. By default the tests construct the actual provider
|
||||
objects from ``data/.config.yaml`` but route every network call through
|
||||
a recording shim, so no traffic leaves the host.
|
||||
|
||||
Set ``RUN_LIVE_API_TESTS=1`` to opt in to real network calls. In that
|
||||
mode the 5-module readiness check runs in strict form (any missing key
|
||||
→ ``sys.exit(3)``), the mock shims are uninstalled, and tests hit the
|
||||
real providers.
|
||||
|
||||
Configuration loading
|
||||
---------------------
|
||||
Always uses the file-merge path (``config.yaml`` + ``data/.config.yaml``).
|
||||
``manager-api`` is intentionally NOT contacted — pytest must work in a
|
||||
single-module deployment.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
# Windows console 默认 GBK 编码;emoji / 中文 print 会炸,强制 UTF-8。
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
if str(_PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_PROJECT_ROOT))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# opuslib_next stub:让 import 链路通;真调音频会失败,测试自行 try/except
|
||||
# ---------------------------------------------------------------------------
|
||||
try:
|
||||
import opuslib_next # noqa: F401
|
||||
except Exception:
|
||||
_stub = types.ModuleType("opuslib_next")
|
||||
_stub.Encoder = type("Encoder", (), {"__init__": lambda *a, **kw: None})
|
||||
_stub.Decoder = type("Decoder", (), {"__init__": lambda *a, **kw: None})
|
||||
_stub.APPLICATION_AUDIO = 0
|
||||
_stub.OpusError = type("OpusError", (Exception,), {})
|
||||
_stub.constants = types.SimpleNamespace()
|
||||
sys.modules["opuslib_next"] = _stub
|
||||
for sub in ("api", "exceptions"):
|
||||
sys.modules[f"opuslib_next.{sub}"] = types.ModuleType(f"opuslib_next.{sub}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 配置加载:永远走文件合并
|
||||
# ---------------------------------------------------------------------------
|
||||
# 优先级:
|
||||
# 1. 环境变量 ``PYTEST_CONFIG_FILE`` 指向的文件(推荐 — 隔离测试配置)
|
||||
# 2. data/.config.yaml(生产 / 单模块部署配置)
|
||||
_DEFAULT_CUSTOM = _PROJECT_ROOT / "data" / ".config.yaml"
|
||||
_CUSTOM_CONFIG = Path(os.environ["PYTEST_CONFIG_FILE"]) if os.environ.get(
|
||||
"PYTEST_CONFIG_FILE"
|
||||
) else _DEFAULT_CUSTOM
|
||||
|
||||
|
||||
def _load_via_file_merge() -> dict:
|
||||
"""纯文件合并:config.yaml + data/.config.yaml。和生产单模块部署一致。"""
|
||||
from config.config_loader import merge_configs
|
||||
|
||||
config: dict = {}
|
||||
default_path = _PROJECT_ROOT / "config.yaml"
|
||||
if default_path.exists():
|
||||
config = yaml.safe_load(default_path.read_text(encoding="utf-8")) or {}
|
||||
|
||||
if _CUSTOM_CONFIG.exists():
|
||||
custom = yaml.safe_load(_CUSTOM_CONFIG.read_text(encoding="utf-8")) or {}
|
||||
config = merge_configs(config, custom)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
# 全模块部署检测(在任何模式下都 fail-fast,避免触发远程 API)。
|
||||
# 全模块部署会让 ``load_config`` 走 manager-api 远程拉取,pytest 不应该触发。
|
||||
if _CUSTOM_CONFIG.exists():
|
||||
_raw_custom = yaml.safe_load(_CUSTOM_CONFIG.read_text(encoding="utf-8")) or {}
|
||||
_api_cfg = _raw_custom.get("manager-api", {})
|
||||
_has_url = bool(_api_cfg.get("url"))
|
||||
_has_secret = bool(_api_cfg.get("secret")) and "你" not in str(
|
||||
_api_cfg.get("secret", "")
|
||||
)
|
||||
if _has_url and _has_secret:
|
||||
print(
|
||||
"\n[conftest] ============================================================\n"
|
||||
"[conftest] FAIL: 检测到全模块部署(manager-api.url + secret 已配置),\n"
|
||||
"[conftest] pytest 不支持全模块部署。\n"
|
||||
"[conftest] 原因:manager-api 的 server.secret 是匿名 token,\n"
|
||||
"[conftest] 没有 sys:role:superAdmin 权限,\n"
|
||||
"[conftest] 拿不到 LLM/TTS/Memory 的 configJson(含 api_key)。\n"
|
||||
"[conftest] 切换到单模块的方法:\n"
|
||||
"[conftest] 1) manager-web → 参数管理 → 模型配置,\n"
|
||||
"[conftest] 把 LLM/TTS/Memory 的 configJson 抄出来\n"
|
||||
"[conftest] 2) 写到 data/.config.yaml(结构跟 config.yaml 一致)\n"
|
||||
"[conftest] 3) 清空 data/.config.yaml 里的 manager-api 整块\n"
|
||||
"[conftest] 4) 重跑 pytest\n"
|
||||
"[conftest] ============================================================",
|
||||
flush=True,
|
||||
)
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
# 永远走文件合并:单模块直接用
|
||||
CONFIG: dict = _load_via_file_merge()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 关键:把 ``load_config`` / ``get_server_config`` 等运行时配置入口替换成
|
||||
# 直接返回我们已构建的 CONFIG,避免 ``config.config_loader.load_config`` 在
|
||||
# 测试运行期间再次读取 ``data/.config.yaml``(默认是全模块部署配置)并触发
|
||||
# manager-api 远程调用。
|
||||
# ---------------------------------------------------------------------------
|
||||
async def _load_config_patched(*_args, **_kwargs):
|
||||
return CONFIG
|
||||
|
||||
|
||||
async def _get_server_config_patched(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
|
||||
def _init_service_noop(_config):
|
||||
"""阻止 ``init_service`` 实例化 ``ManageApiClient``。"""
|
||||
return None
|
||||
|
||||
|
||||
import config.config_loader as _cl # noqa: E402
|
||||
import config.manage_api_client as _mac # noqa: E402
|
||||
_cl.load_config = _load_config_patched
|
||||
_mac.init_service = _init_service_noop
|
||||
_mac.get_server_config = _get_server_config_patched
|
||||
# 清空 ManageApiClient 单例,避免前面已经被其它代码触发过实例化。
|
||||
_mac.ManageApiClient._instance = None
|
||||
_mac.ManageApiClient._closed = True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 配置访问 helper(test 引用)
|
||||
# ---------------------------------------------------------------------------
|
||||
def get_provider_config(module: str, provider_name: str | None = None) -> dict:
|
||||
"""拿某个 provider 的 config dict。
|
||||
|
||||
- provider_name=None:取 ``selected_module[module]``
|
||||
- 否则显式指定
|
||||
返回 {} 表示没配。
|
||||
"""
|
||||
if provider_name is None:
|
||||
provider_name = CONFIG.get("selected_module", {}).get(module)
|
||||
if not provider_name:
|
||||
return {}
|
||||
return CONFIG.get(module, {}).get(provider_name, {}) or {}
|
||||
|
||||
|
||||
def get_selected_provider_name(module: str) -> str | None:
|
||||
return CONFIG.get("selected_module", {}).get(module)
|
||||
|
||||
|
||||
def get_provider_type(module: str, provider_name: str | None = None) -> str | None:
|
||||
"""返回 ``create_instance`` 真正需要的 type 名(与 section 名可能不同)。
|
||||
|
||||
约定(来自 core/utils/modules_initialize.py):type 不存在时回退到 section 名。
|
||||
"""
|
||||
cfg = get_provider_config(module, provider_name)
|
||||
if not cfg:
|
||||
return None
|
||||
return cfg.get("type") or (provider_name or get_selected_provider_name(module))
|
||||
|
||||
|
||||
def has_real_key(config: dict, *keys: str) -> bool:
|
||||
"""任一候选 key 名下值不是占位符就算有真密钥。
|
||||
|
||||
占位符判定:空 / "你的..." / 包含 "placeholder" / 字面 "none"。
|
||||
"""
|
||||
if not config:
|
||||
return False
|
||||
for key in keys:
|
||||
val = config.get(key)
|
||||
if val is None:
|
||||
continue
|
||||
s = str(val).strip().lower()
|
||||
if not s or s == "none":
|
||||
continue
|
||||
if s.startswith("你的") or "placeholder" in s:
|
||||
continue
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 默认 mock 模式:拦截第三方 HTTP/SDK 网络调用,测试无须真密钥也能跑通
|
||||
# ---------------------------------------------------------------------------
|
||||
LIVE_API_TESTS: bool = os.environ.get("RUN_LIVE_API_TESTS") == "1"
|
||||
|
||||
# 第三方 SDK 列表。真实模式下不需要做任何事(保留真实 import)。
|
||||
# Mock 模式下把这些名字塞进 sys.modules,并提供异常类 / 客户端占位。
|
||||
_MOCKED_MODULES: tuple[str, ...] = (
|
||||
# 注:openai / httpx / requests 这些真实第三方包通常已装在 conda 环境,
|
||||
# shim 整个 module 会破坏 ``openai.types`` / ``httpx.AsyncClient`` 等子模块
|
||||
# 解析。仅当对应包没装时才 shim(__getattr__ 仍走真 import 路径)。
|
||||
"anthropic",
|
||||
"dashscope",
|
||||
"tencentcloud",
|
||||
"xunfei",
|
||||
"vosk",
|
||||
"edge_tts",
|
||||
"elevenlabs",
|
||||
"mem0",
|
||||
"mem0ai",
|
||||
"freezegun",
|
||||
)
|
||||
|
||||
# 这些包即使装了也强制 shim — 它们要么本地模型链 import 时炸
|
||||
# (funasr 引 torch、torch DLL 路径长),要么是 GPU 重型依赖,mock 跑不动。
|
||||
_FORCE_SHIM_MODULES: tuple[str, ...] = (
|
||||
"funasr",
|
||||
"torch",
|
||||
"torchaudio",
|
||||
"modelscope",
|
||||
)
|
||||
|
||||
|
||||
def _try_import_real(name: str) -> bool:
|
||||
"""检查真实第三方包是否可加载(不真正 import,只检查 importer.find_spec)。
|
||||
|
||||
主动 ``__import__`` 会触发包级副作用(funasr 引 torch 等),绕过它直接
|
||||
看包是否在 sys.path / site-packages 里。
|
||||
"""
|
||||
import importlib.util
|
||||
|
||||
spec = importlib.util.find_spec(name)
|
||||
return spec is not None
|
||||
|
||||
|
||||
class _RecordingShim:
|
||||
"""A no-op stand-in for any object reachable through a shimmed module.
|
||||
|
||||
Acts as both a callable and an attribute container: every attribute
|
||||
access returns a callable that records the call and yields another
|
||||
shim. Used as a base class for fake exception classes so
|
||||
``except httpx.ConnectError`` blocks evaluate correctly.
|
||||
"""
|
||||
|
||||
_calls: list = []
|
||||
|
||||
def __init__(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
def __getattr__(self, attr):
|
||||
def _record(*args, **kwargs):
|
||||
type(self)._calls.append((attr, args, kwargs))
|
||||
return _RecordingShim()
|
||||
|
||||
return _record
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
type(self)._calls.append(("__call__", args, kwargs))
|
||||
return _RecordingShim()
|
||||
|
||||
|
||||
class _ShimModule(types.ModuleType):
|
||||
"""PEP 562 module — any attribute access returns a recording shim."""
|
||||
|
||||
def __getattr__(self, attr):
|
||||
if attr in ("__path__", "__loader__", "__spec__"):
|
||||
raise AttributeError(attr)
|
||||
# Cache so identity stays stable across accesses.
|
||||
value = _RecordingShim()
|
||||
setattr(self, attr, value)
|
||||
return value
|
||||
|
||||
|
||||
def _install_mock_layer() -> None:
|
||||
"""Insert PEP 562 shims for every third-party SDK in :data:`_MOCKED_MODULES`.
|
||||
|
||||
Exception classes (e.g. ``httpx.ConnectError``) become ``_RecordingShim``
|
||||
subclasses — so ``except`` blocks match and ``isinstance`` checks pass.
|
||||
Common callable symbols (``Client`` / ``OpenAI`` / ``AutoModel``) are
|
||||
pre-bound to the shim type so ``Client(...)`` constructions succeed.
|
||||
|
||||
If a real package is already importable (e.g. openai installed in conda),
|
||||
we leave it alone — shimming would break submodule resolution like
|
||||
``openai.types``.
|
||||
"""
|
||||
for name in list(_MOCKED_MODULES) + list(_FORCE_SHIM_MODULES):
|
||||
if name in sys.modules and isinstance(sys.modules[name], _ShimModule):
|
||||
continue
|
||||
if name not in _FORCE_SHIM_MODULES and _try_import_real(name):
|
||||
# Real package is available — use it. We'll patch network I/O
|
||||
# at the request layer in mock mode (see below).
|
||||
continue
|
||||
shim = _ShimModule(name)
|
||||
shim.OpenAI = _RecordingShim
|
||||
shim.AsyncOpenAI = _RecordingShim
|
||||
shim.Client = _RecordingShim
|
||||
shim.AsyncClient = _RecordingShim
|
||||
shim.AutoModel = _RecordingShim
|
||||
shim.completions = _RecordingShim()
|
||||
shim.chat = _RecordingShim()
|
||||
shim.exceptions = _ShimModule(f"{name}.exceptions")
|
||||
sys.modules[name] = shim
|
||||
sys.modules[f"{name}.exceptions"] = shim.exceptions
|
||||
|
||||
# 短化 asyncio.sleep 避免重试循环拖时间。
|
||||
import asyncio
|
||||
|
||||
async def _fast_sleep(_seconds):
|
||||
return None
|
||||
|
||||
asyncio.sleep = _fast_sleep # type: ignore[assignment]
|
||||
|
||||
# 网络层 mock:如果真实 httpx 已加载,把它的 AsyncClient.send 替换成
|
||||
# 立即抛 ConnectError 的桩,触发 ``_should_retry`` 走到 ``raise``,
|
||||
# 但避免真发请求。Live 模式完全不安装这层。
|
||||
if not LIVE_API_TESTS:
|
||||
try:
|
||||
import httpx as _httpx # noqa: F401
|
||||
|
||||
class _FakeAsyncClient:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
async def send(self, *args, **kwargs):
|
||||
raise _httpx.ConnectError("MOCK: connect refused")
|
||||
|
||||
async def aclose(self):
|
||||
return None
|
||||
|
||||
class _FakeClient:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def send(self, *args, **kwargs):
|
||||
raise _httpx.ConnectError("MOCK: connect refused")
|
||||
|
||||
def close(self):
|
||||
return None
|
||||
|
||||
_httpx.AsyncClient = _FakeAsyncClient # type: ignore[misc]
|
||||
_httpx.Client = _FakeClient # type: ignore[misc]
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
if not LIVE_API_TESTS:
|
||||
_install_mock_layer()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Live-mode 启动校验:单模块部署检测已在文件加载早期完成
|
||||
# ---------------------------------------------------------------------------
|
||||
if LIVE_API_TESTS:
|
||||
print("[conftest] OK: 单模块部署(文件合并配置)")
|
||||
|
||||
|
||||
_REQUIRED_MODULES = ("ASR", "LLM", "TTS", "Memory", "VAD")
|
||||
_SECRET_FIELDS = (
|
||||
"api_key", "token", "access_token", "authorization",
|
||||
"secret_key", "access_key", "app_id", "app_secret",
|
||||
"bot_id", "user_id",
|
||||
)
|
||||
|
||||
|
||||
def _check_modules_ready() -> None:
|
||||
"""Live 模式下:5 个核心模块必须配齐。Mock 模式下只打印 soft warning。"""
|
||||
problems: list[str] = []
|
||||
selected = CONFIG.get("selected_module") or {}
|
||||
for module in _REQUIRED_MODULES:
|
||||
provider_name = selected.get(module)
|
||||
if not provider_name:
|
||||
problems.append(f"{module} 未在 selected_module 配置(dev 漏选)")
|
||||
continue
|
||||
cfg = CONFIG.get(module, {}).get(provider_name)
|
||||
if not cfg:
|
||||
problems.append(
|
||||
f"{module}.{provider_name} 配置缺失(CFG 字典里没这个 provider)"
|
||||
)
|
||||
continue
|
||||
secret_keys_present = [k for k in _SECRET_FIELDS if k in cfg]
|
||||
if secret_keys_present and not any(
|
||||
has_real_key(cfg, k) for k in secret_keys_present
|
||||
):
|
||||
problems.append(
|
||||
f"{module}.{provider_name} 的 secret 字段"
|
||||
f"{secret_keys_present} 全是占位符(dev 没填真 key)"
|
||||
)
|
||||
if not problems:
|
||||
return
|
||||
if LIVE_API_TESTS:
|
||||
msg = (
|
||||
"\n[conftest] ============================================================\n"
|
||||
"[conftest] FAIL: pytest 要求 5 个核心模块全部配齐才能跑。\n"
|
||||
"[conftest] 缺失/未就绪项:\n"
|
||||
+ "\n".join(f"[conftest] - {p}" for p in problems)
|
||||
+ "\n[conftest] 必须在 data/.config.yaml 里把 5 个模块"
|
||||
"(ASR/LLM/TTS/Memory/VAD)都配齐才能跑 pytest。\n"
|
||||
"[conftest] ============================================================"
|
||||
)
|
||||
print(msg, file=sys.stderr, flush=True)
|
||||
sys.exit(3)
|
||||
print(
|
||||
"[conftest] NOTE: 默认 mock 模式 — 下列模块未配齐,但 pytest 仍可跑:\n - "
|
||||
+ "\n - ".join(problems)
|
||||
+ "\n[conftest] 真请求模式:export RUN_LIVE_API_TESTS=1 且配齐后再跑。",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
_check_modules_ready()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 显式标记:mock 模式下提示用户当前模式
|
||||
# ---------------------------------------------------------------------------
|
||||
if not LIVE_API_TESTS:
|
||||
print(
|
||||
"[conftest] MOCK 模式(默认):第三方 HTTP/SDK 已注入 shim,不发真请求。\n"
|
||||
"[conftest] 真请求模式:export RUN_LIVE_API_TESTS=1 pytest tests/ -v",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
import pytest # noqa: E402 (after conftest hooks so pytest is initialised)
|
||||
|
||||
|
||||
def pytest_collection_modifyitems(config, items):
|
||||
"""Live 模式下:``live_api`` 标记的测试必须配齐密钥才能跑(否则 skip)。"""
|
||||
if LIVE_API_TESTS:
|
||||
return
|
||||
# Mock 模式下不强行 skip:测试应该都能跑(用 shim)。
|
||||
return
|
||||
0
main/xiaozhi-server/tests/core/__init__.py
Normal file
0
main/xiaozhi-server/tests/core/__init__.py
Normal file
0
main/xiaozhi-server/tests/core/utils/__init__.py
Normal file
0
main/xiaozhi-server/tests/core/utils/__init__.py
Normal file
57
main/xiaozhi-server/tests/core/utils/test_current_time.py
Normal file
57
main/xiaozhi-server/tests/core/utils/test_current_time.py
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
"""Tests for core/utils/current_time.py.
|
||||
|
||||
Uses freezegun to control `datetime.now()` so the tests don't flake
|
||||
around midnight, and to verify the weekday/lunar mapping logic.
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
from freezegun import freeze_time
|
||||
|
||||
from core.utils import current_time
|
||||
|
||||
|
||||
@freeze_time("2026-09-02 10:30:00")
|
||||
def test_get_current_time_format_is_hh_mm():
|
||||
assert current_time.get_current_time() == "10:30"
|
||||
|
||||
|
||||
@freeze_time("2026-09-02 23:59:59")
|
||||
def test_get_current_time_at_late_hour():
|
||||
assert current_time.get_current_time() == "23:59"
|
||||
|
||||
|
||||
@freeze_time("2026-09-02 10:30:00")
|
||||
def test_get_current_date_format_is_iso():
|
||||
assert current_time.get_current_date() == "2026-09-02"
|
||||
|
||||
|
||||
@freeze_time("2026-09-02 10:30:00") # 2026-09-02 is a Wednesday
|
||||
def test_get_current_weekday_returns_chinese_label():
|
||||
assert current_time.get_current_weekday() == "星期三"
|
||||
|
||||
|
||||
def test_weekday_map_has_all_seven_days():
|
||||
assert set(current_time.WEEKDAY_MAP.keys()) == {
|
||||
"Monday", "Tuesday", "Wednesday", "Thursday",
|
||||
"Friday", "Saturday", "Sunday",
|
||||
}
|
||||
|
||||
|
||||
@freeze_time("2026-09-02 10:30:00")
|
||||
def test_get_current_time_info_returns_four_tuple():
|
||||
info = current_time.get_current_time_info()
|
||||
assert isinstance(info, tuple)
|
||||
assert len(info) == 4
|
||||
time_str, date_str, weekday, lunar = info
|
||||
assert time_str == "10:30"
|
||||
assert date_str == "2026-09-02"
|
||||
assert weekday == "星期三"
|
||||
assert "年" in lunar # lunar output contains "年"
|
||||
|
||||
|
||||
@freeze_time("2026-09-02 10:30:00")
|
||||
def test_get_current_lunar_date_contains_year():
|
||||
"""cnlunar should produce a string containing 年 character."""
|
||||
lunar = current_time.get_current_lunar_date()
|
||||
assert "年" in lunar
|
||||
83
main/xiaozhi-server/tests/core/utils/test_dialogue.py
Normal file
83
main/xiaozhi-server/tests/core/utils/test_dialogue.py
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
"""Tests for the Message/Dialogue classes used to build LLM context."""
|
||||
import pytest
|
||||
|
||||
from core.utils.dialogue import Dialogue, Message
|
||||
|
||||
|
||||
def test_message_assigns_default_uniq_id():
|
||||
m = Message(role="user", content="hi")
|
||||
assert m.uniq_id is not None
|
||||
assert len(m.uniq_id) > 0
|
||||
|
||||
|
||||
def test_message_preserves_explicit_uniq_id():
|
||||
m = Message(role="user", content="hi", uniq_id="abc")
|
||||
assert m.uniq_id == "abc"
|
||||
|
||||
|
||||
def test_message_default_is_not_temporary():
|
||||
m = Message(role="user", content="hi")
|
||||
assert m.is_temporary is False
|
||||
|
||||
|
||||
def test_message_tool_call_id_default_is_none():
|
||||
m = Message(role="user", content="hi")
|
||||
assert m.tool_call_id is None
|
||||
|
||||
|
||||
def test_dialogue_starts_empty():
|
||||
d = Dialogue()
|
||||
assert d.dialogue == []
|
||||
|
||||
|
||||
def test_dialogue_put_appends_message():
|
||||
d = Dialogue()
|
||||
d.put(Message(role="user", content="hi"))
|
||||
d.put(Message(role="assistant", content="hello"))
|
||||
assert len(d.dialogue) == 2
|
||||
|
||||
|
||||
def test_dialogue_get_llm_dialogue_includes_user_and_assistant():
|
||||
d = Dialogue()
|
||||
d.put(Message(role="user", content="hi"))
|
||||
d.put(Message(role="assistant", content="hello"))
|
||||
msgs = d.get_llm_dialogue()
|
||||
assert {"role": "user", "content": "hi"} in msgs
|
||||
assert {"role": "assistant", "content": "hello"} in msgs
|
||||
|
||||
|
||||
def test_dialogue_update_system_message_replaces_existing():
|
||||
d = Dialogue()
|
||||
d.update_system_message("you are a helper")
|
||||
d.update_system_message("you are a coder")
|
||||
system_msgs = [m for m in d.dialogue if m.role == "system"]
|
||||
assert len(system_msgs) == 1
|
||||
assert system_msgs[0].content == "you are a coder"
|
||||
|
||||
|
||||
def test_dialogue_update_system_message_creates_when_missing():
|
||||
d = Dialogue()
|
||||
d.update_system_message("you are a coder")
|
||||
assert len(d.dialogue) == 1
|
||||
assert d.dialogue[0].role == "system"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_llm_dialogue_with_memory_substitutes_into_system_message():
|
||||
d = Dialogue()
|
||||
d.update_system_message("Memory so far: <memory></memory>")
|
||||
msgs = d.get_llm_dialogue_with_memory(memory_str="user likes cats")
|
||||
system = next(m for m in msgs if m["role"] == "system")
|
||||
assert "user likes cats" in system["content"]
|
||||
assert "<memory></memory>" not in system["content"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_llm_dialogue_separates_temporary_few_shot_from_actual_history():
|
||||
d = Dialogue()
|
||||
d.put(Message(role="user", content="real user msg", is_temporary=False))
|
||||
d.put(Message(role="user", content="fewshot example", is_temporary=True))
|
||||
msgs = d.get_llm_dialogue()
|
||||
contents = [m["content"] for m in msgs if m["role"] == "user"]
|
||||
assert "real user msg" in contents
|
||||
assert "fewshot example" in contents
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
"""Tests for the create_instance factories in intent/llm/memory utils.
|
||||
|
||||
Each `create_instance(name, ...)` looks up `core/providers/<type>/<name>/<name>.py`
|
||||
on disk. We only test:
|
||||
- the ValueError path for unknown names (no providers need to exist)
|
||||
- that the signature accepts *args / **kwargs (so all three modules work)
|
||||
|
||||
NOTE: This test file is currently skipped at module level because importing
|
||||
`core.utils.intent` triggers `setup_logging()` at module load time, which
|
||||
requires `data/.config.yaml` to exist. That file is .gitignore'd and not
|
||||
present in CI. To enable this test suite, either:
|
||||
1. Make `setup_logging()` lazy (move the call out of module-level scope).
|
||||
2. Provide a stub `data/.config.yaml` in the test environment.
|
||||
Tracked as deferred-minor in progress.md.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
pytest.skip(
|
||||
"setup_logging() at module import requires data/.config.yaml; skipped",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
from core.utils import intent, llm, memory # noqa: E402 (unreachable when skipped)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("factory,module_type", [
|
||||
(intent.create_instance, "intent"),
|
||||
(llm.create_instance, "llm"),
|
||||
(memory.create_instance, "memory"),
|
||||
])
|
||||
def test_create_instance_raises_for_unknown_class(factory, module_type):
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
factory("definitely-not-a-real-provider-name-xyz")
|
||||
assert "不支持" in str(exc_info.value) or "不支持的" in str(exc_info.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("factory,module_type", [
|
||||
(intent.create_instance, "intent"),
|
||||
(llm.create_instance, "llm"),
|
||||
(memory.create_instance, "memory"),
|
||||
])
|
||||
def test_create_instance_accepts_args_and_kwargs(factory, module_type):
|
||||
"""Even when the provider exists, the call must accept *args and **kwargs.
|
||||
|
||||
We don't need to assert successful creation — just that the signature
|
||||
is variadic. We use a sentinel that will fail the path check.
|
||||
"""
|
||||
with pytest.raises(ValueError):
|
||||
factory("__missing__", "positional-arg", kwarg="value")
|
||||
53
main/xiaozhi-server/tests/core/utils/test_output_counter.py
Normal file
53
main/xiaozhi-server/tests/core/utils/test_output_counter.py
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
"""Tests for the per-device daily output character counter."""
|
||||
import pytest
|
||||
|
||||
from core.utils import output_counter
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_counter():
|
||||
"""Each test starts with a clean counter."""
|
||||
output_counter.reset_device_output()
|
||||
yield
|
||||
output_counter.reset_device_output()
|
||||
|
||||
|
||||
def test_get_device_output_returns_zero_when_never_added():
|
||||
assert output_counter.get_device_output("dev-1") == 0
|
||||
|
||||
|
||||
def test_add_device_output_increments_count():
|
||||
output_counter.add_device_output("dev-1", 100)
|
||||
output_counter.add_device_output("dev-1", 50)
|
||||
assert output_counter.get_device_output("dev-1") == 150
|
||||
|
||||
|
||||
def test_add_device_output_is_per_device():
|
||||
output_counter.add_device_output("dev-1", 100)
|
||||
output_counter.add_device_output("dev-2", 200)
|
||||
assert output_counter.get_device_output("dev-1") == 100
|
||||
assert output_counter.get_device_output("dev-2") == 200
|
||||
|
||||
|
||||
def test_check_device_output_limit_returns_true_when_exceeded():
|
||||
output_counter.add_device_output("dev-1", 100)
|
||||
assert output_counter.check_device_output_limit("dev-1", 100) is True
|
||||
assert output_counter.check_device_output_limit("dev-1", 50) is True
|
||||
|
||||
|
||||
def test_check_device_output_limit_returns_false_when_under():
|
||||
output_counter.add_device_output("dev-1", 50)
|
||||
assert output_counter.check_device_output_limit("dev-1", 100) is False
|
||||
|
||||
|
||||
def test_check_device_output_limit_with_empty_device_id_returns_false():
|
||||
assert output_counter.check_device_output_limit("", 1) is False
|
||||
assert output_counter.check_device_output_limit(None, 1) is False
|
||||
|
||||
|
||||
def test_reset_clears_all_counts():
|
||||
output_counter.add_device_output("dev-1", 100)
|
||||
output_counter.add_device_output("dev-2", 200)
|
||||
output_counter.reset_device_output()
|
||||
assert output_counter.get_device_output("dev-1") == 0
|
||||
assert output_counter.get_device_output("dev-2") == 0
|
||||
51
main/xiaozhi-server/tests/core/utils/test_textUtils.py
Normal file
51
main/xiaozhi-server/tests/core/utils/test_textUtils.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
"""Characterization tests for core/utils/textUtils.py."""
|
||||
from core.utils.textUtils import (
|
||||
is_emoji,
|
||||
is_punctuation_or_emoji,
|
||||
get_string_no_punctuation_or_emoji,
|
||||
check_emoji,
|
||||
)
|
||||
|
||||
|
||||
def test_is_emoji_returns_true_for_smile():
|
||||
assert is_emoji("🙂") is True
|
||||
|
||||
|
||||
def test_is_emoji_returns_false_for_ascii_letter():
|
||||
assert is_emoji("a") is False
|
||||
|
||||
|
||||
def test_is_emoji_returns_false_for_chinese_char():
|
||||
assert is_emoji("你") is False
|
||||
|
||||
|
||||
def test_is_punctuation_or_emoji_for_chinese_comma():
|
||||
assert is_punctuation_or_emoji(",") is True
|
||||
|
||||
|
||||
def test_is_punctuation_or_emoji_for_space():
|
||||
assert is_punctuation_or_emoji(" ") is True
|
||||
|
||||
|
||||
def test_is_punctuation_or_emoji_for_letter_is_false():
|
||||
assert is_punctuation_or_emoji("a") is False
|
||||
|
||||
|
||||
def test_get_string_no_punctuation_or_emoji_strips_both_sides():
|
||||
assert get_string_no_punctuation_or_emoji(", 你好 。") == "你好"
|
||||
|
||||
|
||||
def test_get_string_no_punctuation_or_emoji_no_punctuation():
|
||||
assert get_string_no_punctuation_or_emoji("你好") == "你好"
|
||||
|
||||
|
||||
def test_get_string_no_punctuation_or_emoji_empty_string():
|
||||
assert get_string_no_punctuation_or_emoji("") == ""
|
||||
|
||||
|
||||
def test_check_emoji_removes_emoji_keeps_text():
|
||||
assert check_emoji("hi 😀 there") == "hi there"
|
||||
|
||||
|
||||
def test_check_emoji_removes_newlines():
|
||||
assert check_emoji("a\nb") == "ab"
|
||||
0
main/xiaozhi-server/tests/plugins_func/__init__.py
Normal file
0
main/xiaozhi-server/tests/plugins_func/__init__.py
Normal file
26
main/xiaozhi-server/tests/plugins_func/test_loadplugins.py
Normal file
26
main/xiaozhi-server/tests/plugins_func/test_loadplugins.py
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
"""Test for the auto-import mechanism in plugins_func/loadplugins.py.
|
||||
|
||||
We import a real subpackage (`plugins_func.functions`) and verify the
|
||||
import side-effect runs. This protects against accidentally deleting
|
||||
`auto_import_modules` from `app.py` startup code.
|
||||
|
||||
NOTE: This test is currently skipped because importing
|
||||
`plugins_func.functions` triggers heavy module imports (cache_manager,
|
||||
etc.) that may not initialise in the test environment. To enable this
|
||||
test, ensure `data/.config.yaml` exists in the test environment or refactor
|
||||
plugin discovery to be lazy.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
pytest.skip(
|
||||
"plugins_func.functions import has side effects that need data/.config.yaml; skipped",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
from plugins_func.functions import get_time # noqa: F401 (unreachable when skipped)
|
||||
|
||||
|
||||
def test_functions_package_importable():
|
||||
"""If this test runs, plugins_func.functions.__init__.py has been imported."""
|
||||
import plugins_func.functions as fns
|
||||
assert hasattr(fns, "get_time")
|
||||
109
main/xiaozhi-server/tests/test_llm.py
Normal file
109
main/xiaozhi-server/tests/test_llm.py
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
"""LLM 链路测试。
|
||||
|
||||
Mock 模式(默认):从 data/.config.yaml 拿配置构造真实 provider,
|
||||
网络调用走 conftest 注入的 shim —— 不发任何请求。
|
||||
Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 LLM provider,参考
|
||||
``performance_tester_llm.py`` 的 ThreadPoolExecutor + 10s 超时模式。
|
||||
|
||||
接口约定(core/providers/llm/base.py):
|
||||
response(session_id, dialogue) -> Iterator[str],同步流式生成器
|
||||
response_no_stream(system_prompt, user_content) -> str
|
||||
|
||||
特殊处理:
|
||||
- CozeLLM 看 bot_id / user_id 而非 api_key
|
||||
- Ollama 要 model_name + 本地服务可用
|
||||
- placeholder 检测("你的" / "placeholder" / "xxx" / "sk-xxx")
|
||||
- 因为 LLM 是同步 generator,不能直接 asyncio.wait_for → 线程池
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import (
|
||||
CONFIG,
|
||||
LIVE_API_TESTS,
|
||||
get_provider_config,
|
||||
get_provider_type,
|
||||
get_selected_provider_name,
|
||||
has_real_key,
|
||||
)
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
|
||||
def _build_provider():
|
||||
name = get_selected_provider_name("LLM")
|
||||
if not name:
|
||||
pytest.skip("selected_module.LLM 未设置")
|
||||
cfg = get_provider_config("LLM", name)
|
||||
if not cfg:
|
||||
pytest.skip(f"LLM provider '{name}' 配置缺失")
|
||||
|
||||
# 任何模式下:key 是占位符 → skip。真请求需要真 key;mock 模式下
|
||||
# 没有真 key 跑下去也会撞真 SDK 的网络栈(openai/edge_tts)报错。
|
||||
if name == "CozeLLM":
|
||||
if any(x in cfg.get("bot_id", "") for x in ["你的"]) or any(
|
||||
x in cfg.get("user_id", "") for x in ["你的"]
|
||||
):
|
||||
pytest.skip("LLM 'CozeLLM' 的 bot_id/user_id 未配置")
|
||||
elif name == "Ollama":
|
||||
if not cfg.get("model_name"):
|
||||
pytest.skip("LLM 'Ollama' 的 model_name 未配置")
|
||||
elif not has_real_key(cfg, "api_key"):
|
||||
if LIVE_API_TESTS:
|
||||
pytest.skip(f"LLM '{name}' 的 api_key 未配置")
|
||||
else:
|
||||
pytest.skip(
|
||||
f"LLM '{name}' 的 api_key 是占位符(mock 模式不会真发请求)。"
|
||||
"真请求模式:export RUN_LIVE_API_TESTS=1 并填真 key 后再跑。"
|
||||
)
|
||||
|
||||
ptype = get_provider_type("LLM", name)
|
||||
if not ptype:
|
||||
pytest.skip(f"LLM '{name}' 的 type 字段缺失")
|
||||
from core.utils.llm import create_instance
|
||||
|
||||
return create_instance(ptype, cfg)
|
||||
|
||||
|
||||
def _collect_with_timeout(provider, session_id: str, dialogue, timeout: float = 10.0):
|
||||
"""调同步 generator response(),用线程池加 10s 超时。"""
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
|
||||
future = executor.submit(lambda: list(provider.response(session_id, dialogue)))
|
||||
return future.result(timeout=timeout)
|
||||
|
||||
|
||||
def test_llm_response_streams_non_empty() -> None:
|
||||
"""response(session_id, dialogue) 应产生非空 token 流。"""
|
||||
provider = _build_provider()
|
||||
dialogue = [
|
||||
{"role": "system", "content": "你是助手"},
|
||||
{"role": "user", "content": "用一句话说 hi"},
|
||||
]
|
||||
chunks = _collect_with_timeout(provider, "test-session", dialogue, timeout=10.0)
|
||||
|
||||
full = "".join(chunks).strip()
|
||||
assert isinstance(full, str), f"LLM chunks join 应是 str,得到 {type(full).__name__}"
|
||||
assert full, f"LLM 返回空响应(provider={type(provider).__name__})"
|
||||
|
||||
|
||||
def test_llm_response_no_stream_returns_string() -> None:
|
||||
"""response_no_stream 应返回非空字符串。"""
|
||||
provider = _build_provider()
|
||||
text = provider.response_no_stream("你是助手", "介绍一下北京").strip()
|
||||
|
||||
assert isinstance(text, str), f"response_no_stream 应返回 str,得到 {type(text).__name__}"
|
||||
assert text, "response_no_stream 返回空字符串"
|
||||
|
||||
|
||||
def test_llm_dialogue_min_length_one_user() -> None:
|
||||
"""至少一条 user 消息的 dialogue 应能跑通。"""
|
||||
provider = _build_provider()
|
||||
dialogue = [{"role": "user", "content": "ping"}]
|
||||
chunks = _collect_with_timeout(provider, "s1", dialogue, timeout=10.0)
|
||||
|
||||
assert "".join(chunks).strip(), "单 user 消息应返回内容"
|
||||
81
main/xiaozhi-server/tests/test_memory.py
Normal file
81
main/xiaozhi-server/tests/test_memory.py
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
"""Memory 链路测试。
|
||||
|
||||
Mock 模式(默认):从 data/.config.yaml 拿配置构造真实 provider;外部
|
||||
SDK 调用(mem0ai / powermem 客户端)走 shim,不会真发请求。
|
||||
Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 Memory provider。
|
||||
|
||||
接口约定(core/providers/memory/base.py):
|
||||
async save_memory(msgs, session_id=None) -> str
|
||||
async query_memory(query: str) -> str
|
||||
|
||||
默认 selected_module.Memory = nomem(不开启记忆,本地即可)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import (
|
||||
get_provider_config,
|
||||
get_provider_type,
|
||||
get_selected_provider_name,
|
||||
)
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
|
||||
def _build_provider():
|
||||
name = get_selected_provider_name("Memory")
|
||||
if not name:
|
||||
pytest.skip("selected_module.Memory 未设置")
|
||||
cfg = get_provider_config("Memory", name)
|
||||
if not cfg:
|
||||
pytest.skip(f"Memory provider '{name}' 配置缺失")
|
||||
ptype = get_provider_type("Memory", name)
|
||||
if not ptype:
|
||||
pytest.skip(f"Memory '{name}' 的 type 字段缺失")
|
||||
from core.utils.memory import create_instance
|
||||
|
||||
return create_instance(ptype, cfg, None)
|
||||
|
||||
|
||||
def test_memory_provider_constructs_from_config() -> None:
|
||||
"""从 config 应该能实例化出 MemoryProviderBase 子类。"""
|
||||
provider = _build_provider()
|
||||
from core.providers.memory.base import MemoryProviderBase
|
||||
|
||||
assert isinstance(provider, MemoryProviderBase), (
|
||||
f"Memory provider 类型错:{type(provider).__name__}"
|
||||
)
|
||||
|
||||
|
||||
def test_memory_provider_exposes_save_and_query() -> None:
|
||||
"""provider 必须实现 save_memory / query_memory。"""
|
||||
provider = _build_provider()
|
||||
assert hasattr(provider, "save_memory"), (
|
||||
f"{type(provider).__name__} 缺少 save_memory 方法"
|
||||
)
|
||||
assert hasattr(provider, "query_memory"), (
|
||||
f"{type(provider).__name__} 缺少 query_memory 方法"
|
||||
)
|
||||
|
||||
|
||||
def test_memory_save_and_query_roundtrip() -> None:
|
||||
"""save 后 query 应该不抛异常;nomem 返回 None/空串都算通过。"""
|
||||
provider = _build_provider()
|
||||
msgs = [{"role": "user", "content": "test message"}]
|
||||
|
||||
async def run():
|
||||
mid = await provider.save_memory(msgs, "test-session")
|
||||
result = await provider.query_memory("test")
|
||||
return mid, result
|
||||
|
||||
mid, result = asyncio.run(run())
|
||||
# nomem 等"不开记忆"实现可能返回 None;真实记忆服务应返回 str ID
|
||||
assert mid is None or isinstance(mid, str), (
|
||||
f"save_memory 应返回 str 或 None,得到 {type(mid).__name__}"
|
||||
)
|
||||
assert isinstance(result, str), "query_memory 应返回 str"
|
||||
78
main/xiaozhi-server/tests/test_rag.py
Normal file
78
main/xiaozhi-server/tests/test_rag.py
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
"""RAG(检索增强生成)链路测试。
|
||||
|
||||
xiaozhi-esp32-server 项目里没有独立的 RAG provider —— RAG 由
|
||||
MemoryProvider(mem0ai / powermem)的 ``query_memory`` 配合 LLM 工具
|
||||
调用实现。本测试聚焦「save → query → 拿到检索结果」这一核心链路。
|
||||
|
||||
Mock 模式(默认):mem0/powermem 等云调用走 shim,不发请求。
|
||||
Live 模式(``RUN_LIVE_API_TESTS=1``):真发请求到所选 memory provider。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import (
|
||||
get_provider_config,
|
||||
get_provider_type,
|
||||
get_selected_provider_name,
|
||||
)
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
|
||||
def _build_memory_provider():
|
||||
name = get_selected_provider_name("Memory")
|
||||
if not name:
|
||||
pytest.skip("selected_module.Memory 未设置")
|
||||
cfg = get_provider_config("Memory", name)
|
||||
if not cfg:
|
||||
pytest.skip(f"Memory provider '{name}' 配置缺失")
|
||||
ptype = get_provider_type("Memory", name)
|
||||
if not ptype:
|
||||
pytest.skip(f"Memory '{name}' 的 type 字段缺失")
|
||||
from core.utils.memory import create_instance
|
||||
|
||||
return create_instance(ptype, cfg, None)
|
||||
|
||||
|
||||
def test_rag_query_after_save_returns_string() -> None:
|
||||
"""保存后 query_memory 应返回字符串(nomem 返回空串也合法)。"""
|
||||
provider = _build_memory_provider()
|
||||
msgs = [
|
||||
{"role": "user", "content": "我喜欢喝咖啡"},
|
||||
{"role": "assistant", "content": "好的记住了"},
|
||||
]
|
||||
|
||||
async def run():
|
||||
await provider.save_memory(msgs, "rag-session")
|
||||
return await provider.query_memory("咖啡")
|
||||
|
||||
result = asyncio.run(run())
|
||||
assert isinstance(result, str), f"query_memory 应返回 str,得到 {type(result).__name__}"
|
||||
|
||||
|
||||
def test_rag_query_no_match_returns_empty() -> None:
|
||||
"""query 不存在内容时返回空字符串,不抛异常。"""
|
||||
provider = _build_memory_provider()
|
||||
|
||||
async def run():
|
||||
return await provider.query_memory("完全不存在的关键词xyz")
|
||||
|
||||
result = asyncio.run(run())
|
||||
assert isinstance(result, str)
|
||||
|
||||
|
||||
def test_rag_empty_query_handled() -> None:
|
||||
"""空 query 不应抛异常。"""
|
||||
provider = _build_memory_provider()
|
||||
|
||||
async def run():
|
||||
await provider.save_memory([{"role": "user", "content": "测试"}], "s")
|
||||
return await provider.query_memory("")
|
||||
|
||||
result = asyncio.run(run())
|
||||
assert isinstance(result, str)
|
||||
14
main/xiaozhi-server/tests/test_smoke.py
Normal file
14
main/xiaozhi-server/tests/test_smoke.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
"""Smoke test — confirms pytest can collect from this directory.
|
||||
|
||||
Real tests land in Slice 2 (see docs/superpowers/specs/2026-09-02-test-infrastructure-design.md).
|
||||
"""
|
||||
|
||||
|
||||
def test_pytest_works():
|
||||
assert 1 + 1 == 2
|
||||
|
||||
|
||||
def test_repo_path_is_writable(tmp_path):
|
||||
p = tmp_path / "scratch.txt"
|
||||
p.write_text("ok", encoding="utf-8")
|
||||
assert p.read_text(encoding="utf-8") == "ok"
|
||||
128
main/xiaozhi-server/tests/test_stt.py
Normal file
128
main/xiaozhi-server/tests/test_stt.py
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
"""ASR(语音识别)链路测试。
|
||||
|
||||
Mock 模式(默认):从 data/.config.yaml 拿配置构造真实 ASR provider;
|
||||
所有外部 HTTP/SDK 调用走 conftest 注入的 shim,不发真请求。
|
||||
Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 ASR provider。
|
||||
|
||||
接口约定(core/providers/asr/base.py):
|
||||
async speech_to_text_wrapper(pcm_data, session_id) -> Tuple[Optional[str], Optional[str]]
|
||||
async speech_to_text(opus_data, session_id, artifacts) -> Tuple[Optional[str], Optional[str]]
|
||||
|
||||
注意:
|
||||
- performance_tester_asr.py 用 3-arg 调 wrapper 是错的(base 只接 2 个),
|
||||
这里用 2-arg 正确版本
|
||||
- FunASR 是本地模型:构造时会加载 model_dir 的模型文件;
|
||||
如果模型没下载,`__init__` 直接抛异常,测试会 skip
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import (
|
||||
get_provider_config,
|
||||
get_provider_type,
|
||||
get_selected_provider_name,
|
||||
)
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
_ASSETS_DIR = Path(__file__).resolve().parent.parent / "config" / "assets"
|
||||
|
||||
|
||||
def _build_provider():
|
||||
name = get_selected_provider_name("ASR")
|
||||
if not name:
|
||||
pytest.skip("selected_module.ASR 未设置")
|
||||
cfg = get_provider_config("ASR", name)
|
||||
if not cfg:
|
||||
pytest.skip(f"ASR provider '{name}' 配置缺失")
|
||||
ptype = get_provider_type("ASR", name)
|
||||
if not ptype:
|
||||
pytest.skip(f"ASR '{name}' 的 type 字段缺失")
|
||||
from core.utils.asr import create_instance
|
||||
|
||||
return create_instance(ptype, cfg, True)
|
||||
|
||||
|
||||
def _find_test_audio() -> Path:
|
||||
"""从 config/assets/ 找 >300KB 的 wav 当测试音频。"""
|
||||
if not _ASSETS_DIR.exists():
|
||||
pytest.skip(f"音频目录不存在:{_ASSETS_DIR}")
|
||||
wavs = sorted(
|
||||
(p for p in _ASSETS_DIR.glob("*.wav") if p.stat().st_size > 300 * 1024),
|
||||
key=lambda p: p.stat().st_size,
|
||||
reverse=True, # 最大的优先
|
||||
)
|
||||
if not wavs:
|
||||
pytest.skip(f"config/assets/ 下没有 >300KB 的 wav 文件")
|
||||
return wavs[0]
|
||||
|
||||
|
||||
def test_asr_provider_constructs_from_config() -> None:
|
||||
"""从 config 应该能实例化出 ASRProviderBase 子类。"""
|
||||
provider = _build_provider()
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
|
||||
assert isinstance(provider, ASRProviderBase), (
|
||||
f"ASR provider 类型错:{type(provider).__name__}"
|
||||
)
|
||||
|
||||
|
||||
def test_asr_provider_exposes_speech_to_text() -> None:
|
||||
"""provider 必须实现 speech_to_text 方法。"""
|
||||
provider = _build_provider()
|
||||
assert hasattr(provider, "speech_to_text"), (
|
||||
f"{type(provider).__name__} 缺少 speech_to_text 方法"
|
||||
)
|
||||
assert callable(provider.speech_to_text)
|
||||
|
||||
|
||||
def test_asr_provider_has_output_dir() -> None:
|
||||
"""provider 应有 output_dir 属性(写入识别结果用)。"""
|
||||
provider = _build_provider()
|
||||
assert hasattr(provider, "output_dir"), (
|
||||
f"{type(provider).__name__} 缺少 output_dir 属性"
|
||||
)
|
||||
|
||||
|
||||
def test_asr_speech_to_text_wrapper_returns_text() -> None:
|
||||
"""真发一次 ASR 请求(live 模式),断言返回识别结果。
|
||||
|
||||
Mock 模式下也照常调,但 shim 返回空 dict/text,断言宽松:
|
||||
text 可以是 None / str / dict,只要不抛异常就算通过。
|
||||
|
||||
参考 performance_tester_asr.py:
|
||||
- 喂真实 wav 文件 bytes 给 speech_to_text_wrapper
|
||||
- 10s 超时
|
||||
- 返回的 text 可能是 None(识别失败)/ str(部分 provider)/ dict(FunASR 等带 emotion/language 的)
|
||||
"""
|
||||
provider = _build_provider()
|
||||
# Mock 模式下没有 wav 资产也能跑(shim 不读文件)。
|
||||
from tests.conftest import LIVE_API_TESTS
|
||||
if LIVE_API_TESTS:
|
||||
wav_path = _find_test_audio()
|
||||
audio_data = wav_path.read_bytes()
|
||||
else:
|
||||
# Mock 模式:喂占位 bytes,shim 不会真去解码。
|
||||
audio_data = b"\x00" * 1024
|
||||
|
||||
async def run():
|
||||
return await asyncio.wait_for(
|
||||
provider.speech_to_text_wrapper([audio_data], "test-session"),
|
||||
timeout=10.0,
|
||||
)
|
||||
|
||||
text, file_path = asyncio.run(run())
|
||||
# ASR 结果兼容性:None / str / dict(FunASR 返回 {content, language, emotion})
|
||||
assert text is None or isinstance(text, (str, dict)), (
|
||||
f"speech_to_text_wrapper 应返回 (None/str/dict, str|None),"
|
||||
f"得到 text 类型 {type(text).__name__}"
|
||||
)
|
||||
if isinstance(text, dict):
|
||||
# FunASR 风格:取 content 字段(live 模式才严格校验)。
|
||||
if LIVE_API_TESTS:
|
||||
assert text.get("content"), f"ASR dict 结果缺少 content:{text!r}"
|
||||
127
main/xiaozhi-server/tests/test_tts.py
Normal file
127
main/xiaozhi-server/tests/test_tts.py
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
"""TTS(语音合成)链路测试。
|
||||
|
||||
Mock 模式(默认):从 data/.config.yaml 拿配置构造真实 TTS provider;
|
||||
所有外部 HTTP/SDK 调用走 conftest 注入的 shim,不发真请求。
|
||||
Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 TTS provider。
|
||||
|
||||
接口约定(core/providers/tts/base.py):
|
||||
text_to_speak(text, output_file) -> 异步,把合成结果写到 output_file
|
||||
|
||||
注意:
|
||||
- 3 个构造测试不依赖云服务;第 4 个 test_tts_text_to_speak_writes_nonempty_file
|
||||
才是真链路测试,会真发 HTTP。
|
||||
- Mock 模式下:第 4 个测试断言宽松 —— 文件存在即可(shim 创建空文件),
|
||||
不强求 size > 0。Live 模式下严格校验 size > 0。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import (
|
||||
LIVE_API_TESTS,
|
||||
get_provider_config,
|
||||
get_provider_type,
|
||||
get_selected_provider_name,
|
||||
)
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
|
||||
def _build_provider():
|
||||
name = get_selected_provider_name("TTS")
|
||||
if not name:
|
||||
pytest.skip("selected_module.TTS 未设置")
|
||||
cfg = get_provider_config("TTS", name)
|
||||
if not cfg:
|
||||
pytest.skip(f"TTS provider '{name}' 配置缺失")
|
||||
ptype = get_provider_type("TTS", name)
|
||||
if not ptype:
|
||||
pytest.skip(f"TTS '{name}' 的 type 字段缺失")
|
||||
from core.utils.tts import create_instance
|
||||
|
||||
return create_instance(ptype, cfg, True)
|
||||
|
||||
|
||||
def test_tts_provider_constructs_from_config() -> None:
|
||||
"""从 config 应该能实例化出 TTSProviderBase 子类。"""
|
||||
provider = _build_provider()
|
||||
from core.providers.tts.base import TTSProviderBase
|
||||
|
||||
assert isinstance(provider, TTSProviderBase), (
|
||||
f"TTS provider 类型错:{type(provider).__name__}"
|
||||
)
|
||||
|
||||
|
||||
def test_tts_provider_exposes_to_tts() -> None:
|
||||
"""provider 必须实现 to_tts / to_tts_stream 之一。"""
|
||||
provider = _build_provider()
|
||||
has_sync = hasattr(provider, "to_tts") and callable(provider.to_tts)
|
||||
has_stream = hasattr(provider, "to_tts_stream") and callable(
|
||||
provider.to_tts_stream
|
||||
)
|
||||
assert has_sync or has_stream, (
|
||||
f"{type(provider).__name__} 缺少 to_tts / to_tts_stream 方法"
|
||||
)
|
||||
|
||||
|
||||
def test_tts_provider_has_output_dir() -> None:
|
||||
"""provider 应有 output_file 属性(合成结果写到哪)。"""
|
||||
provider = _build_provider()
|
||||
assert hasattr(provider, "output_file"), (
|
||||
f"{type(provider).__name__} 缺少 output_file 属性"
|
||||
)
|
||||
assert isinstance(provider.output_file, str)
|
||||
assert provider.output_file, "output_file 不应为空"
|
||||
|
||||
|
||||
def test_tts_text_to_speak_writes_file() -> None:
|
||||
"""Mock 模式:断言 file 存在即可。Live 模式:断言 size > 0。
|
||||
|
||||
参考 performance_tester_tts.py 的实现:
|
||||
- mock conn(sample_rate/audio_format/stop_event/client_abort/headers)
|
||||
和 opus_encoder(SimpleNamespace 占位即可)
|
||||
- generate_filename() 拿输出路径
|
||||
- text_to_speak() 异步调云服务,写文件
|
||||
- 10s 超时
|
||||
- 用完删掉测试文件,避免 tmp/ 目录堆积
|
||||
"""
|
||||
provider = _build_provider()
|
||||
|
||||
# 参考 performance_tester_tts.py:部分 provider 内部访问 self.conn.sample_rate 等
|
||||
if not hasattr(provider, "conn") or provider.conn is None:
|
||||
provider.conn = SimpleNamespace(
|
||||
sample_rate=16000,
|
||||
audio_format="pcm",
|
||||
stop_event=threading.Event(),
|
||||
client_abort=False,
|
||||
headers={},
|
||||
)
|
||||
if not hasattr(provider, "opus_encoder") or provider.opus_encoder is None:
|
||||
provider.opus_encoder = SimpleNamespace()
|
||||
|
||||
out_file = provider.generate_filename()
|
||||
try:
|
||||
async def run():
|
||||
await asyncio.wait_for(
|
||||
provider.text_to_speak("测试一下", out_file),
|
||||
timeout=10.0,
|
||||
)
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
assert os.path.exists(out_file), f"输出文件不存在:{out_file}"
|
||||
if LIVE_API_TESTS:
|
||||
assert os.path.getsize(out_file) > 0, f"输出文件为空:{out_file}"
|
||||
finally:
|
||||
if os.path.exists(out_file):
|
||||
try:
|
||||
os.remove(out_file)
|
||||
except OSError:
|
||||
pass
|
||||
Loading…
Reference in a new issue