chore(westernization): translate remaining Han text across code, UI and docs

Final localization pass over everything the audit covers, driven by the
local qwen3.8:instruct endpoint (thinking disabled) with placeholder-
masked, cached, resumable batches:

- Python server: comments, docstrings, log/error messages, prompt text
- manager-api Java: javadoc, exception messages, Swagger summaries,
  westernized test fixtures (locale strings, signed-URL examples)
- manager-web / manager-mobile: component comments and misc leftovers
  (functional split regexes such as /[、;;,,]/ left byte-identical)
- digital-human: HTML/UI text, JS comments, wake-word defaults aligned
  with the server canonical English wake words
- docs: device-call guide, wakeword and search integration guides

Also widens the westernization audit exception to the whole vendored
generator bundle and retires the stale per-file exception list.
This commit is contained in:
lapy 2026-10-11 17:58:15 +01:00
parent 302ed23055
commit 70771b4209
139 changed files with 3465 additions and 3467 deletions

View file

@ -1,32 +1,32 @@
# 一体机数字人配置指南
# All-in-one Digital Human Configuration Guide
本项目用于在 x86 架构设备(如迷你主机、工控机、普通电脑等)上部署一套完整的数字人展示系统,实现以下功能:
- 开机自动进入 Kiosk 全屏浏览器,展示指定网页
- 后台运行唤醒词检测服务,支持语音交互
This project deploys a complete digital human display system on x86 devices (e.g., mini PCs, industrial PCs, standard computers), implementing the following features:
- Auto-launch Kiosk full-screen browser on boot to display the specified webpage
- Run wake word detection service in background, supporting voice interaction
> **说明**:本文档以 **Intel N100 迷你主机(天虹 QN10-100B4)** 为例进行部署演示,其他 x86 设备可参考调整(注意网络配置和声卡设备差异)。
> **Note**: This document uses the **Intel N100 mini PC (Tianhong QN10-100B4)** as an example for deployment. Other x86 devices can refer to this guide with adjustments (note differences in network configuration and sound card devices).
## 适用环境
## Environment
| 项目 | 说明 |
| Item | Description |
|------|------|
| 示例硬件 | 天虹 QN10-100B4(Intel N100) |
| 操作系统 | Ubuntu 24.04 LTS (Noble Numbat) |
| 示例用户 | xz(请根据实际情况替换) |
| 网络 | Wi-Fi 连接,固定 IP(可按需改为有线) |
| Example Hardware | Tianhong QN10-100B4 (Intel N100) |
| OS | Ubuntu 24.04 LTS (Noble Numbat) |
| Example user | xz (replace as needed) |
| Network | Wi-Fi connection, static IP (can be changed to wired if needed) |
## 部署流程
## Deployment Process
1. 系统初始化(换源、连网)
2. 安装图形组件与 Kiosk 浏览器
3. 配置自动登录与图形界面
4. 部署唤醒词服务(Python 环境 + 麦克风)
5. 优化开机速度与隐藏启动信息
1. System initialization (switch source, connect network)
2. Install graphical components and Kiosk browser
3. Configure auto-login and GUI
4. Deploy wake word service (Python environment + microphone)
5. Optimize boot speed and hide startup info
---
### 系统初始化(换源、连网)
### System initialization (switch source, connect network)
```
sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
@ -52,7 +52,7 @@ echo 'Acquire::ForceIPv4 "true";' | sudo tee /etc/apt/apt.conf.d/99force-ipv4
```
安装网络管理工具(若已存在可忽略)
Install network management tool (ignore if already exists)
Bash
@ -64,9 +64,9 @@ sudo systemctl enable NetworkManager
```
设置wifi密码,固定ip
Set Wi-Fi password and static IP
> **提醒**:以下命令中的 Wi-Fi 名称、密码、IP 地址均为示例,请务必替换为你自己的实际信息。
> **Note**: The Wi-Fi name, password, and IP address in the following commands are examples. Replace them with your actual information.
Bash
@ -79,9 +79,9 @@ sudo nmcli connection up "MERCURY_1812"
```
### 第一步:安装核心图形组件与浏览器
### Step 1: Install core graphics components and browser
这里我们坚持“极简主义”,坚决不装多余的桌面环境(如 GNOME/KDE),只装底层驱动、最轻量的窗口管理器(Openbox)、隐藏鼠标工具以及 Chromium 浏览器。
We adhere to "minimalism", strictly avoiding unnecessary desktop environments (such as GNOME/KDE), installing only low-level drivers, the lightest window manager (Openbox), mouse hiding tools, and the Chromium browser.
Bash
@ -100,11 +100,11 @@ sudo apt purge snapd -y
```
### 第二步:配置 TTY1 开机免密自动登录
### Step 2: Configure passwordless auto-login for TTY1 on boot
为了避免手动输入账号密码的尴尬,我们通过修改 systemd 服务,让系统一开机就自动以 `xz` 的身份登录。这里使用一键写入命令,彻底避开由于 `nano` 或 `vi` 操作不当导致的保存失败问题。
To avoid the awkwardness of manually entering credentials, we modify the systemd service to automatically log in as `xz` on boot. Use the one-click write command to completely avoid save failures caused by improper `nano` or `vi` operations.
**1. 创建配置目录:**
**1. Create config directory:**
Bash
@ -112,7 +112,7 @@ Bash
sudo mkdir -p /etc/systemd/system/getty@tty1.service.d/
```
**2. 写入自动登录规则:**
**2. Write auto-login rules:**
Bash
@ -120,7 +120,7 @@ Bash
echo -e "[Service]\nExecStart=\nExecStart=-/sbin/agetty --autologin xz --noclear %I \$TERM" | sudo tee /etc/systemd/system/getty@tty1.service.d/override.conf
```
**3. 重载服务并设置默认启动目标:**
**3. Reload service and set default startup target:**
Bash
@ -129,13 +129,13 @@ sudo systemctl daemon-reload
sudo systemctl set-default multi-user.target
```
### 第三步:配置登录后自动启动图形界面
### Step 3: Configure GUI to auto-start after login
系统自动登录后默认停留在黑底白字的命令行,我们需要配置脚本,让它一旦登录立马启动 X11 图形环境。
After automatic system login, the default state is a black-background white-text command line. Configure a script to launch the X11 graphical environment immediately upon login.
**1. 触发 `startx` 的启动逻辑:**
**1. Trigger the startup logic for `startx`:**
直接将触发代码追加写入你的个人环境配置文件中:
Append trigger code directly to your personal environment config file:
Bash
@ -147,7 +147,7 @@ fi
EOF
```
**2. 告诉 `startx` 去启动 Openbox:**
**2. Tell `startx` to start Openbox:**
Bash
@ -155,11 +155,11 @@ Bash
echo "exec openbox-session" > ~/.xinitrc
```
### 第四步:配置“铜墙铁壁”的 Openbox 与浏览器
### Step 4: Configure 'fortress-like' Openbox and browser
这是最核心的一步:关闭屏幕休眠、隐藏鼠标、全屏锁定浏览器,并写一个“死循环”保证浏览器被意外关闭后也能瞬间复活。
Critical step: Disable screen sleep, hide the mouse, lock the browser in fullscreen, and implement a watchdog loop to instantly restart the browser if it closes unexpectedly.
**1. 创建 Openbox 配置目录:**
**1. Create Openbox config directory:**
Bash
@ -167,23 +167,23 @@ Bash
mkdir -p ~/.config/openbox
```
**2. 写入自启动脚本 (`autostart`):**
**2. Write autostart script (`autostart`):**
复制以下整段代码并回车(这会自动把所有保护规则写进文件里):
Copy the entire code block below and press Enter (this automatically writes all protection rules to the file):
Bash
```
cat << 'EOF' > ~/.config/openbox/autostart
# 关闭屏幕保护
# Disable screensaver
xset -dpms
xset s noblank
xset s off
# 隐藏鼠标
# Hide Cursor
unclutter -idle 0.1 -root &
# 死循环启动 Chromium(崩溃或被关也能秒重启)
# Infinite loop to launch Chromium (instant restart on crash or close)
while true; do
google-chrome \
--kiosk \
@ -201,9 +201,9 @@ done &
EOF
```
**3. 屏蔽 `Alt+F4` 退出快捷键:**
**3. Disable the `Alt+F4` exit shortcut:**
为了防止别人插上键盘强行关掉窗口,我们把 Openbox 默认的系统快捷键干掉。
To prevent others from closing the window via keyboard shortcuts, disable Openbox default system shortcuts.
Bash
@ -212,9 +212,9 @@ cp /etc/xdg/openbox/rc.xml ~/.config/openbox/
sed -i '/<keybind key="A-F4">/,/<\/keybind>/d' ~/.config/openbox/rc.xml
```
### 第五步:重启验收成果
### Step 5: Restart to verify results
如果拔掉网线或不需要等待所有网络上线,可禁用网络等待服务,避免开机卡顿
If the network cable is unplugged or waiting for all networks to come online is unnecessary, disable the network wait service to avoid boot lag
Bash
@ -223,7 +223,7 @@ sudo systemctl mask systemd-networkd-wait-online.service
sudo systemctl mask NetworkManager-wait-online.service
```
隐藏开机信息(GRUB)
Hide boot info (GRUB)
Bash
@ -236,7 +236,7 @@ echo 'GRUB_RECORDFAIL_TIMEOUT=0' | sudo tee -a /etc/default/grub
sudo update-grub
```
声音设置成100%,然后 重启:
Set volume to 100%, then restart:
Bash
@ -245,11 +245,11 @@ amixer -q sset Master 100% unmute
sudo reboot
```
### 部署唤醒词服务
### Deploy wake word service
在一体机上部署唤醒词检测服务,需要安装 Python 环境、上传项目文件、配置 Camera 麦克风和开机自启。
To deploy the wake word detection service on an all-in-one device, install the Python environment, upload project files, configure the Camera microphone, and set up auto-start on boot.
#### 1. 安装 Miniconda
#### 1. Install Miniconda
```bash
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
@ -260,7 +260,7 @@ rm Miniconda3-latest-Linux-x86_64.sh
```
确保登录时自动进入conda环境
Ensure automatic entry into the conda environment upon login
```bash
if ! grep -q '.bashrc' ~/.bash_profile; then
@ -274,38 +274,38 @@ fi
```
#### 2. 创建 Python 虚拟环境
#### 2. Create Python virtual environment
```bash
conda create -n test python=3.10 -y
conda activate test
```
若出现 Terms of Service have not been accepted 错误,执行:
If the 'Terms of Service have not been accepted' error occurs, run:
```bash
conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main
conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r
```
#### 3. 上传项目文件
#### 3. Upload project files
将开发机上的 `main/digital-human/` 整个目录上传到一体机的 `~/digital-human/` 目录:
Upload the entire `main/digital-human/` directory from the dev machine to the `~/digital-human/` directory on the all-in-one device:
```bash
# 在开发机上执行(将 <一体机IP> 替换为实际 IP)
scp -r main/digital-human/ xz@<一体机IP>:~/digital-human/
# Execute on the development machine (replace <All-in-One IP> with the actual IP)
scp -r main/digital-human/ xz@<All-in-One IP>:~/digital-human/
```
#### 4. 安装系统依赖
#### 4. Install system dependencies
唤醒词服务需要音频采集库和 ALSA PulseAudio 插件:
The wake word service requires audio capture libraries and ALSA PulseAudio plugins:
```bash
sudo apt install libportaudio2 portaudio19-dev libasound2-plugins -y
```
#### 5. 安装 Python 依赖
#### 5. Install Python dependencies
```bash
cd ~/digital-human/wakeword_runtime
@ -313,58 +313,58 @@ pip install numpy
pip install -r requirements.txt
```
#### 6. 下载唤醒词模型
#### 6. Download wake word model
模型文件不包含在项目中,需要单独下载配置,详见 [docs/digital-human-wakeword.md](digital-human-wakeword.md) 中的“模型下载”章节。
Model files are not included in the project and must be downloaded and configured separately. See the "Model Download" section in [docs/digital-human-wakeword.md](digital-human-wakeword.md).
#### 7. 修改 Openbox 自启动脚本
#### 7. Modify Openbox autostart script
需要在 autostart 中加上 PulseAudio 和 Camera 麦克风配置,并将 Chrome 地址改为测试页面。
Add PulseAudio and Camera microphone configs to autostart, and change Chrome URL to the test page.
先确认 Camera 麦克风在 PulseAudio 中的设备名:
First verify the Camera microphone device name in PulseAudio:
```bash
pulseaudio --start
pactl list sources short
```
找到包含 `USB_Camera` 的那一行,记下完整名称,例如:
Find the line containing `USB_Camera`, note the full name, e.g.:
```
alsa_input.usb-SN0002_2K_USB_Camera_46435000_P030D00_SN0002-02.mono-fallback
```
然后用完整内容覆盖 autostart(将 `TARGET_MIC` 替换为你的实际设备名):
Then overwrite autostart with the full content (replace `TARGET_MIC` with your actual device name):
```bash
cat << 'EOF' > ~/.config/openbox/autostart
# 1. 启动声音服务并稍作等待
# 1. Start the audio service and wait briefly
pulseaudio --start
sleep 1
# 2. 锁定 Camera 的麦克风(请替换为你的实际设备名)
# 2. Lock Camera microphone (replace with your actual device name)
TARGET_MIC="alsa_input.usb-SN0002_2K_USB_Camera_46435000_P030D00_SN0002-02.mono-fallback"
# 3. 设为系统默认麦克风
# 3. Set as system default microphone
pactl set-default-source "$TARGET_MIC"
# 4. 解除静音
# 4. Unmute
pactl set-source-mute "$TARGET_MIC" 0
# 5. 音量拉到 100%
# 5. Set volume to 100%
pactl set-source-volume "$TARGET_MIC" 100%
# --- 极简桌面与浏览器环境配置 ---
# --- Minimal desktop and browser environment configuration ---
# 关闭屏幕保护
# Disable screensaver
xset -dpms
xset s noblank
xset s off
# 隐藏鼠标
# Hide Cursor
unclutter -idle 0.1 -root &
# 死循环启动浏览器(崩溃或被关也能秒重启)
# Start browser in infinite loop (restarts instantly on crash or close)
while true; do
google-chrome \
--kiosk \
@ -382,17 +382,17 @@ done &
EOF
```
#### 8. 配置唤醒词服务开机自启
#### 8. Configure wake word service to start on boot
创建 systemd 服务文件,让唤醒词服务开机自动运行。
Create a systemd service file to enable the wake word service to run automatically on boot.
先确认当前用户的 UID:
First confirm the current user's UID:
```bash
id -u $(whoami)
```
然后用查到的 UID 替换下面 `1000`(通常第一个用户就是 1000):
Then replace the UID below with the one you found `1000` (the first user is usually 1000):
```bash
sudo tee /etc/systemd/system/digital-human.service << 'EOF'
@ -416,13 +416,13 @@ WantedBy=multi-user.target
EOF
```
> **重要说明**:
> - `User=xz` — 替换为你的实际用户名
> - `/run/user/1000` — 替换为你实际的 UID
> - `WorkingDirectory` 和 `ExecStart` 中的路径 — 替换为你的实际部署路径
> - `Environment` 中的 PulseAudio 环境变量**必须保留**,否则唤醒词服务和浏览器无法同时使用 Camera 麦克风
> **Important Note**:
> - `User=xz` - Replace with your actual username
> - `/run/user/1000` - Replace with your actual UID
> - Paths in `WorkingDirectory` and `ExecStart` - Replace with your actual deployment paths
> - The PulseAudio environment variables in `Environment` **must be preserved**, otherwise the wake word service and browser cannot simultaneously use the Camera microphone
启用并启动服务:
Enable and start service:
```bash
sudo systemctl daemon-reload
@ -430,13 +430,13 @@ sudo systemctl enable digital-human
sudo systemctl start digital-human
```
#### 9. 常用服务管理命令
#### 9. Common service management commands
```bash
sudo systemctl start digital-human # 立即启动
sudo systemctl stop digital-human # 停止
sudo systemctl restart digital-human # 重启
sudo systemctl status digital-human # 查看状态
journalctl -u digital-human -f # 查看实时日志
sudo systemctl start digital-human # Start now
sudo systemctl stop digital-human # Stop
sudo systemctl restart digital-human # Restart
sudo systemctl status digital-human # View status
journalctl -u digital-human -f # View real-time logs
```

View file

@ -1,60 +1,60 @@
# 设备间相互呼叫插件使用指南
# Inter-device mutual call plugin usage guide
## 概述
## Overview
设备呼叫功能允许两个已配置设备之间通过语音/数据通道进行双向通信。设备A呼叫设备B时,系统通过以下流程实现:
The device call feature enables bidirectional communication between two configured devices via voice/data channels. When Device A calls Device B, the system follows this process:
```
设备A → 授权校验 → MQTT网关 → 设备B远程唤醒 → 建立连接 → 通话建立
Device A → Authorization Check → MQTT Gateway → Remote Wake-up of Device B → Connection Established → Call Established
```
## 使用这个功能的前提条件
1. 你必须要有至少两个设备,每个设备型号必须是`ESP32-S3`,因为只有`ESP32-S3`才支持远程唤醒功能。
2. 你的设备必须要有`两个麦克风`。但是如果你的设备只有`单个麦克风`,你只是想体验一下这个功能,也是可以的,但是会有强烈的卡顿感。
3. 你必须使用[全模块部署](Deployment_all.md)本项目,因为你需要`智控台`来管理设备的权限和通信。
4. 你必须安装并配置好`2026年5月27日`以后的[MQTT网关服务](mqtt-gateway-integration.md),如果你已经部署了MQTT网关服务,请确认代码的版本是`2026年5月27日`之后的版本。
## Prerequisites for using this feature
1. You must have at least two devices, each of model `ESP32-S3`, because only `ESP32-S3` supports remote wake-up.
2. Your device must have `two microphones`. If your device has only a `single microphone`, you can still try this feature, but expect significant lag.
3. You must use [Full Module Deployment](Deployment_all.md) for this project, as you need the `Console` to manage device permissions and communication.
4. You must install and configure the [MQTT Gateway Service ](mqtt-gateway-integration.md) after `May 27, 2026`. If you have already deployed the MQTT Gateway Service, ensure the code version is after `May 27, 2026`.
以上是使用这个功能的硬性条件,接下来会详细介绍。
These are the mandatory prerequisites for using this feature. Detailed instructions follow.
## 配置步骤
## Configuration steps
### 第一步:开启通讯录功能
### Step 1: Enable the contacts feature
1. 确认你的智控台版本是`0.9.4`或以上版本。
2. 登录智控台后台
3. 进入 **系统功能配置**
4. 在左侧功能列表中勾选 **通讯录**
5. 点击 **保存配置** 确认
1. Ensure your Console version is `0.9.4` or higher.
2. Log in to the Console backend
3. Go to **System Function Config**
4. Check the **Contacts** option in the left-side feature list
5. Click **Save Configuration** to confirm
### 第二步:配置设备间呼叫权限
### Step 2: Configure inter-device call permissions
1. 在智控台顶部菜单点击 **通讯录**
2. 在左侧智能体下,设备列表中选择你的设备A(支持按 MAC地址 或 备注名 搜索)
3. 在右侧详情面板中,找到目标设备B的称呼设置,例如 **"小王"**
4. 勾选设备B的 **呼叫权限** 复选框
5. 点击 **保存**
1. Click **Contacts** in the top menu of the Console
2. Under the Agent list on the left, select Device A from the device list (search by MAC address or remark name).
3. In the right-side details panel, find the nickname setting for target device B, e.g., **"Xiao Wang"**
4. Check the **Call Permission** checkbox for Device B
5. Click **Save**
**双向授权说明:** 如需设备A和设备B互相通信,必须在两侧智控台分别配置对方权限。例如:
**Bidirectional Authorization Note:** To enable communication between Device A and Device B, configure mutual permissions in the Console on both sides. For example:
- 在设备A的配置中勾选设备B → 设备A可与设备B通信
- 在设备B的配置中勾选设备A → 设备B可与设备A通信
- Check device B in device A's config → Device A can communicate with device B
- Check device A in device B's config → Device B can communicate with device A
### 第三步:在智能体配置添加呼叫工具
### Step 3: Add the call tool in the Agent config
1. 在智控台顶部菜单点击 **智能体管理**
2. 在刚刚配置设备联系人的相关智能体中点击 **编辑角色**
3. 在右侧详情面板中,点击 **编辑功能**
4. 勾选 **设备呼叫设备** 工具
5. 点击 **保存配置** 确认
6. 在外侧再次点击 **保存配置** ,随即重启设备
1. Click **Agent Management** in the top menu of the Console
2. In the Agent associated with the recently configured device contact, click **Edit Role**
3. In the right-side details panel, click **Edit Features**
4. Check the **Device-to-Device Call** tool
5. Click **Save Configuration** to confirm
6. Click **Save Config** again on the outer layer, then restart the device
### 第四步:固件端添加远程唤醒工具
### Step 4: Add the remote wake-up tool on the firmware side
1. 在[xiaozhi-esp32](https://github.com/78/xiaozhi-esp32) 代码的基础上增加远程唤醒工具MCP,版本支持为2.1.0至2.2.6(2026年5月29日的版本)
2. 在application.h文件中添加远程唤醒函数声明
1. Add the remote wake-up tool MCP to the [xiaozhi-esp32](https://github.com/78/xiaozhi-esp32) codebase. Supported versions are 2.1.0 to 2.2.6 (version from May 29, 2026).
2. Add the remote wake-up function declaration in application.h
```cpp
void RemoteWakeup(const std::string& reason);
```
3. 在application.cc文件中添加远程唤醒函数
3. Add the remote wake-up function in application.cc
```cpp
void Application::RemoteWakeup(const std::string& reason){
if (!protocol_) {
@ -96,7 +96,7 @@
}
}
```
4. 在mcp_server.cc文件中添加远程唤醒工具
4. Add the remote wake-up tool in mcp_server.cc
```cpp
AddUserOnlyTool("self.remote_wakeup", "Remote wakeup function with configurable parameters",
PropertyList({
@ -109,40 +109,40 @@
app.RemoteWakeup(reason);
return true;
```
5. 按照 [固件编译烧录指南](firmware-build.md) 完成固件烧录
6. 无论你的设备是单麦还是双麦,请在编译环节,勾选开启AEC功能!
7. 无论你的设备是单麦还是双麦,请在编译环节,勾选开启AEC功能!
8. 无论你的设备是单麦还是双麦,请在编译环节,勾选开启AEC功能!
5. Complete firmware flashing according to the [Firmware Compilation and Flashing Guide](firmware-build.md)
6. Regardless of whether your device has a single or dual microphone, enable the AEC feature during compilation!
7. Regardless of whether your device has a single or dual microphone, enable the AEC feature during compilation!
8. Regardless of whether your device has a single or dual microphone, enable the AEC feature during compilation!
### 第五步:配置MQTT网关服务
### Step 5: Configure the MQTT gateway service
1. 部署MQTT网关服务,参考 [MQTT网关集成文档](mqtt-gateway-integration.md)
2. 如果已经部署请确认代码的版本是2026年5月27日的版本
1. Deploy the MQTT Gateway Service. Refer to [MQTT Gateway Integration Documentation](mqtt-gateway-integration.md)
2. If already deployed, confirm the code version is from May 27, 2026
## 呼叫流程说明
## Call flow description
准备两个设备,在智控台上面配置好通讯权限和在智能体中添加呼叫工具之后,在其中一个小智对话那里对他说:”呼叫XXX“,观察设备B是否响应。
Prepare two devices. After configuring communication permissions in the Console and adding the call tool to the Agent, say "Call XXX" to one Xiaozhi device and observe if Device B responds.
## 常见问题
## FAQ
### Q: 设备B没有响应呼叫?
### Q: Device B does not respond to the call?
- 检查设备B是否在线(智控台设备状态)
- 确认设备B的固件已正确集成远程唤醒工具
- 检查MQTT网关连接是否正常
- 验证双向权限配置是否完整
- Check if Device B is online (Console device status)
- Ensure Device B's firmware correctly integrates the remote wake-up tool
- Check if the MQTT gateway connection is normal
- Verify if the bidirectional permission config is complete
### Q: 提示"无呼叫权限"?
### Q: Prompt shows "No call permission"?
- 在智控台确认设备A已勾选设备B的呼叫权限
- 确认配置已保存(非仅修改未保存)
- Verify in the Console that Device A has granted call permissions to Device B
- Ensure the configuration is saved (not just modified)
### Q: 如何确认通讯录功能已开启?
### Q: How to confirm the contacts feature is enabled?
- 智控台顶部菜单如显示"通讯录"入口,则表示已开启
- If the "Contacts" entry appears in the top menu of the Console, the feature is enabled
### Q: 我叫他呼叫"张山",但是他老是识别成"张三",怎么办?
- 可以查阅你使用的asr服务的文档,确认是否支持热词识别。
- 如果你用的是`FunASRServer`,可以在容器里的`热词文件`里添加"张山",然后重启容器。
- 如果你用的是`火山引擎`的服务,可以在`火山引擎的控制台`里添加`热词文件`,然后回到智控台的`模型配置页面`,把`热词文件名称`配置在`火山引擎的tts`上去。
### Q: I ask it to call "Zhang Shan", but it always recognizes it as "Zhang San". What should I do?
- Check the documentation for your ASR service to confirm if hotword recognition is supported.
- If you use `FunASRServer`, add "Zhang Shan" to the `hotword file` in the container, then restart the container.
- If you use `Volcano Engine` services, add a `hotword file` in the `Volcano Engine Console`, then go to the `Model Configuration page` in the Console and configure the `hotword file name` for `Volcano Engine TTS`.

View file

@ -1,33 +1,33 @@
# 数字人digital-human启动方法
# Digital human startup method
## 概述
## Overview
测试页面集成了基于 **Sherpa-ONNX** 的高精度语音唤醒功能,支持自定义唤醒词和实时检测。使用轻量级关键词检测模型,提供毫秒级响应速度。
The test page integrates high-precision voice wake-up based on **Sherpa-ONNX**, supporting custom wake words and real-time detection. It uses a lightweight keyword spotting model for millisecond-level response times.
## 唤醒词模型
## Wake word model
### 模型下载(必需)
### Model download (required)
**重要说明**: 项目不包含模型文件,需要提前下载配置。
**Important note**: The project does not include model files; download and configure them in advance.
### 官方模型下载地址
### Official model download URL
- **官方模型列表**: <https://csukuangfj.github.io/sherpa/onnx/kws/pretrained_models/index.html>
- **推荐模型**: `sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01`
- **Official model list**: <https://csukuangfj.github.io/sherpa/onnx/kws/pretrained_models/index.html>
- **Recommended model**: `sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01`
### 下载和配置步骤
### Download and configuration steps
#### 1. 下载模型包
#### 1. Download model package
```bash
# 方法1:直接下载(推荐)
# Method 1: Direct download (recommended)
cd main/digital-human/wakeword_runtime/
wget https://github.com/k2-fsa/sherpa-onnx/releases/download/kws-models/sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01.tar.bz2
# 解压
# Unzip
tar xvf sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01.tar.bz2
# 方法2:使用ModelScope
# Method 2: Use ModelScope
pip install modelscope
python -c "
from modelscope import snapshot_download
@ -35,112 +35,112 @@ snapshot_download('pkufool/sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01
"
```
#### 2. 配置模型文件
#### 2. Configure model files
模型包下载后包含以下文件:
Model package contains the following files after download:
```
sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01/
├── encoder-epoch-12-avg-2-chunk-16-left-64.int8.onnx # 速度优先
├── encoder-epoch-12-avg-2-chunk-16-left-64.int8.onnx # Speed Priority
├── encoder-epoch-12-avg-2-chunk-16-left-64.onnx
├── encoder-epoch-99-avg-1-chunk-16-left-64.int8.onnx # 速度优先
├── encoder-epoch-99-avg-1-chunk-16-left-64.onnx # 精度优先
├── encoder-epoch-99-avg-1-chunk-16-left-64.int8.onnx # Speed Priority
├── encoder-epoch-99-avg-1-chunk-16-left-64.onnx # Accuracy priority
├── decoder-epoch-12-avg-2-chunk-16-left-64.onnx
├── decoder-epoch-99-avg-1-chunk-16-left-64.onnx # 精度优先
├── joiner-epoch-12-avg-2-chunk-16-left-64.int8.onnx # 速度优先
├── decoder-epoch-99-avg-1-chunk-16-left-64.onnx # Accuracy priority
├── joiner-epoch-12-avg-2-chunk-16-left-64.int8.onnx # Speed Priority
├── joiner-epoch-12-avg-2-chunk-16-left-64.onnx
├── joiner-epoch-99-avg-1-chunk-16-left-64.int8.onnx # 速度优先
├── joiner-epoch-99-avg-1-chunk-16-left-64.onnx # 精度优先
├── tokens.txt # Token映射表(必需)
├── keywords_raw.txt # 模型包里可能附带(可选,runtime 不依赖)
├── keywords.txt # 现成的
├── test_wavs/ # 测试音频(可选)
├── configuration.json # 模型元信息(可选)
└── README.md # 说明文档(可选)
├── joiner-epoch-99-avg-1-chunk-16-left-64.int8.onnx # Speed Priority
├── joiner-epoch-99-avg-1-chunk-16-left-64.onnx # Accuracy priority
├── tokens.txt # Token mapping table (required)
├── keywords_raw.txt # Model package may include optional assets (runtime does not depend on them)
├── keywords.txt # Ready-made
├── test_wavs/ # Test audio (optional)
├── configuration.json # Model metadata (optional)
└── README.md # Documentation (optional)
```
#### 3. 选择配置方案
#### 3. Select config scheme
**方案一:精度优先(推荐)**
**Option 1: Prioritize accuracy (recommended)**
```bash
cd sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01
# 创建模型目录
# Create model directory
mkdir -p ../models
# 复制精度优先的epoch-99 fp32三件套
# Copy the accuracy-priority epoch-99 fp32 triplet
cp encoder-epoch-99-avg-1-chunk-16-left-64.onnx ../models/encoder.onnx
cp decoder-epoch-99-avg-1-chunk-16-left-64.onnx ../models/decoder.onnx
cp joiner-epoch-99-avg-1-chunk-16-left-64.onnx ../models/joiner.onnx
# 复制配套文件
# Copy companion files
cp tokens.txt ../models/tokens.txt
# keywords_raw.txt 如果模型包里附带,可自行保留;runtime 不依赖它
# keywords_raw.txt can be kept if included in the model package; runtime does not depend on it
```
**方案二:速度优先**
**Option 2: Speed priority**
```bash
cd sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01
# 创建模型目录
# Create model directory
mkdir -p ../models
# 复制速度优先的epoch-99 int8三件套
# Copy the speed-priority epoch-99 int8 triplet
cp encoder-epoch-99-avg-1-chunk-16-left-64.int8.onnx ../models/encoder.onnx
cp decoder-epoch-99-avg-1-chunk-16-left-64.onnx ../models/decoder.onnx
cp joiner-epoch-99-avg-1-chunk-16-left-64.int8.onnx ../models/joiner.onnx
# 复制配套文件
# Copy companion files
cp tokens.txt ../models/tokens.txt
```
**注意事项**:
**Notes:
- **不要混用 fp32 与 int8**:三个模型文件必须保持一致的精度
- **优先选择 epoch-99**:比 epoch-12 训练更充分,精度更高
- **必需文件**:`encoder.onnx` + `decoder.onnx` + `joiner.onnx` + `tokens.txt` + `keywords.txt`
- **Do not mix fp32 and int8**: all three model files must use the same precision
- **Prefer epoch-99**: trained more thoroughly than epoch-12, with higher accuracy
- **Required Files**: `encoder.onnx` + `decoder.onnx` + `joiner.onnx` + `tokens.txt` + `keywords.txt`
### 最终模型文件结构
### Final model file structure
配置完成后,模型文件应放在 `wakeword_runtime/models/` 目录下,完整路径为 `main/digital-human/wakeword_runtime/models/`:
After configuration, model files should be placed in the `wakeword_runtime/models/` directory. The full path is `main/digital-human/wakeword_runtime/models/`:
```
wakeword_runtime/models/
├── encoder.onnx # 编码器模型(重命名后)
├── decoder.onnx # 解码器模型(重命名后)
├── joiner.onnx # 连接器模型(重命名后)
├── tokens.txt # 拼音 Token 映射表(228行版本)
├── keywords.txt # 关键词配置文件(首次启动自动生成)
└── keywords_raw.txt # 可选,runtime 不依赖
├── encoder.onnx # Encoder model (after renaming)
├── decoder.onnx # Decoder model (after renaming)
├── joiner.onnx # Connector model (after rename)
├── tokens.txt # Pinyin token mapping table (228-line version)
├── keywords.txt # Keyword config file (auto-generated on first launch)
└── keywords_raw.txt # Optional, runtime independent
```
## 启动方式
## Startup method
在 `main/digital-human` 目录执行:
Execute in `main/digital-human` directory:
```bash
pip install -r wakeword_runtime/requirements.txt
python start.py
```
启动后默认地址:
Default address after startup:
- 页面地址:`http://127.0.0.1:8006/index.html`
- 事件桥地址:`ws://127.0.0.1:8006/wakeword-ws`
- 健康检查:`http://127.0.0.1:8006/health`
- Page address: `http://127.0.0.1:8006/index.html`
- Event bridge address: `ws://127.0.0.1:8006/wakeword-ws`
- Health check: `http://127.0.0.1:8006/health`
停止方式:
Stop Method:
- 在运行终端按 `Ctrl+C`
- 会同时停止静态页面服务、事件桥和唤醒词检测流程
- Press `Ctrl+C` in the running terminal
- Simultaneously stops static page service, event bridge, and wake word detection process
## 配置文件说明
## Config file description
配置文件位于 [main/digital-human/wakeword_runtime/config.json](../main/digital-human/wakeword_runtime/config.json)。
The config file is located at [main/digital-human/wakeword_runtime/config.json](../main/digital-human/wakeword_runtime/config.json).
当前主要配置项:
Current main configuration items:
```json
{
@ -170,51 +170,51 @@ python start.py
}
```
各字段含义:
Field descriptions:
| 参数 | 说明 |
| Parameter | Description |
| --- | --- |
| `wakeword.enabled` | 是否启用本地唤醒词检测 |
| `model_dir` | 模型和词表所在目录 |
| `audio.input_device` | 麦克风输入设备,默认使用系统默认设备 |
| `audio.sample_rate` | 采样率,默认 `16000` |
| `audio.channels` | 声道数,默认 `1` |
| `detector.num_threads` | 检测器线程数 |
| `detector.provider` | 推理 provider,当前通常为 `cpu` |
| `detector.max_active_paths` | 搜索路径数 |
| `detector.keywords_score` | 关键词增强分数 |
| `detector.keywords_threshold` | 检测阈值 |
| `detector.num_trailing_blanks` | 尾随空白数量 |
| `detector.cooldown_seconds` | 连续触发冷却时间 |
| `logging.level` | 日志等级 |
| `logging.dir` | 日志目录 |
| `logging.file` | 日志文件名 |
| `wakeword.enabled` | Enable local wake word detection |
| `model_dir` | Directory containing the model and vocabulary |
| `audio.input_device` | Microphone input device, defaults to system default device |
| `audio.sample_rate` | Sample rate, default `16000` |
| `audio.channels` | Number of channels, default `1` |
| `detector.num_threads` | Detector thread count |
| `detector.provider` | Inference provider, currently usually `cpu` |
| `detector.max_active_paths` | Search path count |
| `detector.keywords_score` | Keyword enhancement score |
| `detector.keywords_threshold` | Detection threshold |
| `detector.num_trailing_blanks` | Trailing whitespace count |
| `detector.cooldown_seconds` | Continuous trigger cooldown time |
| `logging.level` | Log level |
| `logging.dir` | Log directory |
| `logging.file` | Log file name |
## 推荐使用流程
## Recommended workflow
### 首次使用
### First Use
1. 准备 `models/` 目录下的模型文件和 `tokens.txt`
2. 确认 `models/keywords.txt` 存在
3. 在 `digital-human` 目录运行 `python start.py`
4. 浏览器打开 `http://127.0.0.1:8006/index.html`
5. 进入设置页检查“唤醒词”配置
1. Prepare model files and `tokens.txt` in the `models/` directory
2. Verify `models/keywords.txt` exists
3. Run `python start.py` in the `digital-human` directory
4. Open `http://127.0.0.1:8006/index.html` in the browser
5. Go to the settings page and check the "wake word" config
### 修改唤醒词
### Modify Wake Word
1. 打开数字人页面设置
2. 切到“唤醒词”页签
3. 修改启用状态或唤醒词列表
4. 点击“应用唤醒词”
5. 根据提示决定是否立即重启
1. Open digital human page settings
2. Switch to "Wake Word" tab
3. Modify enabled status or wake word list
4. Click " to apply the wake word"
5. Decide whether to restart immediately based on prompt
### 禁用唤醒词
### Disable wake word
1. 将“启用本地唤醒词”改成禁用
2. 点击“应用唤醒词”
3. 建议立即重启一次
1. Change "Enable local wake word" to disabled
2. Click " to apply the wake word"
3. Recommend immediate restart
禁用后:
When disabled:
- 页面与事件桥仍然可用
- 唤醒词检测不会继续运行
- Page and event bridge remain available
- Wake word detection will not continue running

View file

@ -1,74 +1,74 @@
# 联网搜索插件使用指南
# Web search plugin usage guide
## 功能简介
## Feature description
联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持三个搜索源:秘塔(Metaso)、Tavily和Serply,用户可根据需要选择其中一个。
The web search plugin `web_search` supports real-time web search during conversations and returns results. The plugin supports three search sources: Metaso, Tavily, and Serply. Users can choose one as needed.
## API Key申请指南
## API Key Application Guide
目前我们适配了`秘塔搜索`、`Tavily搜索`和`Serply搜索`。
- Tavily搜索:每个月1000次免费额度。
- 秘塔搜索:拥有较为优质的国内数据源。
- Serply搜索:返回谷歌搜索结果,注册赠送2500次免费额度,额度用完后需要付费。
We currently support `Mita Search `,`Tavily Search` and `Serply Search`.
- Tavily Search: 1000 free requests per month.
- Metaso Search: Offers high-quality domestic data sources.
- Serply Search: Returns Google search results. Registration grants 2500 free credits; payment is required after credits are exhausted.
## API Key申请指南
## API Key Application Guide
### 方式一:使用秘塔搜索
### Method 1: Use Metaso Search
- 访问 [秘塔搜索API](https://metaso.cn/search-api/api-keys),注册并登录账号
- 在API密钥管理页面,点击"创建新的Key"
- 复制生成的API Key(以 `mk-` 为前缀),这是配置所需的关键信息
- Visit [Metaso Search API](https://metaso.cn/search-api/api-keys), register and log in
- On the API key management page, click " to create a new Key"
- Copy the generated API Key (prefixed with `mk-`), which is essential for configuration
### 方式二:使用Tavily搜索
### Method 2: Use Tavily search
- 访问 [Tavily控制台](https://app.tavily.com/home),注册并登录账号
- 在控制台中创建API Key
- 复制生成的API Key(以 `tvly-` 为前缀),这是配置所需的关键信息
- Visit [Tavily Console ](https://app.tavily.com/home), register and log in
- Create an API Key in the Console
- Copy the generated API Key (prefixed with `tvly-`); this is critical for configuration
### 方式三:使用Serply搜索
### Method 3: Use Serply search
- 访问 [Serply](https://serply.io),注册并登录账号
- 在控制台中创建API Key
- 复制生成的API Key,这是配置所需的关键信息
- 接口说明见 [Serply文档](https://serply.io/docs)
- Visit [Serply](https://serply.io), register and log in to your account
- Create an API Key in the Console
- Copy the generated API Key; this is critical information for configuration
- See [Serply documentation ](https://serply.io/docs) for interface details
## 配置方式
## Configuration Method
### 方式1. 使用智控台部署(推荐)
### Method 1. Deploy via Console (recommended)
- 登录智控台
- 进入"配置角色"页面,选择要配置的智能体
- 点击"编辑功能"按钮,在右侧参数配置区域找到"联网搜索"插件
- 勾选"联网搜索"
- 填入搜索源(`metaso`、`tavily`或`serply`),并将对应的`API Key`填入配置项
- 保存配置,再保存智能体配置
- Log in to Console
- Go to the "Configure Role" page and select the Agent to configure
- Click the "Edit Function" button, find the "Web Search" plugin in the parameter configuration area on the right
- Check " for online search"
- Fill in the search source (`metaso`, `tavily`, or `serply`) and enter the corresponding `API Key` in the config
- Save config, then save agent config
### 方式2. 单模块xiaozhi-server部署
### Method 2. Single-module xiaozhi-server deployment
在 `data/.config.yaml` 中配置:
Configure in `data/.config.yaml`:
- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily` 或 `serply`
- 将申请到的API Key填入 `api_key`
- Fill search source into `provider`, valid values are `metaso`, `tavily` or `serply`
- Enter the obtained API Key into `api_key`
```yaml
plugins:
web_search:
provider: "metaso"
api_key: "你的API Key"
api_key: "your API Key"
```
如需自定义返回结果数量和工具描述,可额外配置 `max_results` 和 `description`:
To customize the number of returned results and tool descriptions, additionally configure `max_results` and `description`:
```yaml
plugins:
web_search:
provider: "metaso"
description: "联网搜索工具。当用户明确需要联网搜索问题时使用此工具。"
description: " web search tool. Use this tool when the user explicitly needs to search the web."
max_results: 5
api_key: "你的API Key"
api_key: "your API Key"
```
同时在 `functions` 列表中确保已启用 `web_search`:
Also ensure `web_search` is enabled in the `functions` list:
```yaml
plugins:
@ -76,4 +76,4 @@ plugins:
- web_search
```
配置完成后重启服务即可生效。
Restart service after configuration to apply changes.

View file

@ -1,34 +1,34 @@
<!DOCTYPE html>
<html lang="zh-CN">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>小智数字人页面</title>
<title> Xiaozhi Digital Human Page </title>
<link rel="stylesheet" href="css/index.css?v=0206">
<script>
// 检测是否使用file://协议打开
// Detect if opened via file:// protocol
if (window.location.protocol === 'file:') {
document.addEventListener('DOMContentLoaded', function () {
// 创建背景模糊遮罩
// Create background blur mask
const overlayDiv = document.createElement('div');
overlayDiv.className = 'file-protocol-overlay';
document.body.appendChild(overlayDiv);
// 创建警告框
// Create warning box
const warningDiv = document.createElement('div');
warningDiv.id = 'fileProtocolWarning';
warningDiv.innerHTML = `
<h2>⚠️ 警告:请使用HTTP服务器打开此页面</h2>
<p>您当前使用的是本地文件方式打开页面(file://协议),这可能导致页面功能异常。</p>
<p>您可以使用nginx映射启动小智数字人页面,也可以请按照以下步骤启动测试运行时:</p>
<h2>⚠️ Warning: Open this page using an HTTP server </h2>
<p>You are currently opening the page via local file (file:// protocol), which may cause functional issues.</p>
<p>You can launch the XiaoZhi digital human page via nginx mapping, or follow these steps to start the test runtime:</p>
<ol>
<li>打开命令行终端</li>
<li>命令行进入到 digital-human 目录</li>
<li>执行以下命令启动小智数字人页面运行时:</li>
<li>Open command line terminal</li>
<li>Use the command line to enter the digital-human directory</li>
<li>Run the following command to start the XiaoZhi digital human page runtime:</li>
</ol>
<pre>python start.py</pre>
<p>然后在浏览器中访问:<strong>http://localhost:8006/index.html</strong></p>
<p>Then access in the browser: <strong>http://localhost:8006/index.html</strong></p>
`;
document.body.appendChild(warningDiv);
});
@ -37,20 +37,20 @@
</head>
<body>
<!-- 背景容器 -->
<!-- Background container -->
<div class="background-container" id="backgroundContainer">
<div class="background-overlay"></div>
</div>
<!-- 主容器 -->
<!-- Main container -->
<div class="container">
<!-- 摄像头显示区域(可拖动) -->
<!-- Camera display area (draggable) -->
<div class="camera-container" id="cameraContainer">
<video id="cameraVideo" autoplay playsinline muted></video>
<div class="camera-switch-mask" id="cameraSwitchMask">
<div class="camera-switch-container">
<!-- 摄像头切换按钮 -->
<!-- Camera switch button -->
<div class="camera-switch" id="cameraSwitch">
<svg class="btn-icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7319" width="32" height="32"><path d="M722.1 530.3c0-44.9-13.8-86.5-37.2-120.9-0.3-0.6-0.6-1.2-0.9-1.7-2.9-4.2-6.1-8.1-9.2-12-0.4-0.5-0.7-1-1.1-1.5-21.4-26.3-48.3-46.7-78.7-59.9-0.8-0.4-1.7-0.8-2.5-1.2-4.9-2-9.8-3.8-14.9-5.5-1.8-0.6-3.6-1.3-5.4-1.8-4.4-1.3-8.8-2.4-13.3-3.5-2.5-0.6-4.9-1.2-7.4-1.7-1.2-0.2-2.4-0.6-3.6-0.8-3.3-0.6-6.7-0.8-10-1.3-2.3-0.3-4.6-0.7-6.9-0.9-5.6-0.5-11.2-0.8-16.7-0.9-1 0-2-0.1-3-0.1-0.2 0-0.3 0.1-0.5 0.1-42.8 0-84.6 13.1-120.4 38.6-11.5 8.1-14.2 24.1-6.2 35.7 8 11.6 23.8 14.4 35.2 6.3 27.7-19.7 60-29.6 93.1-29.3 4.8 0 9.5 0.3 14.1 0.7 1.4 0.2 2.8 0.4 4.3 0.5 3.8 0.5 7.6 1 11.3 1.8 1.6 0.3 3.3 0.8 4.9 1.1 3.7 0.8 7.3 1.7 10.9 2.8 1.1 0.4 2.2 0.8 3.4 1.2 4.1 1.3 8.1 2.8 12 4.5 0.4 0.2 0.8 0.4 1.2 0.5 23.6 10.3 44.3 26.1 60.4 45.9 0.1 0.1 0.2 0.3 0.3 0.4 22.7 28 36.4 63.9 36.4 102.9h-42.2L697 632.9l67.5-102.6h-42.4z m-119 133c-27.9 19.8-60.5 29.7-93.9 29.3-4.4-0.1-8.8-0.3-13.1-0.7-1.8-0.2-3.5-0.5-5.3-0.7-3.4-0.5-6.8-0.9-10.1-1.6-2-0.4-4-0.9-6.1-1.4-3.3-0.8-6.5-1.5-9.7-2.5-1.5-0.5-3-1-4.6-1.5-3.7-1.2-7.3-2.5-10.8-4-0.8-0.3-1.6-0.7-2.4-1.1-4.1-1.9-8.2-3.8-12.2-6l-0.6-0.3c-13.4-7.5-25.7-16.8-36.4-27.7-0.2-0.2-0.3-0.4-0.5-0.6-3.3-3.4-6.5-6.9-9.5-10.7-0.6-0.8-1.3-1.6-1.9-2.5-21.9-27.8-35.1-63-35.1-101.2h42.2l-67.5-102.6-67.5 102.6h42.2c0 45 13.9 86.7 37.3 121.1 0.3 0.5 0.5 1 0.8 1.5 2.4 3.5 5.1 6.8 7.7 10.1 1 1.3 1.9 2.6 2.9 3.8 3.9 4.7 7.9 9.2 12.1 13.5 0.4 0.4 0.8 0.9 1.2 1.3 14.1 14.3 30.1 26.4 47.4 36 0.5 0.3 0.9 0.6 1.4 0.8 5 2.7 10.1 5.2 15.3 7.5l3.9 1.8c4.4 1.9 9 3.5 13.6 5.1 2.2 0.7 4.4 1.5 6.6 2.2 4 1.2 8.1 2.2 12.3 3.2 2.8 0.7 5.5 1.4 8.3 1.9 1.2 0.3 2.3 0.6 3.4 0.8 3.9 0.7 7.8 1.1 11.8 1.6l4.2 0.6c7 0.7 14.1 1.2 21.1 1.2 42.9 0 84.7-13.3 120.6-38.8 11.4-8.2 14.2-24.1 6.2-35.8-8-11.5-23.8-14.3-35.3-6.2z m271.3-421.6H763c-26.5 0-82.9-119.7-112.5-119.7H370.6c-29.6 0-85.9 119.7-112.4 119.7H147.5c-46.3 0-83.9 40.2-83.9 89.7v478.8c0 49.6 37.6 89.8 83.9 89.8h726.9c46.3 0 83.9-40.1 83.9-89.8V331.4c0-49.5-37.6-89.7-83.9-89.7z m28 538.6c0 33.1-25 59.8-55.9 59.8h-671c-30.9 0-55.9-26.8-55.9-59.8V361.4c0-33 25-59.8 55.9-59.8h111.2c25.8 0 82-119.7 111.6-119.7h223.2c29.5 0 85.6 119.7 111.5 119.7h113.5c30.9 0 55.9 26.8 55.9 59.8v418.9z" p-id="7320" fill="#ffffff"></path></svg>
</div>
@ -58,138 +58,138 @@
</div>
</div>
<!-- 连接状态指示器 - 页面顶部中部 -->
<!-- Connection status indicator - top center of page -->
<div class="connection-status-top">
<div class="status-indicator">
<span class="status-dot status-disconnected"></span>
<span id="connectionStatus">离线</span>
<span id="connectionStatus">Offline</span>
</div>
</div>
<!-- 模型加载提示 -->
<!-- Model loading prompt -->
<div class="model-container">
<div class="model-loading" id="modelLoading">
<div class="loading-char-float">
<div class="main-char">
<span>模</span><span>型</span><span>加</span><span>载</span><span>中</span><span>✨</span>
<span>Model</span><span>loading</span><span>ing</span><span>...</span><span>✨</span>
</div>
<div class="shadow-char">模型加载中✨</div>
<div class="shadow-char">Loading model✨</div>
</div>
</div>
</div>
<!-- Live2D Canvas 容器 -->
<!-- Live2D Canvas container -->
<canvas id="live2d-stage"></canvas>
<!-- 聊天消息流(弹幕样式) -->
<!-- Chat message stream (danmaku style) -->
<div class="chat-container">
<div class="chat-stream" id="chatStream">
<!-- 聊天消息将动态插入这里 -->
<!-- Chat messages will be dynamically inserted here -->
</div>
<div class="chat-ipt" id="chatIpt">
<input type="text" id="messageInput" autocomplete="off" placeholder="输入消息,按Enter发送">
<input type="text" id="messageInput" autocomplete="off" placeholder="Enter message, press Enter to send">
</div>
</div>
<!-- 底部控制栏 -->
<!-- Bottom control bar -->
<div class="control-bar">
<button class="control-btn" id="settingsBtn" title="设置">
<button class="control-btn" id="settingsBtn" title="Settings">
<svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
<path
d="M12 15.5A3.5 3.5 0 0 1 8.5 12A3.5 3.5 0 0 1 12 8.5A3.5 3.5 0 0 1 15.5 12A3.5 3.5 0 0 1 12 15.5M19.43 12.97C19.47 12.65 19.5 12.33 19.5 12C19.5 11.67 19.47 11.34 19.43 11L21.54 9.37C21.73 9.22 21.78 8.95 21.66 8.73L19.66 5.27C19.54 5.05 19.27 4.96 19.05 5.05L16.56 6.05C16.04 5.66 15.5 5.32 14.87 5.07L14.5 2.42C14.46 2.18 14.25 2 14 2H10C9.75 2 9.54 2.18 9.5 2.42L9.13 5.07C8.5 5.32 7.96 5.66 7.44 6.05L4.95 5.05C4.73 4.96 4.46 5.05 4.34 5.27L2.34 8.73C2.22 8.95 2.27 9.22 2.46 9.37L4.57 11C4.53 11.34 4.5 11.67 4.5 12C4.5 12.33 4.53 12.65 4.57 12.97L2.46 14.63C2.27 14.78 2.22 15.05 2.34 15.27L4.34 18.73C4.46 18.95 4.73 19.03 4.95 18.95L7.44 17.94C7.96 18.34 8.5 18.68 9.13 18.93L9.5 21.58C9.54 21.82 9.75 22 10 22H14C14.25 22 14.46 21.82 14.5 21.58L14.87 18.93C15.5 18.68 16.04 18.34 16.56 17.94L19.05 18.95C19.27 19.03 19.54 18.95 19.66 18.73L21.66 15.27C21.78 15.05 21.73 14.78 21.54 14.63L19.43 12.97Z" />
</svg>
<span class="btn-text">设置</span>
<span class="btn-text">Settings</span>
</button>
<button class="control-btn" id="cameraBtn" title="请先连接服务器" disabled>
<button class="control-btn" id="cameraBtn" title="Please connect to the server first" disabled>
<svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
<path
d="M17,10.5V7A1,1 0 0,0 16,6H4A1,1 0 0,0 3,7V17A1,1 0 0,0 4,18H16A1,1 0 0,0 17,17V13.5L21,17.5V6.5L17,10.5Z" />
</svg>
<span class="btn-text">摄像头</span>
<span class="btn-text">Camera</span>
</button>
<button class="control-btn dial-btn" id="dialBtn" title="拨号">
<button class="control-btn dial-btn" id="dialBtn" title="Dial">
<svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
<path
d="M6.62,10.79C8.06,13.62 10.38,15.94 13.21,17.38L15.41,15.18C15.69,14.9 16.08,14.82 16.43,14.93C17.55,15.3 18.75,15.5 20,15.5A1,1 0 0,1 21,16.5V20A1,1 0 0,1 20,21A17,17 0 0,1 3,4A1,1 0 0,1 4,3H7.5A1,1 0 0,1 8.5,4C8.5,5.25 8.7,6.45 9.07,7.57C9.18,7.92 9.1,8.31 8.82,8.59L6.62,10.79Z" />
</svg>
<span class="btn-text">拨号</span>
<span class="btn-text">Dial</span>
</button>
<button class="control-btn" id="recordBtn" title="开始录音" disabled>
<button class="control-btn" id="recordBtn" title="Start recording" disabled>
<svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
<path
d="M12,2A3,3 0 0,1 15,5V11A3,3 0 0,1 12,14A3,3 0 0,1 9,11V5A3,3 0 0,1 12,2M19,11C19,14.53 16.39,17.44 13,17.93V21H11V17.93C7.61,17.44 5,14.53 5,11H7A5,5 0 0,0 12,16A5,5 0 0,0 17,11H19Z" />
</svg>
<span class="btn-text">录音</span>
<span class="btn-text">Record</span>
</button>
</div>
</div>
<!-- 设置弹窗 -->
<!-- Settings Modal -->
<div class="modal" id="settingsModal">
<div class="modal-content settings-modal">
<div class="modal-header">
<h2>设置</h2>
<h2>Settings</h2>
<button class="close-btn" id="closeSettingsBtn">&times;</button>
</div>
<div class="modal-body">
<div class="settings-tabs">
<button class="tab-btn active" data-tab="device">设备配置</button>
<button class="tab-btn" data-tab="wakeword">唤醒词</button>
<button class="tab-btn" data-tab="mcp">MCP工具</button>
<button class="tab-btn" data-tab="other">数字人皮肤</button>
<button class="tab-btn active" data-tab="device">Device Config </button>
<button class="tab-btn" data-tab="wakeword">Wake Word</button>
<button class="tab-btn" data-tab="mcp">MCP Tools </button>
<button class="tab-btn" data-tab="other">Digital Human Skin </button>
</div>
<div class="tab-content active" id="deviceTab">
<!-- 设备配置面板 -->
<!-- Device Config Panel -->
<div class="config-panel">
<div class="control-panel">
<div class="config-row">
<div class="config-item">
<label for="deviceMac">设备MAC:</label>
<label for="deviceMac">Device MAC:</label>
<input type="text" id="deviceMac" placeholder="device-id">
</div>
</div>
<div class="config-row">
<div class="config-item">
<label for="clientId">客户端ID:</label>
<label for="clientId">Client ID:</label>
<input type="text" id="clientId" value="web_test_client" placeholder="client-id">
</div>
<div class="config-item">
<label for="deviceName">设备名称:</label>
<input type="text" id="deviceName" value="Web测试设备" maxlength="50"
<label for="deviceName">Device Name:</label>
<input type="text" id="deviceName" value="Web test device" maxlength="50"
placeholder="deviceName">
</div>
</div>
<div class="config-row">
<div class="config-item">
<label for="emojiEnabled">情绪表情:</label>
<label for="emojiEnabled">Emotion Expressions:</label>
<select id="emojiEnabled" class="model-select">
<option value="true">启用</option>
<option value="false" selected>禁用</option>
<option value="true">Enable</option>
<option value="false" selected>Disable </option>
</select>
</div>
</div>
</div>
</div>
<!-- 连接信息面板 -->
<!-- Connection Info Panel -->
<div class="connection-controls">
<div class="input-group">
<label for="otaUrl">OTA服务器地址:</label>
<label for="otaUrl">OTA Server Address:</label>
<input type="text" id="otaUrl" value="http://127.0.0.1:8002/xiaozhi/ota/"
placeholder="OTA服务器地址,如:http://127.0.0.1:8002/xiaozhi/ota/" />
placeholder="OTA server address, e.g., http://127.0.0.1:8002/xiaozhi/ota/" />
</div>
<div class="input-group">
<label for="serverUrl">WebSocket服务器地址:</label>
<label for="serverUrl">WebSocket server address:</label>
<input type="text" id="serverUrl" value="" readonly disabled
placeholder="填写OTA地址后,点击拨号按钮自动连接" />
placeholder="Enter the OTA address, then click the dial button to connect automatically" />
</div>
<div class="input-group">
<label for="visionUrl">视觉分析地址:</label>
<input type="text" id="visionUrl" value="" readonly disabled placeholder="成功建立ws连接后自动获取" />
<label for="visionUrl">Vision analysis URL: </label>
<input type="text" id="visionUrl" value="" readonly disabled placeholder="Automatically fetch after successful WS connection" />
</div>
</div>
</div>
@ -199,45 +199,45 @@
<div class="control-panel">
<div class="config-row">
<div class="config-item">
<label for="wakewordEnabled">启用本地唤醒词:</label>
<label for="wakewordEnabled">Enable local wake word: </label>
<select id="wakewordEnabled" class="model-select">
<option value="true">启用</option>
<option value="false">禁用</option>
<option value="true">Enable</option>
<option value="false">Disabled</option>
</select>
</div>
</div>
<div class="config-row">
<div class="config-item">
<label for="wakewordWsUrl">唤醒词服务地址:</label>
<label for="wakewordWsUrl">Wake word service address: </label>
<input type="text" id="wakewordWsUrl" placeholder="ws://127.0.0.1:8006/wakeword-ws">
</div>
</div>
<div class="config-row">
<div class="config-item">
<label for="wakewordList">唤醒词配置 (一行一个):</label>
<textarea id="wakewordList" placeholder="例如:&#10;小智小智&#10;你好小智"></textarea>
<label for="wakewordList">Wake word config (one per line):</label>
<textarea id="wakewordList" placeholder="Example:&#10;XiaoZhi XiaoZhi&#10;Hello XiaoZhi"></textarea>
</div>
</div>
<div class="modal-actions">
<button type="button" class="btn-primary" id="applyWakewordBtn">应用唤醒词</button>
<button type="button" class="btn-primary" id="applyWakewordBtn">Apply Wake Word</button>
</div>
</div>
</div>
</div>
<div class="tab-content" id="mcpTab">
<!-- MCP 工具管理区域 -->
<!-- MCP Tool Management Area -->
<div class="mcp-tools-container">
<div class="mcp-tools-header">
<h3>MCP 工具管理</h3>
<h3>MCP Tool Management</h3>
</div>
<div class="mcp-tools-panel" id="mcpToolsPanel">
<div class="mcp-tools-list" id="mcpToolsContainer">
<!-- 工具列表将动态插入这里 -->
<!-- Tool list will be dynamically inserted here -->
</div>
<div class="mcp-actions">
<button class="btn-primary" id="addMcpToolBtn">
➕ 添加新工具
➕ Add new tool
</button>
</div>
</div>
@ -249,22 +249,22 @@
<div class="control-panel">
<div class="config-row">
<div class="config-item">
<label>选择模型:</label>
<label> Select model: </label>
<select id="live2dModelSelect" class="model-select">
<option value="hiyori_pro_zh">hiyori (春日)</option>
<option value="natori_pro_zh">natori (名取)</option>
<option value="hiyori_pro_zh">hiyori (Kasuga)</option>
<option value="natori_pro_zh">natori (Natori)</option>
</select>
</div>
</div>
<div class="config-row">
<div class="config-item">
<label></label>
<button class="background-btn" id="backgroundBtn" title="切换背景">
<button class="background-btn" id="backgroundBtn" title="Toggle Background">
<svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
<path
d="M12,18A6,6 0 0,1 6,12C6,11 6.25,10.03 6.7,9.2L5.24,7.74C4.46,8.97 4,10.43 4,12A8,8 0 0,0 12,20V23L16,19L12,15V18M12,4V1L8,5L12,9V6A6,6 0 0,1 18,12C18,13 17.75,13.97 17.3,14.8L18.76,16.26C19.54,15.03 20,13.57 20,12A8,8 0 0,0 12,4Z" />
</svg>
<span class="btn-text">切换背景</span>
<span class="btn-text">Switch Background</span>
</button>
</div>
</div>
@ -275,34 +275,34 @@
</div>
</div>
<!-- MCP 工具编辑模态框 -->
<!-- MCP tool edit modal -->
<div id="mcpToolModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h2 id="mcpModalTitle">添加工具</h2>
<h2 id="mcpModalTitle">Add Tool</h2>
<button class="close-btn" id="closeMcpModalBtn">&times;</button>
</div>
<div class="modal-body">
<div id="mcpErrorContainer"></div>
<form id="mcpToolForm">
<div class="input-group">
<label for="mcpToolName">工具名称 *</label>
<input type="text" id="mcpToolName" placeholder="例如: self.get_device_status" required>
<label for="mcpToolName">Tool Name *</label>
<input type="text" id="mcpToolName" placeholder="e.g., self.get_device_status" required>
</div>
<div class="input-group">
<label for="mcpToolDescription">工具描述 *</label>
<textarea id="mcpToolDescription" placeholder="详细描述工具的功能和使用场景..." required></textarea>
<label for="mcpToolDescription">Tool description *</label>
<textarea id="mcpToolDescription" placeholder="Describe the tool's functionality and use cases..." required></textarea>
</div>
<div class="input-group">
<div class="input-group-header">
<label>输入参数</label>
<label>Input parameters</label>
<button type="button" class="properties-btn-primary" id="addMcpPropertyBtn">
➕ 添加参数
➕ Add parameter
</button>
</div>
<div class="properties-container">
<div class="mcp-empty-state" id="mcpEmptyState">
暂无参数,点击上方按钮添加参数
No parameters. Click the button above to add one.
</div>
<div class="mcp-properties-list" id="mcpPropertiesContainer">
</div>
@ -310,105 +310,105 @@
</div>
<div class="input-group">
<label for="mcpMockResponse">
模拟返回结果 (JSON 格式,可选)
<span style="font-size: 12px; color: #999; font-weight: normal;">- 留空则返回默认成功消息</span>
Mock return result (JSON format, optional)
<span style="font-size: 12px; color: #999; font-weight: normal;">- Leave empty to return default success message</span>
</label>
<textarea id="mcpMockResponse" placeholder='{"success": true, "data": "执行成功"}'></textarea>
<textarea id="mcpMockResponse" placeholder='{"success": true, "data": "Execution successful"}'></textarea>
</div>
<div class="modal-actions">
<button type="button" class="btn-secondary" id="cancelMcpBtn">取消</button>
<button type="submit" class="btn-primary">保存</button>
<button type="button" class="btn-secondary" id="cancelMcpBtn">Cancel</button>
<button type="submit" class="btn-primary">Save </button>
</div>
</form>
</div>
</div>
</div>
<!-- 参数编辑模态框 -->
<!-- Parameter edit modal -->
<div id="mcpPropertyModal" class="modal">
<div class="modal-content property-modal">
<div class="modal-header">
<h2 id="mcpPropertyModalTitle">编辑参数</h2>
<h2 id="mcpPropertyModalTitle">Edit Parameters</h2>
<button class="close-btn" id="closeMcpPropertyModalBtn">&times;</button>
</div>
<div class="modal-body">
<form id="mcpPropertyForm">
<input type="hidden" id="mcpPropertyIndex" value="-1">
<div class="input-group">
<label for="mcpPropertyName">参数名称 *</label>
<input type="text" id="mcpPropertyName" placeholder="例如: param_1" required>
<label for="mcpPropertyName">Parameter name *</label>
<input type="text" id="mcpPropertyName" placeholder="e.g., param_1" required>
</div>
<div class="input-group">
<label for="mcpPropertyType">数据类型 *</label>
<label for="mcpPropertyType">Data type *</label>
<select id="mcpPropertyType" class="model-select" required>
<option value="string">字符串</option>
<option value="integer">整数</option>
<option value="number">数字</option>
<option value="boolean">布尔值</option>
<option value="array">数组</option>
<option value="object">对象</option>
<option value="string">String </option>
<option value="integer">Integer </option>
<option value="number">Number </option>
<option value="boolean">Boolean</option>
<option value="array">Array</option>
<option value="object">Object</option>
</select>
</div>
<div class="input-group" id="mcpPropertyRangeGroup" style="display: none;">
<div class="config-row">
<div class="config-item">
<label for="mcpPropertyMinimum">最小值</label>
<input type="number" id="mcpPropertyMinimum" placeholder="可选">
<label for="mcpPropertyMinimum">Min value </label>
<input type="number" id="mcpPropertyMinimum" placeholder="Optional">
</div>
<div class="config-item">
<label for="mcpPropertyMaximum">最大值</label>
<input type="number" id="mcpPropertyMaximum" placeholder="可选">
<label for="mcpPropertyMaximum">Max value </label>
<input type="number" id="mcpPropertyMaximum" placeholder="Optional">
</div>
</div>
</div>
<div class="input-group">
<label for="mcpPropertyDescription">参数描述</label>
<input type="text" id="mcpPropertyDescription" placeholder="可选">
<label for="mcpPropertyDescription">Parameter description</label>
<input type="text" id="mcpPropertyDescription" placeholder="Optional">
</div>
<div class="input-group">
<label class="mcp-checkbox-label">
<input type="checkbox" id="mcpPropertyRequired">
必填参数
Required parameter
</label>
</div>
<div class="modal-actions">
<button type="button" class="btn-secondary" id="cancelMcpPropertyBtn">取消</button>
<button type="submit" class="btn-primary">保存</button>
<button type="button" class="btn-secondary" id="cancelMcpPropertyBtn">Cancel</button>
<button type="submit" class="btn-primary">Save </button>
</div>
</form>
</div>
</div>
</div>
<!-- 背景加载 -->
<!-- Background loading -->
<script src="js/ui/background-load.js?v=0205"></script>
<!-- PIXI.js 2D渲染引擎 -->
<!-- PIXI.js 2D rendering engine -->
<script src="js/live2d/pixi.js?v=0205"></script>
<!-- Live2D Cubism 4.0 SDK -->
<script src="js/live2d/live2dcubismcore.min.js?v=0205"></script>
<script src="js/live2d/cubism4.min.js?v=0205"></script>
<!-- Live2D 管理器 -->
<!-- Live2D Manager -->
<script src="js/live2d/live2d.js?v=0205"></script>
<!-- Opus解码库 -->
<!-- Opus decoding library -->
<script src="js/utils/libopus.js?v=0205"></script>
<!-- 主应用入口 -->
<!-- Main App Entry -->
<script type="module" src="js/app.js?v=0205"></script>
<!-- 全局错误处理 -->
<!-- Global error handling -->
<script>
// 添加全局错误处理
// Add global error handling
window.addEventListener('error', function (event) {
console.error('全局错误:', event.error);
console.error('Global error:', event.error);
});
// 添加未处理的Promise拒绝处理
// Add handler for unhandled promise rejections
window.addEventListener('unhandledrejection', function (event) {
console.error('未处理的Promise拒绝:', event.reason);
console.error('Unhandled promise rejection:', event.reason);
});
</script>
</body>

View file

@ -1,4 +1,4 @@
// 主应用入口
// Main App Entry
import { checkOpusLoaded, initOpusEncoder } from './core/audio/opus-codec.js?v=0205';
import { getAudioPlayer } from './core/audio/player.js?v=0205';
import { checkMicrophoneAvailability, isHttpNonLocalhost } from './core/audio/recorder.js?v=0205';
@ -7,7 +7,7 @@ import { startWakewordBridgeListener } from './core/network/wakeword-bridge.js?v
import { uiController } from './ui/controller.js?v=0205';
import { log } from './utils/logger.js?v=0205';
// 辅助函数:将Base64数据转换为Blob
// Helper function: Convert Base64 data to Blob
function dataURItoBlob(dataURI) {
const byteString = atob(dataURI.split(',')[1]);
const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
@ -19,7 +19,7 @@ function dataURItoBlob(dataURI) {
return new Blob([ab], { type: mimeString });
}
// 应用类
// Application type
class App {
constructor() {
this.uiController = null;
@ -29,64 +29,64 @@ class App {
this.currentFacingMode = 'user';
}
// 初始化应用
// Initialize application
async init() {
log('正在初始化应用...', 'info');
// 初始化UI控制器
log('Initializing application...', 'info');
// Initialize UI controller
this.uiController = uiController;
this.uiController.init();
// 检查Opus库
// Check Opus library
checkOpusLoaded();
// 初始化Opus编码器
// Initialize Opus encoder
initOpusEncoder();
// 初始化音频播放器
// Initialize audio player
this.audioPlayer = getAudioPlayer();
await this.audioPlayer.start();
// 初始化MCP工具
// Initialize MCP tools
initMcpTools();
// 初始化本地唤醒事件监听
// Initialize local wake event listener
startWakewordBridgeListener();
// 检查麦克风可用性
// Check microphone availability
await this.checkMicrophoneAvailability();
// 检查摄像头可用性
// Check camera availability
this.checkCameraAvailability();
// 初始化Live2D
// Initialize Live2D
await this.initLive2D();
// 初始化摄像头
// Initialize camera
this.initCamera();
// 关闭加载loading
// Close loading indicator
this.setModelLoadingStatus(false);
log('应用初始化完成', 'success');
log('Application initialization complete', 'success');
}
// 初始化Live2D
// Initialize Live2D
async initLive2D() {
try {
// 检查Live2DManager是否已加载
// Check if Live2DManager is loaded
if (typeof window.Live2DManager === 'undefined') {
throw new Error('Live2DManager未加载,请检查脚本引入顺序');
throw new Error('Live2DManager not loaded, check script import order');
}
this.live2dManager = new window.Live2DManager();
await this.live2dManager.initializeLive2D();
// 更新UI状态
// Update UI state
const live2dStatus = document.getElementById('live2dStatus');
if (live2dStatus) {
live2dStatus.textContent = '● 已加载';
live2dStatus.textContent = '● Loaded';
live2dStatus.className = 'status loaded';
}
log('Live2D初始化完成', 'success');
log('Live2D initialization complete', 'success');
} catch (error) {
log(`Live2D初始化失败: ${error.message}`, 'error');
// 更新UI状态
log(`Live2D initialization failed: ${error.message}`, 'error');
// Update UI state
const live2dStatus = document.getElementById('live2dStatus');
if (live2dStatus) {
live2dStatus.textContent = '● 加载失败';
live2dStatus.textContent = '● Load failed';
live2dStatus.className = 'status error';
}
}
}
// 设置model加载状态
// Set model loading status
setModelLoadingStatus(isLoading) {
const modelLoading = document.getElementById('modelLoading');
if (modelLoading) {
@ -95,24 +95,24 @@ class App {
}
/**
* 检查麦克风可用性
* 在应用初始化时调用,检查麦克风是否可用并更新UI状态
* Check microphone availability
* Call during app initialization to check microphone availability and update UI state
*/
async checkMicrophoneAvailability() {
try {
const isAvailable = await checkMicrophoneAvailability();
const isHttp = isHttpNonLocalhost();
// 保存可用性状态到全局变量
// Save availability status to global variable
window.microphoneAvailable = isAvailable;
window.isHttpNonLocalhost = isHttp;
// 更新UI
// Update UI
if (this.uiController) {
this.uiController.updateMicrophoneAvailability(isAvailable, isHttp);
}
log(`麦克风可用性检查完成: ${isAvailable ? '可用' : '不可用'}`, isAvailable ? 'success' : 'warning');
log(`Microphone availability check complete: ${isAvailable ? 'Available' : 'Unavailable'}`, isAvailable ? 'success' : 'warning');
} catch (error) {
log(`检查麦克风可用性失败: ${error.message}`, 'error');
// 默认设置为不可用
log(`Failed to check microphone availability: ${error.message}`, 'error');
// Set default to unavailable
window.microphoneAvailable = false;
window.isHttpNonLocalhost = isHttpNonLocalhost();
if (this.uiController) {
@ -121,13 +121,13 @@ class App {
}
}
// 检查摄像头可用性
// Check camera availability
checkCameraAvailability() {
window.cameraAvailable = true;
log('摄像头可用性检查完成: 默认已绑定验证码', 'success');
log('Camera availability check complete: default verification code bound', 'success');
}
// 初始化摄像头
// Initialize camera
async initCamera() {
const cameraContainer = document.getElementById('cameraContainer');
const cameraVideo = document.getElementById('cameraVideo');
@ -136,7 +136,7 @@ class App {
const dialBtn = document.getElementById('dialBtn');
if (!cameraContainer || !cameraVideo) {
log('摄像头元素未找到,跳过初始化', 'warning');
log('Camera element not found, skipping initialization', 'warning');
return Promise.resolve(false);
}
@ -190,10 +190,10 @@ class App {
window.startCamera = async () => {
try {
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
log('浏览器不支持摄像头API', 'warning');
log('Browser does not support camera API', 'warning');
return false;
}
log('正在请求摄像头权限...', 'info');
log('Requesting camera permission...', 'info');
this.cameraStream = await navigator.mediaDevices.getUserMedia({
video: { width: 180, height: 240, facingMode: this.currentFacingMode },
audio: false
@ -206,23 +206,23 @@ class App {
}
cameraContainer.classList.add('active');
// 切换时挂断情况
// Hang up on switch
const hasActive = dialBtn.classList.contains('dial-active');
if (!hasActive) {
cameraContainer.classList.remove('active');
cameraSwitch.classList.remove('active');
window.stopCamera();
}
log('摄像头已启动', 'success');
log('Camera started', 'success');
return true;
} catch (error) {
log(`启动摄像头失败: ${error.name} - ${error.message}`, 'error');
log(`Failed to start camera: ${error.name} - ${error.message}`, 'error');
if (error.name === 'NotAllowedError') {
log('摄像头权限被拒绝,请检查浏览器设置', 'warning');
log('Camera permission denied, check browser settings', 'warning');
} else if (error.name === 'NotFoundError') {
log('未找到摄像头设备', 'warning');
log('Camera device not found', 'warning');
} else if (error.name === 'NotReadableError') {
log('摄像头已被其他程序占用', 'warning');
log('Camera is occupied by another program', 'warning');
}
return false;
}
@ -233,7 +233,7 @@ class App {
this.cameraStream.getTracks().forEach(track => track.stop());
this.cameraStream = null;
cameraVideo.srcObject = null;
log('摄像头已关闭', 'info');
log('Camera closed', 'info');
}
};
@ -263,16 +263,16 @@ class App {
}
};
window.takePhoto = (question = '描述一下看到的物品') => {
window.takePhoto = (question = 'Describe the visible object') => {
return new Promise(async (resolve) => {
const canvas = document.createElement('canvas');
const video = cameraVideo;
if (!video || video.readyState !== video.HAVE_ENOUGH_DATA) {
log('无法拍照:摄像头未就绪', 'warning');
log('Unable to capture photo: camera not ready', 'warning');
resolve({
success: false,
error: '摄像头未就绪,请确保已连接且摄像头已启动'
error: 'Camera not ready, ensure it is connected and started'
});
return;
}
@ -283,7 +283,7 @@ class App {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const photoData = canvas.toDataURL('image/jpeg', 0.8);
log(`拍照成功,图像数据长度: ${photoData.length}`, 'success');
log(`Photo captured successfully, image data length: ${photoData.length}`, 'success');
try {
const xz_tester_vision = localStorage.getItem('xz_tester_vision');
@ -293,15 +293,15 @@ class App {
try {
visionInfo = JSON.parse(xz_tester_vision);
} catch (err) {
throw new Error(`视觉配置解析失败`);
throw new Error(`Failed to parse vision config`);
}
const { url, token } = visionInfo || {};
if (!url || !token) {
throw new Error('视觉分析失败:配置缺少接口地址(url)或令牌(token)');
throw new Error('Visual analysis failed: config missing url or token');
}
log(`正在发送图片到视觉分析接口: ${url}`, 'info');
log(`Sending image to vision analysis API: ${url}`, 'info');
const deviceId = document.getElementById('deviceMac')?.value || '';
const clientId = document.getElementById('clientId')?.value || 'web_test_client';
@ -325,7 +325,7 @@ class App {
}
const analysisResult = await response.json();
log(`视觉分析完成: ${JSON.stringify(analysisResult).substring(0, 200)}...`, 'success');
log(`Visual analysis complete: ${JSON.stringify(analysisResult).substring(0, 200)}...`, 'success');
resolve({
success: true,
@ -336,10 +336,10 @@ class App {
vision_analysis: analysisResult
});
} else {
log('未配置视觉分析服务', 'warning');
log('Visual analysis service not configured', 'warning');
}
} catch (error) {
log(`视觉分析失败: ${error.message}`, 'error');
log(`Visual analysis failed: ${error.message}`, 'error');
resolve({
success: true,
message: question,
@ -349,25 +349,25 @@ class App {
vision_analysis: {
success: false,
error: error.message,
fallback: '无法连接到视觉分析服务'
fallback: 'Unable to connect to visual analysis service'
}
});
}
});
};
log('摄像头初始化完成', 'success');
log('Camera initialization complete', 'success');
resolve(true);
});
}
}
// 创建并启动应用
// Create and start app
const app = new App();
// 将应用实例暴露到全局,供其他模块访问
// Expose the application instance globally for access by other modules
window.chatApp = app;
document.addEventListener('DOMContentLoaded', () => {
// 初始化应用
// Initialize application
app.init();
});
export default app;

View file

@ -62,7 +62,7 @@
"mockResponse": {
"success": true,
"volume": "${volume}",
"message": "音量已设置为 ${volume}"
"message": "Volume set to ${volume}"
}
},
{
@ -84,7 +84,7 @@
"mockResponse": {
"success": true,
"brightness": "${brightness}",
"message": "亮度已设置为 ${brightness}"
"message": "Brightness set to ${brightness}"
}
}
]

View file

@ -1,9 +1,9 @@
// 配置管理模块
// Config management module
// 默认唤醒词列表
export const DEFAULT_WAKE_WORDS = '你好小智\n你好小志\n小爱同学\n你好小鑫\n你好小新\n小美同学\n小龙小龙\n喵喵同学\n小滨小滨\n小冰小冰\n嘿你好呀';
// Default wake word list
export const DEFAULT_WAKE_WORDS = 'Alexa\nHi ESP\nJarvis\ncomputer\nHey Willow\nSophia\nHey Wanda\nHi Jolly\nHi Fairy\nHey Printer\nMycroft\nHi Joy\nHi Jason\nAstrolabe\nHey Ily\nBlue Chip\nHi Lily';
// 生成随机MAC地址
// Generate random MAC address
function generateRandomMac() {
const hexDigits = '0123456789ABCDEF';
let mac = '';
@ -16,7 +16,7 @@ function generateRandomMac() {
return mac;
}
// 加载配置
// Load config
export function loadConfig() {
const deviceMacInput = document.getElementById('deviceMac');
const deviceNameInput = document.getElementById('deviceName');
@ -26,7 +26,7 @@ export function loadConfig() {
const wakewordEnabledInput = document.getElementById('wakewordEnabled');
const wakewordListInput = document.getElementById('wakewordList');
// 从localStorage加载MAC地址,如果没有则生成新的
// Load MAC address from localStorage, generate a new one if missing
let savedMac = localStorage.getItem('xz_tester_deviceMac');
if (!savedMac) {
savedMac = generateRandomMac();
@ -34,7 +34,7 @@ export function loadConfig() {
}
deviceMacInput.value = savedMac;
// 从localStorage加载其他配置
// Load other configs from localStorage
const savedDeviceName = localStorage.getItem('xz_tester_deviceName');
if (savedDeviceName) {
deviceNameInput.value = savedDeviceName;
@ -74,7 +74,7 @@ export function loadConfig() {
}
}
// 保存配置
// Save config
export function saveConfig() {
const deviceMacInput = document.getElementById('deviceMac');
const deviceNameInput = document.getElementById('deviceName');
@ -101,16 +101,16 @@ export function saveConfig() {
}
}
// 获取配置值
// Get config value
export function getConfig() {
// 从DOM获取值
// Get value from DOM
const deviceMac = document.getElementById('deviceMac')?.value.trim() || '';
const deviceName = document.getElementById('deviceName')?.value.trim() || '';
const clientId = document.getElementById('clientId')?.value.trim() || '';
const emojiEnabled = document.getElementById('emojiEnabled')?.value !== 'false';
return {
deviceId: deviceMac, // 使用MAC地址作为deviceId
deviceId: deviceMac, // Use MAC address as deviceId
deviceName,
deviceMac,
clientId,
@ -118,7 +118,7 @@ export function getConfig() {
};
}
// 保存连接URL
// Save connection URL
export function saveConnectionUrls() {
const otaUrl = document.getElementById('otaUrl').value.trim();
const wsUrl = document.getElementById('serverUrl').value.trim();

View file

@ -102,18 +102,18 @@ export class AudioRecorder {
this.processPCMBuffer(event.data.buffer);
}
};
log('使用AudioWorklet处理音频', 'success');
log('Processing audio with AudioWorklet', 'success');
const silent = this.audioContext.createGain();
silent.gain.value = 0;
audioProcessor.connect(silent);
silent.connect(this.audioContext.destination);
return { node: audioProcessor, type: 'worklet' };
} else {
log('AudioWorklet不可用,使用ScriptProcessorNode作为后备方案', 'warning');
log('AudioWorklet unavailable, falling back to ScriptProcessorNode', 'warning');
return this.createScriptProcessor();
}
} catch (error) {
log(`创建音频处理器失败: ${error.message},尝试后备方案`, 'error');
log(`Failed to create audio processor: ${error.message}, trying fallback`, 'error');
return this.createScriptProcessor();
}
}
@ -136,10 +136,10 @@ export class AudioRecorder {
silent.gain.value = 0;
scriptProcessor.connect(silent);
silent.connect(this.audioContext.destination);
log('使用ScriptProcessorNode作为后备方案成功', 'warning');
log('Successfully used ScriptProcessorNode as fallback', 'warning');
return { node: scriptProcessor, type: 'processor' };
} catch (fallbackError) {
log(`后备方案也失败: ${fallbackError.message}`, 'error');
log(`Fallback also failed: ${fallbackError.message}`, 'error');
return null;
}
}
@ -162,7 +162,7 @@ export class AudioRecorder {
// Encode and send Opus data
encodeAndSendOpus(pcmData = null) {
if (!this.opusEncoder) {
log('Opus编码器未初始化', 'error');
log('Opus encoder not initialized', 'error');
return;
}
try {
@ -175,11 +175,11 @@ export class AudioRecorder {
try {
this.websocket.send(opusData.buffer);
} catch (error) {
log(`WebSocket发送错误: ${error.message}`, 'error');
log(`WebSocket send error: ${error.message}`, 'error');
}
}
} else {
log('Opus编码失败,未返回有效数据', 'error');
log('Opus encoding failed, no valid data returned', 'error');
}
} else {
if (this.pcmDataBuffer.length > 0) {
@ -195,7 +195,7 @@ export class AudioRecorder {
}
}
} catch (error) {
log(`Opus编码错误: ${error.message}`, 'error');
log(`Opus encoding error: ${error.message}`, 'error');
}
}
@ -204,10 +204,10 @@ export class AudioRecorder {
if (this.isRecording) return false;
try {
if (!this.initEncoder()) {
log('无法开始录音: Opus编码器初始化失败', 'error');
log('Cannot start recording: Opus encoder initialization failed', 'error');
return false;
}
log('请至少录制1-2秒音频以确保收集足够的数据', 'info');
log('Record at least 1-2 seconds to ensure sufficient data collection', 'info');
const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, sampleRate: 16000, channelCount: 1 } });
this.audioContext = this.getAudioContext();
if (this.audioContext.state === 'suspended') {
@ -215,7 +215,7 @@ export class AudioRecorder {
}
const processorResult = await this.createAudioProcessor();
if (!processorResult) {
log('无法创建音频处理器', 'error');
log('Failed to create audio processor', 'error');
return false;
}
this.audioProcessor = processorResult.node;
@ -234,9 +234,9 @@ export class AudioRecorder {
}
// Send listening start message
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
log(`已发送录音开始消息`, 'info');
log(`Sent recording start message`, 'info');
} else {
log('WebSocket未连接,无法发送开始消息', 'error');
log('WebSocket not connected, cannot send start message', 'error');
return false;
}
// Start visualization
@ -256,10 +256,10 @@ export class AudioRecorder {
this.onRecordingStart(recordingSeconds);
}
}, 100);
log('已开始PCM直接录音', 'success');
log('PCM direct recording started', 'success');
return true;
} catch (error) {
log(`直接录音启动错误: ${error.message}`, 'error');
log(`Direct recording start error: ${error.message}`, 'error');
this.isRecording = false;
return false;
}
@ -308,15 +308,15 @@ export class AudioRecorder {
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
const emptyOpusFrame = new Uint8Array(0);
this.websocket.send(emptyOpusFrame);
log('已发送录音停止信号', 'info');
log('Recording stop signal sent', 'info');
}
if (this.onRecordingStop) {
this.onRecordingStop();
}
log('已停止PCM直接录音', 'success');
log('PCM direct recording stopped', 'success');
return true;
} catch (error) {
log(`直接录音停止错误: ${error.message}`, 'error');
log(`Direct recording stop error: ${error.message}`, 'error');
return false;
}
}
@ -344,7 +344,7 @@ export function getAudioRecorder() {
export async function checkMicrophoneAvailability() {
// Check if browser supports getUserMedia API
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
log('浏览器不支持getUserMedia API', 'warning');
log('Browser does not support getUserMedia API', 'warning');
return false;
}
try {
@ -352,10 +352,10 @@ export async function checkMicrophoneAvailability() {
const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, sampleRate: 16000, channelCount: 1 } });
// Immediately stop all tracks to release microphone
stream.getTracks().forEach(track => track.stop());
log('麦克风可用性检查成功', 'success');
log('Microphone availability check succeeded', 'success');
return true;
} catch (error) {
log(`麦克风不可用: ${error.message}`, 'warning');
log(`Microphone unavailable: ${error.message}`, 'warning');
return false;
}
}

View file

@ -16,7 +16,7 @@ export function startWakewordBridgeListener() {
}
shouldReconnect = true;
log('正在连接本地唤醒事件桥...', 'info');
log('Connecting to local wake event bridge...', 'info');
tryConnect();
return wakewordSocket;
}
@ -28,15 +28,15 @@ function tryConnect() {
wakewordSocket = new WebSocket(bridgeUrl);
wakewordSocket.onopen = () => {
reconnectAttempts = 0;
log(`本地唤醒事件桥已连接: ${bridgeUrl}`, 'success');
// 连接成功后自动保存地址,刷新后仍能记住
log(`Local wake event bridge connected: ${bridgeUrl}`, 'success');
// Auto-save address after successful connection, persists after refresh
localStorage.setItem('xz_tester_wakewordWsUrl', bridgeUrl);
const urlInput = document.getElementById('wakewordWsUrl');
if (urlInput) urlInput.value = bridgeUrl;
};
wakewordSocket.onerror = () => {
log(`本地唤醒事件桥连接失败: ${bridgeUrl}`, 'error');
log(`Local wake event bridge connection failed: ${bridgeUrl}`, 'error');
};
wakewordSocket.onmessage = async (event) => {
@ -48,12 +48,12 @@ function tryConnect() {
}
if (message.success === false) {
log(`本地唤醒事件桥返回错误: ${message.error || '未知错误'}`, 'error');
log(`Local wake event bridge returned error: ${message.error || 'Unknown error'}`, 'error');
return;
}
if (message.type === 'bridge_connected') {
log('本地唤醒监听已就绪', 'info');
log('Local wake word listener ready', 'info');
if (onNextBridgeConnectedCallback) {
const cb = onNextBridgeConnectedCallback;
onNextBridgeConnectedCallback = null;
@ -63,28 +63,28 @@ function tryConnect() {
}
if (message.type === 'service_ready') {
log('本地唤醒服务已启动', 'info');
log('Local wake word service started', 'info');
return;
}
if (message.type === 'wakeword_config') {
uiController.applyWakewordConfig(message.payload || {});
log('已同步本地唤醒词配置', 'info');
log('Local wake word configuration synced', 'info');
return;
}
if (message.type === 'service_stopping') {
log('本地唤醒服务正在停止', 'warning');
log('Local wake word service stopping', 'warning');
return;
}
if (message.type === 'wake_word_detected') {
const wakeWord = message.payload?.wake_word || '唤醒词';
log(`检测到本地唤醒事件: ${wakeWord}`, 'info');
const wakeWord = message.payload?.wake_word || 'wake word';
log(`Local wake event detected: ${wakeWord}`, 'info');
await uiController.triggerWakewordDial(wakeWord);
}
} catch (error) {
log(`解析本地唤醒事件失败: ${error.message}`, 'error');
log(`Failed to parse local wake word event: ${error.message}`, 'error');
}
};
@ -93,7 +93,7 @@ function tryConnect() {
wakewordSocket = null;
}
rejectAllWakewordRequests('本地唤醒事件桥已断开');
rejectAllWakewordRequests('Local wake event bridge disconnected');
if (!shouldReconnect) {
return;
@ -105,7 +105,7 @@ function tryConnect() {
reconnectAttempts += 1;
const delay = Math.min(1000 * reconnectAttempts, 5000);
log(`本地唤醒事件桥将在 ${delay}ms 后重连: ${bridgeUrl}`, 'warning');
log(`Local wake event bridge will reconnect in ${delay}ms: ${bridgeUrl}`, 'warning');
reconnectTimer = window.setTimeout(() => {
reconnectTimer = null;
tryConnect();
@ -114,7 +114,7 @@ function tryConnect() {
return wakewordSocket;
} catch (error) {
log(`启动本地唤醒监听失败: ${error.message}`, 'error');
log(`Failed to start local wake word listener: ${error.message}`, 'error');
return null;
}
}
@ -138,7 +138,7 @@ export function stopWakewordBridgeListener() {
export function sendWakewordBridgeMessage(type, payload = {}, requestId = null) {
if (!wakewordSocket || wakewordSocket.readyState !== WebSocket.OPEN) {
log('本地唤醒事件桥未连接,无法发送消息', 'warning');
log('Local wake event bridge not connected, cannot send message', 'warning');
return false;
}
@ -156,7 +156,7 @@ export function requestWakewordBridge(type, payload = {}, timeout = 5000) {
return new Promise((resolve, reject) => {
const timer = window.setTimeout(() => {
pendingWakewordRequests.delete(requestId);
reject(new Error('本地唤醒服务响应超时'));
reject(new Error('Local wake service response timed out'));
}, timeout);
pendingWakewordRequests.set(requestId, { resolve, reject, timer });
@ -164,7 +164,7 @@ export function requestWakewordBridge(type, payload = {}, timeout = 5000) {
if (!sendWakewordBridgeMessage(type, payload, requestId)) {
window.clearTimeout(timer);
pendingWakewordRequests.delete(requestId);
reject(new Error('本地唤醒事件桥未连接'));
reject(new Error('Local wake event bridge not connected'));
}
});
}
@ -209,7 +209,7 @@ function settleWakewordRequest(message) {
pendingWakewordRequests.delete(message.requestId);
if (message.success === false) {
pendingRequest.reject(new Error(message.error || '本地唤醒服务返回失败'));
pendingRequest.reject(new Error(message.error || 'Local wake service returned failure'));
return;
}

View file

@ -1,4 +1,4 @@
// WebSocket消息处理模块
// WebSocket message handling module
import { getConfig, saveConnectionUrls } from '../../config/manager.js?v=0205';
import { uiController } from '../../ui/controller.js?v=0205';
import { log } from '../../utils/logger.js?v=0205';
@ -7,7 +7,7 @@ import { getAudioRecorder } from '../audio/recorder.js?v=0205';
import { executeMcpTool, getMcpTools, setWebSocket as setMcpWebSocket } from '../mcp/tools.js?v=0205';
import { webSocketConnect } from './ota-connector.js?v=0205';
// WebSocket处理器类
// WebSocket handler class
export class WebSocketHandler {
constructor() {
this.websocket = null;
@ -15,12 +15,12 @@ export class WebSocketHandler {
this.onRecordButtonStateChange = null;
this.onSessionStateChange = null;
this.onSessionEmotionChange = null;
this.onChatMessage = null; // 新增:聊天消息回调
this.onChatMessage = null; // Added: chat message callback
this.currentSessionId = null;
this.isRemoteSpeaking = false;
}
// 发送hello握手消息
// Send hello handshake message
async sendHelloMessage() {
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) return false;
@ -39,13 +39,13 @@ export class WebSocketHandler {
}
};
log('发送hello握手消息', 'info');
log('Send hello handshake message', 'info');
this.websocket.send(JSON.stringify(helloMessage));
return new Promise(resolve => {
const timeout = setTimeout(() => {
log('等待hello响应超时', 'error');
log('提示: 请尝试点击"测试认证"按钮进行连接排查', 'info');
log('Timeout waiting for hello response', 'error');
log('Hint: try clicking the "Test authentication" button to troubleshoot the connection', 'info');
resolve(false);
}, 5000);
@ -53,20 +53,20 @@ export class WebSocketHandler {
try {
const response = JSON.parse(event.data);
if (response.type === 'hello' && response.session_id) {
log(`服务器握手成功,会话ID: ${response.session_id}`, 'success');
log(`Server handshake successful, session ID: ${response.session_id}`, 'success');
clearTimeout(timeout);
this.websocket.removeEventListener('message', onMessageHandler);
resolve(true);
}
} catch (e) {
// 忽略非JSON消息
// Ignore non-JSON messages
}
};
this.websocket.addEventListener('message', onMessageHandler);
});
} catch (error) {
log(`发送hello消息错误: ${error.message}`, 'error');
log(`Error sending hello message: ${error.message}`, 'error');
return false;
}
}
@ -79,26 +79,26 @@ export class WebSocketHandler {
session_id: sessionId,
type: 'listen',
state: 'detect',
text: '嘿,你好呀'
text: 'Hey, hello'
}));
log('发送listen detect消息,唤醒词: 嘿,你好呀', 'info');
log('Sending listen detect message, wake word: Hey, Hello', 'info');
// listen start:开始监听
// listen start: Begin listening
this.websocket.send(JSON.stringify({
session_id: sessionId,
type: 'listen',
state: 'start',
mode: 'auto'
}));
log('发送listen start消息', 'info');
log('Sending listen start message', 'info');
}
// 处理文本消息
// Process text message
handleTextMessage(message) {
if (message.type === 'hello') {
log(`服务器回应:${JSON.stringify(message, null, 2)}`, 'success');
log(`Server response: ${JSON.stringify(message, null, 2)}`, 'success');
window.cameraAvailable = true;
log('连接成功,摄像头已可用', 'success');
log('Connection successful, camera available', 'success');
uiController.updateDialButton(true);
this._sendWakeupMessages(message.session_id);
@ -107,54 +107,54 @@ export class WebSocketHandler {
} else if (message.type === 'tts') {
this.handleTTSMessage(message);
} else if (message.type === 'audio') {
log(`收到音频控制消息: ${JSON.stringify(message)}`, 'info');
log(`Received audio control message: ${JSON.stringify(message)}`, 'info');
} else if (message.type === 'stt') {
log(`识别结果: ${message.text}`, 'info');
// 检查是否需要绑定设备
if (message.text && (message.text.includes('绑定') || message.text.includes('bind'))) {
log('收到设备绑定提示,更新摄像头状态', 'warning');
log(`Recognition result: ${message.text}`, 'info');
// Check if device binding is required
if (message.text && (message.text.includes('bind') || message.text.includes('bind'))) {
log('Received device binding prompt, updating camera status', 'warning');
window.cameraAvailable = false;
// 关闭摄像头
// Close camera
if (typeof window.stopCamera === 'function') {
window.stopCamera();
}
// 更新摄像头按钮状态
// Update camera button state
const cameraBtn = document.getElementById('cameraBtn');
if (cameraBtn) {
cameraBtn.classList.remove('camera-active');
cameraBtn.querySelector('.btn-text').textContent = '摄像头';
cameraBtn.querySelector('.btn-text').textContent = 'Camera';
cameraBtn.disabled = true;
cameraBtn.title = '请先绑定验证码';
cameraBtn.title = 'Bind verification code first';
}
}
// 使用新的聊天消息回调显示STT消息
// Use new chat message callback to display STT messages
if (this.onChatMessage && message.text) {
this.onChatMessage(message.text, true);
}
} else if (message.type === 'llm') {
log(`大模型回复: ${message.text}`, 'info');
// 使用新的聊天消息回调显示LLM回复
log(`LLM response: ${message.text}`, 'info');
// Use new chat message callback to display LLM replies
if (this.onChatMessage && message.text) {
this.onChatMessage(message.text, false);
}
// 如果包含表情,更新sessionStatus表情并触发Live2D动作
// If emojis are included, update sessionStatus emoji and trigger Live2D action
if (message.text && /[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/u.test(message.text)) {
// 提取表情符号
// Extract emojis
const emojiMatch = message.text.match(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/u);
if (emojiMatch && this.onSessionEmotionChange) {
this.onSessionEmotionChange(emojiMatch[0]);
}
// 触发Live2D情绪动作
// Trigger Live2D emotion action
if (message.emotion) {
console.log(`收到情绪消息: emotion=${message.emotion}, text=${message.text}`);
console.log(`Received emotion message: emotion=${message.emotion}, text=${message.text}`);
this.triggerLive2DEmotionAction(message.emotion);
}
}
// 只有当文本不仅仅是表情时,才添加到对话中
// 移除文本中的表情后检查是否还有内容
// Add to conversation only if text is not just an emoji
// Remove emojis from text and check if content remains
const textWithoutEmoji = message.text ? message.text.replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu, '').trim() : '';
if (textWithoutEmoji && this.onChatMessage) {
this.onChatMessage(message.text, false);
@ -162,46 +162,46 @@ export class WebSocketHandler {
} else if (message.type === 'mcp') {
this.handleMCPMessage(message);
} else {
log(`未知消息类型: ${message.type}`, 'info');
log(`Unknown message type: ${message.type}`, 'info');
if (this.onChatMessage) {
this.onChatMessage(`未知消息类型: ${message.type}\n${JSON.stringify(message, null, 2)}`, false);
this.onChatMessage(`Unknown message type: ${message.type} \n ${JSON.stringify(message, null, 2)}`, false);
}
}
}
// 处理TTS消息
// Process TTS message
handleTTSMessage(message) {
if (message.state === 'start') {
log('服务器开始发送语音', 'info');
log('Server started sending audio', 'info');
this.currentSessionId = message.session_id;
this.isRemoteSpeaking = true;
if (this.onSessionStateChange) {
this.onSessionStateChange(true);
}
// 启动Live2D说话动画
// Start Live2D speaking animation
this.startLive2DTalking();
} else if (message.state === 'sentence_start') {
log(`服务器发送语音段: ${message.text}`, 'info');
log(`Server sent voice segment: ${message.text}`, 'info');
this.ttsSentenceCount = (this.ttsSentenceCount || 0) + 1;
if (message.text && this.onChatMessage) {
this.onChatMessage(message.text, false);
}
// 确保动画在句子开始时运行
// Ensure animation starts at the beginning of the sentence
const live2dManager = window.chatApp?.live2dManager;
if (live2dManager && !live2dManager.isTalking) {
this.startLive2DTalking();
}
} else if (message.state === 'sentence_end') {
log(`语音段结束: ${message.text}`, 'info');
log(`Voice segment ended: ${message.text}`, 'info');
// 句子结束时不清除动画,等待下一个句子或最终停止
// Do not clear animation at sentence end, wait for the next sentence or final stop
} else if (message.state === 'stop') {
log('服务器语音传输结束,清空所有音频缓冲', 'info');
log('Server voice transmission ended, clearing all audio buffers', 'info');
// 清空所有音频缓冲并停止播放
// Clear all audio buffers and stop playback
const audioPlayer = getAudioPlayer();
audioPlayer.clearAllAudio();
@ -213,63 +213,63 @@ export class WebSocketHandler {
this.onSessionStateChange(false);
}
// 延迟停止Live2D说话动画,确保所有句子都播放完毕
// Delay stopping Live2D speaking animation to ensure all sentences finish playing
setTimeout(() => {
this.stopLive2DTalking();
this.ttsSentenceCount = 0; // 重置计数器
}, 1000); // 1秒延迟,确保所有句子都完成
this.ttsSentenceCount = 0; // Reset counter
}, 1000); // 1-second delay to ensure all sentences are completed
}
}
// 启动Live2D说话动画
// Start Live2D speaking animation
startLive2DTalking() {
try {
// 获取Live2D管理器实例
// Get Live2D manager instance
const live2dManager = window.chatApp?.live2dManager;
if (live2dManager && live2dManager.live2dModel) {
// 使用音频播放器的分析器节点
// Use the analyzer node of the audio player
live2dManager.startTalking();
log('Live2D说话动画已启动', 'info');
log('Live2D speaking animation started', 'info');
}
} catch (error) {
log(`启动Live2D说话动画失败: ${error.message}`, 'error');
log(`Failed to start Live2D speaking animation: ${error.message}`, 'error');
}
}
// 停止Live2D说话动画
// Stop Live2D speaking animation
stopLive2DTalking() {
try {
const live2dManager = window.chatApp?.live2dManager;
if (live2dManager) {
live2dManager.stopTalking();
log('Live2D说话动画已停止', 'info');
log('Live2D speaking animation stopped', 'info');
}
} catch (error) {
log(`停止Live2D说话动画失败: ${error.message}`, 'error');
log(`Failed to stop Live2D speaking animation: ${error.message}`, 'error');
}
}
// 初始化Live2D音频分析器
// Initialize Live2D audio analyzer
initializeLive2DAudioAnalyzer() {
try {
const live2dManager = window.chatApp?.live2dManager;
if (live2dManager) {
// 初始化音频分析器(使用音频播放器的上下文)
// Initialize audio analyzer (using audio player context)
if (live2dManager.initializeAudioAnalyzer()) {
log('Live2D音频分析器初始化完成,已连接到音频播放器', 'success');
log('Live2D audio analyzer initialized, connected to audio player', 'success');
} else {
log('Live2D音频分析器初始化失败,将使用模拟动画', 'warning');
log('Live2D audio analyzer initialization failed, using simulated animation', 'warning');
}
}
} catch (error) {
log(`初始化Live2D音频分析器失败: ${error.message}`, 'error');
log(`Failed to initialize Live2D audio analyzer: ${error.message}`, 'error');
}
}
// 处理MCP消息
// Process MCP message
handleMCPMessage(message) {
const payload = message.payload || {};
log(`服务器下发: ${JSON.stringify(message)}`, 'info');
log(`Server sent: ${JSON.stringify(message)}`, 'info');
if (payload.method === 'tools/list') {
const tools = getMcpTools();
@ -285,15 +285,15 @@ export class WebSocketHandler {
}
}
});
log(`客户端上报: ${replyMessage}`, 'info');
log(`Client report: ${replyMessage}`, 'info');
this.websocket.send(replyMessage);
log(`回复MCP工具列表: ${tools.length} 个工具`, 'info');
log(`Replying with MCP tool list: ${tools.length} tools`, 'info');
} else if (payload.method === 'tools/call') {
const toolName = payload.params?.name;
const toolArgs = payload.params?.arguments;
log(`调用工具: ${toolName} 参数: ${JSON.stringify(toolArgs)}`, 'info');
log(`Calling tool: ${toolName} Args: ${JSON.stringify(toolArgs)}`, 'info');
executeMcpTool(toolName, toolArgs).then(result => {
const replyMessage = JSON.stringify({
@ -314,10 +314,10 @@ export class WebSocketHandler {
}
});
log(`客户端上报: ${replyMessage}`, 'info');
log(`Client report: ${replyMessage}`, 'info');
this.websocket.send(replyMessage);
}).catch(error => {
log(`工具执行失败: ${error.message}`, 'error');
log(`Tool execution failed: ${error.message}`, 'error');
const errorReply = JSON.stringify({
"session_id": message.session_id || "",
"type": "mcp",
@ -333,8 +333,8 @@ export class WebSocketHandler {
this.websocket.send(errorReply);
});
} else if (payload.method === 'initialize') {
log(`收到工具初始化请求: ${JSON.stringify(payload.params)}`, 'info');
// 保存视觉分析接口地址
log(`Received tool initialization request: ${JSON.stringify(payload.params)}`, 'info');
// Save visual analysis API address
const visionUrl = document.getElementById('visionUrl');
const visionConfig = payload?.params?.capabilities?.vision;
if (visionConfig && typeof visionConfig === 'object' && visionConfig.url && visionConfig.token) {
@ -364,14 +364,14 @@ export class WebSocketHandler {
}
}
});
log(`回复初始化响应`, 'info');
log(`Reply initialization response`, 'info');
this.websocket.send(replyMessage);
} else {
log(`未知的MCP方法: ${payload.method}`, 'warning');
log(`Unknown MCP method: ${payload.method}`, 'warning');
}
}
// 处理二进制消息
// Process binary message
async handleBinaryMessage(data) {
try {
let arrayBuffer;
@ -379,9 +379,9 @@ export class WebSocketHandler {
arrayBuffer = data;
} else if (data instanceof Blob) {
arrayBuffer = await data.arrayBuffer();
log(`收到Blob音频数据,大小: ${arrayBuffer.byteLength}字节`, 'debug');
log(`Received Blob audio data, size: ${arrayBuffer.byteLength} bytes`, 'debug');
} else {
log(`收到未知类型的二进制数据: ${typeof data}`, 'warning');
log(`Received unknown binary data type: ${typeof data}`, 'warning');
return;
}
@ -389,14 +389,14 @@ export class WebSocketHandler {
const audioPlayer = getAudioPlayer();
audioPlayer.enqueueAudioData(opusData);
} catch (error) {
log(`处理二进制消息出错: ${error.message}`, 'error');
log(`Error processing binary message: ${error.message}`, 'error');
}
}
// 连接WebSocket服务器
// Connect to WebSocket server
async connect() {
const config = getConfig();
log('正在检查OTA状态...', 'info');
log('Checking OTA status...', 'info');
saveConnectionUrls();
try {
@ -407,13 +407,13 @@ export class WebSocketHandler {
}
this.websocket = ws;
// 设置接收二进制数据的类型为ArrayBuffer
// Set binary data reception type to ArrayBuffer
this.websocket.binaryType = 'arraybuffer';
// 设置 MCP 模块的 WebSocket 实例
// Set the WebSocket instance for the MCP module
setMcpWebSocket(this.websocket);
// 设置录音器的WebSocket
// Set WebSocket for recorder
const audioRecorder = getAudioRecorder();
audioRecorder.setWebSocket(this.websocket);
@ -421,7 +421,7 @@ export class WebSocketHandler {
return true;
} catch (error) {
log(`连接错误: ${error.message}`, 'error');
log(`Connection error: ${error.message}`, 'error');
if (this.onConnectionStateChange) {
this.onConnectionStateChange(false);
}
@ -429,30 +429,30 @@ export class WebSocketHandler {
}
}
// 设置事件处理器
// Set event handler
setupEventHandlers() {
this.websocket.onopen = async () => {
const url = document.getElementById('serverUrl').value;
log(`已连接到服务器: ${url}`, 'success');
log(`Connected to server: ${url}`, 'success');
if (this.onConnectionStateChange) {
this.onConnectionStateChange(true);
}
// 连接成功后,默认状态为聆听中
// After successful connection, default state is listening
this.isRemoteSpeaking = false;
if (this.onSessionStateChange) {
this.onSessionStateChange(false);
}
// 在WebSocket连接成功时初始化Live2D音频分析器
// Initialize the Live2D audio analyzer upon successful WebSocket connection
this.initializeLive2DAudioAnalyzer();
await this.sendHelloMessage();
};
this.websocket.onclose = () => {
log('已断开连接', 'info');
log('Disconnected', 'info');
if (this.onConnectionStateChange) {
this.onConnectionStateChange(false);
@ -461,12 +461,12 @@ export class WebSocketHandler {
const audioRecorder = getAudioRecorder();
audioRecorder.stop();
// 关闭摄像头
// Close camera
if (typeof window.stopCamera === 'function') {
window.stopCamera();
}
// 隐藏摄像头显示区域
// Hide camera display area
const cameraContainer = document.getElementById('cameraContainer');
if (cameraContainer) {
cameraContainer.classList.remove('active');
@ -474,8 +474,8 @@ export class WebSocketHandler {
};
this.websocket.onerror = (error) => {
log(`WebSocket错误: ${error.message || '未知错误'}`, 'error');
uiController.addChatMessage(`⚠️ WebSocket错误: ${error.message || '未知错误'}`, false);
log(`WebSocket error: ${error.message || 'Unknown error'}`, 'error');
uiController.addChatMessage(`⚠️ WebSocket error: ${error.message || 'Unknown error'}`, false);
if (this.onConnectionStateChange) {
this.onConnectionStateChange(false);
}
@ -490,14 +490,14 @@ export class WebSocketHandler {
this.handleBinaryMessage(event.data);
}
} catch (error) {
log(`WebSocket消息处理错误: ${error.message}`, 'error');
// 不再使用旧的addMessage函数,因为conversationDiv元素不存在
// 错误消息将通过其他方式显示
log(`WebSocket message processing error: ${error.message}`, 'error');
// No longer using the old addMessage function because the conversationDiv element does not exist
// Error messages will be displayed via other means
}
};
}
// 断开连接
// Disconnect
disconnect() {
if (!this.websocket) return;
@ -505,26 +505,26 @@ export class WebSocketHandler {
const audioRecorder = getAudioRecorder();
audioRecorder.stop();
// 关闭摄像头
// Close camera
if (typeof window.stopCamera === 'function') {
window.stopCamera();
}
// 隐藏摄像头显示区域
// Hide camera display area
const cameraContainer = document.getElementById('cameraContainer');
if (cameraContainer) {
cameraContainer.classList.remove('active');
}
}
// 发送文本消息
// Send text message
sendTextMessage(text) {
if (text === '' || !this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
return false;
}
try {
// 如果对方正在说话,先发送打断消息
// If the other party is speaking, send an interrupt message first
if (this.isRemoteSpeaking && this.currentSessionId) {
const abortMessage = {
session_id: this.currentSessionId,
@ -532,7 +532,7 @@ export class WebSocketHandler {
reason: 'wake_word_detected'
};
this.websocket.send(JSON.stringify(abortMessage));
log('发送打断消息', 'info');
log('Sending interrupt message', 'info');
}
const listenMessage = {
@ -542,45 +542,45 @@ export class WebSocketHandler {
};
this.websocket.send(JSON.stringify(listenMessage));
log(`发送文本消息: ${text}`, 'info');
log(`Sending text message: ${text}`, 'info');
return true;
} catch (error) {
log(`发送消息错误: ${error.message}`, 'error');
log(`Error sending message: ${error.message}`, 'error');
return false;
}
}
/**
* 触发Live2D情绪动作
* @param {string} emotion - 情绪名称
* Trigger Live2D emotion action
* @param {string} emotion - Emotion name
*/
triggerLive2DEmotionAction(emotion) {
try {
const live2dManager = window.chatApp?.live2dManager;
if (live2dManager && typeof live2dManager.triggerEmotionAction === 'function') {
live2dManager.triggerEmotionAction(emotion);
log(`触发Live2D情绪动作: ${emotion}`, 'info');
log(`Trigger Live2D emotion action: ${emotion}`, 'info');
} else {
log(`无法触发Live2D情绪动作: Live2D管理器未找到或方法不可用`, 'warning');
log(`Cannot trigger Live2D emotion action: Live2D manager not found or method unavailable`, 'warning');
}
} catch (error) {
log(`触发Live2D情绪动作失败: ${error.message}`, 'error');
log(`Failed to trigger Live2D emotion action: ${error.message}`, 'error');
}
}
// 获取WebSocket实例
// Get WebSocket instance
getWebSocket() {
return this.websocket;
}
// 检查是否已连接
// Check connection status
isConnected() {
return this.websocket && this.websocket.readyState === WebSocket.OPEN;
}
}
// 创建单例
// Create Singleton
let wsHandlerInstance = null;
export function getWebSocketHandler() {

View file

@ -165,36 +165,36 @@ class UIController {
cameraTimer = setTimeout(() => {
const cameraContainer = document.getElementById('cameraContainer');
if (!cameraContainer) {
log('摄像头容器不存在', 'warning');
log('Camera container does not exist', 'warning');
return;
}
const isActive = cameraContainer.classList.contains('active');
if (isActive) {
// 关闭摄像头
// Close camera
if (typeof window.stopCamera === 'function') {
if (cameraSwitch) cameraSwitch.classList.remove('active');
window.stopCamera();
}
cameraContainer.classList.remove('active');
cameraBtn.classList.remove('camera-active');
cameraBtn.querySelector('.btn-text').textContent = '摄像头';
log('摄像头已关闭', 'info');
cameraBtn.querySelector('.btn-text').textContent = 'Camera';
log('Camera closed', 'info');
} else {
// 打开摄像头
// Open camera
if (typeof window.startCamera === 'function') {
window.startCamera().then(success => {
if (success) {
cameraBtn.classList.add('camera-active');
cameraBtn.querySelector('.btn-text').textContent = '关闭';
cameraBtn.querySelector('.btn-text').textContent = 'Close';
} else {
this.addChatMessage('⚠️ 摄像头启动失败,请检查浏览器权限', false);
this.addChatMessage('⚠️ Camera startup failed, check browser permissions', false);
}
}).catch(error => {
log(`启动摄像头异常: ${error.message}`, 'error');
log(`Camera startup exception: ${error.message}`, 'error');
});
} else {
log('startCamera函数未定义', 'warning');
log('startCamera function undefined', 'warning');
}
}
}, 300);
@ -216,11 +216,11 @@ class UIController {
audioRecorder.stop();
// Restore record button to normal state
recordBtn.classList.remove('recording');
recordBtn.querySelector('.btn-text').textContent = '录音';
recordBtn.querySelector('.btn-text').textContent = 'Record';
} else {
// Update button state to recording
recordBtn.classList.add('recording');
recordBtn.querySelector('.btn-text').textContent = '录音中';
recordBtn.querySelector('.btn-text').textContent = 'Recording';
// Start recording, update button state after delay
setTimeout(() => {
@ -274,15 +274,15 @@ class UIController {
applyWakewordBtn.addEventListener('click', this.handleApplyWakeword);
}
// 点击模态框背景关闭(仅对特定模态框禁用此功能)
// Close modal by clicking background (disabled for specific modals)
const modals = document.querySelectorAll('.modal');
modals.forEach(modal => {
modal.addEventListener('click', (e) => {
if (e.target === modal) {
// settingsModal、mcpToolModal、mcpPropertyModal 只能通过点击X关闭
// settingsModal, mcpToolModal, and mcpPropertyModal can only be closed by clicking X
const nonClosableModals = ['settingsModal', 'mcpToolModal', 'mcpPropertyModal'];
if (nonClosableModals.includes(modal.id)) {
return; // 禁止点击背景关闭
return; // Prevent closing by clicking background
}
this.hideModal(modal.id);
}
@ -308,12 +308,12 @@ class UIController {
if (connectionStatus) {
if (isConnected) {
connectionStatus.textContent = '已连接';
connectionStatus.textContent = 'Connected';
if (statusDot) {
statusDot.className = 'status-dot status-connected';
}
} else {
connectionStatus.textContent = '离线';
connectionStatus.textContent = 'Offline';
if (statusDot) {
statusDot.className = 'status-dot status-disconnected';
}
@ -330,14 +330,14 @@ class UIController {
if (dialBtn) {
if (isConnected) {
dialBtn.classList.add('dial-active');
dialBtn.querySelector('.btn-text').textContent = '挂断';
dialBtn.querySelector('.btn-text').textContent = 'Hang up';
// Update dial button icon to hang up icon
dialBtn.querySelector('svg').innerHTML = `
<path d="M12,9C10.4,9 9,10.4 9,12C9,13.6 10.4,15 12,15C13.6,15 15,13.6 15,12C15,10.4 13.6,9 12,9M12,17C9.2,17 7,14.8 7,12C7,9.2 9.2,7 12,7C14.8,7 17,9.2 17,12C17,14.8 14.8,17 12,17M12,4.5C7,4.5 2.7,7.6 1,12C2.7,16.4 7,19.5 12,19.5C17,19.5 21.3,16.4 23,12C21.3,7.6 17,4.5 12,4.5Z"/>
`;
} else {
dialBtn.classList.remove('dial-active');
dialBtn.querySelector('.btn-text').textContent = '拨号';
dialBtn.querySelector('.btn-text').textContent = 'Dial';
// Restore dial button icon
dialBtn.querySelector('svg').innerHTML = `
<path d="M6.62,10.79C8.06,13.62 10.38,15.94 13.21,17.38L15.41,15.18C15.69,14.9 16.08,14.82 16.43,14.93C17.55,15.3 18.75,15.5 20,15.5A1,1 0 0,1 21,16.5V20A1,1 0 0,1 20,21A17,17 0 0,1 3,4A1,1 0 0,1 4,3H7.5A1,1 0 0,1 8.5,4C8.5,5.25 8.7,6.45 9.07,7.57C9.18,7.92 9.1,8.31 8.82,8.59L6.62,10.79Z"/>
@ -352,10 +352,10 @@ class UIController {
cameraContainer.classList.remove('active');
}
cameraBtn.classList.remove('camera-active');
cameraBtn.querySelector('.btn-text').textContent = '摄像头';
cameraBtn.querySelector('.btn-text').textContent = 'Camera';
cameraBtn.disabled = true;
cameraBtn.title = '请先连接服务器';
// 关闭摄像头
cameraBtn.title = 'Connect to server first';
// Close camera
if (typeof window.stopCamera === 'function') {
window.stopCamera();
}
@ -365,10 +365,10 @@ class UIController {
if (cameraBtn && isConnected) {
if (window.cameraAvailable) {
cameraBtn.disabled = false;
cameraBtn.title = '打开/关闭摄像头';
cameraBtn.title = 'Toggle camera';
} else {
cameraBtn.disabled = true;
cameraBtn.title = '请先绑定验证码';
cameraBtn.title = 'Bind verification code first';
}
}
@ -377,19 +377,19 @@ class UIController {
const microphoneAvailable = window.microphoneAvailable !== false;
if (isConnected && microphoneAvailable) {
recordBtn.disabled = false;
recordBtn.title = '开始录音';
recordBtn.title = 'Start Recording';
// Restore record button to normal state
recordBtn.querySelector('.btn-text').textContent = '录音';
recordBtn.querySelector('.btn-text').textContent = 'Record';
recordBtn.classList.remove('recording');
} else {
recordBtn.disabled = true;
if (!microphoneAvailable) {
recordBtn.title = window.isHttpNonLocalhost ? '当前由于是http访问,无法录音,只能用文字交互' : '麦克风不可用';
recordBtn.title = window.isHttpNonLocalhost ? 'Recording unavailable due to HTTP access; text interaction only' : 'Microphone unavailable';
} else {
recordBtn.title = '请先连接服务器';
recordBtn.title = 'Please connect to server first';
}
// Restore record button to normal state
recordBtn.querySelector('.btn-text').textContent = '录音';
recordBtn.querySelector('.btn-text').textContent = 'Record';
recordBtn.classList.remove('recording');
}
}
@ -400,10 +400,10 @@ class UIController {
const recordBtn = document.getElementById('recordBtn');
if (recordBtn) {
if (isRecording) {
recordBtn.querySelector('.btn-text').textContent = `录音中`;
recordBtn.querySelector('.btn-text').textContent = `Recording`;
recordBtn.classList.add('recording');
} else {
recordBtn.querySelector('.btn-text').textContent = '录音';
recordBtn.querySelector('.btn-text').textContent = 'Record';
recordBtn.classList.remove('recording');
}
// Only enable button when microphone is available
@ -423,15 +423,15 @@ class UIController {
// Disable record button
recordBtn.disabled = true;
// Update button text and title
recordBtn.querySelector('.btn-text').textContent = '录音';
recordBtn.title = isHttpNonLocalhost ? '当前由于是http访问,无法录音,只能用文字交互' : '麦克风不可用';
recordBtn.querySelector('.btn-text').textContent = 'Record';
recordBtn.title = isHttpNonLocalhost ? 'Recording unavailable over HTTP; use text input only' : 'Microphone unavailable';
} else {
// If connected, enable record button
const wsHandler = getWebSocketHandler();
if (wsHandler && wsHandler.isConnected()) {
recordBtn.disabled = false;
recordBtn.title = '开始录音';
recordBtn.title = 'Start Recording';
}
}
}
@ -464,7 +464,7 @@ class UIController {
switchLive2DModel() {
const modelSelect = document.getElementById('live2dModelSelect');
if (!modelSelect) {
console.error('模型选择下拉框不存在');
console.error('Model selection dropdown not found');
return;
}
@ -475,17 +475,17 @@ class UIController {
app.live2dManager.switchModel(selectedModel)
.then(success => {
if (success) {
this.addChatMessage(`已切换到模型: ${selectedModel}`, false);
this.addChatMessage(`Switched to model: ${selectedModel}`, false);
} else {
this.addChatMessage('模型切换失败', false);
this.addChatMessage('Model switch failed', false);
}
})
.catch(error => {
console.error('模型切换错误:', error);
this.addChatMessage('模型切换出错', false);
console.error('Model switch error:', error);
this.addChatMessage('Model switch error', false);
});
} else {
this.addChatMessage('Live2D管理器未初始化', false);
this.addChatMessage('Live2D manager not initialized', false);
}
}
@ -561,47 +561,47 @@ class UIController {
};
if (payload.enabled && payload.wakeWords.length === 0) {
this.addChatMessage('启用唤醒词时,至少需要填写一个唤醒词。', false);
this.addChatMessage('At least one wake word is required when enabling wake word detection.', false);
return;
}
const applyWakewordBtn = document.getElementById('applyWakewordBtn');
if (applyWakewordBtn) {
applyWakewordBtn.disabled = true;
applyWakewordBtn.textContent = '应用中...';
applyWakewordBtn.textContent = 'Applying...';
}
try {
// 保存地址到 localStorage
// Save address to localStorage
if (wakewordWsUrlInput && wakewordWsUrlInput.value.trim()) {
localStorage.setItem('xz_tester_wakewordWsUrl', wakewordWsUrlInput.value.trim());
}
// 比较新地址和当前连接地址
// Compare new address with current connection address
const newWsUrl = localStorage.getItem('xz_tester_wakewordWsUrl');
const currentWsUrl = getWakewordBridgeUrl();
const urlChanged = newWsUrl !== currentWsUrl;
if (urlChanged) {
// 地址变了,先确认
const shouldRestart = window.confirm('地址已变更,是否继续?(将断开旧连接并重新连接)');
// Address changed, please confirm
const shouldRestart = window.confirm('Address changed. Continue? (This will disconnect the old connection and reconnect)');
if (!shouldRestart) {
// 恢复 localStorage 里的旧地址
// Restore old address from localStorage
localStorage.setItem('xz_tester_wakewordWsUrl', currentWsUrl);
this.addChatMessage('已取消地址变更。', false);
this.addChatMessage('Address change cancelled.', false);
return;
}
// 断开旧连接
// Disconnect old connection
stopWakewordBridgeListener();
// 启动新连接(自动用新地址)
// Start new connection (automatically use new address)
startWakewordBridgeListener();
// 等 bridge_connected
// Wait for bridge_connected
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('连接新服务器超时'));
reject(new Error('Connection to new server timed out'));
}, 5000);
onNextBridgeConnected(() => {
@ -610,44 +610,44 @@ class UIController {
});
});
// 发配置和重启
// Send config and restart
await requestWakewordBridge('set_wakeword_config', payload);
this.applyWakewordConfig(payload);
await requestWakewordBridge('restart_wakeword_service');
this.addChatMessage('唤醒词配置已保存,唤醒词服务正在重启。', false);
this.addChatMessage('Wake word config saved, restarting wake word service.', false);
} else {
// 地址没变:直接在当前连接操作
// Address unchanged: operate on current connection
const response = await requestWakewordBridge('set_wakeword_config', payload);
this.applyWakewordConfig(response.payload || payload);
const shouldRestart = window.confirm('唤醒词已保存。是否现在重启唤醒词服务以立即生效?');
const shouldRestart = window.confirm('Wake word saved. Restart the wake word service now to apply changes?');
if (!shouldRestart) {
this.addChatMessage('唤醒词配置已保存,可稍后手动重启服务后生效。', false);
this.addChatMessage('Wake word config saved. Restart the service manually later for changes to take effect.', false);
return;
}
await requestWakewordBridge('restart_wakeword_service');
this.addChatMessage('唤醒词配置已保存,唤醒词服务正在重启。', false);
this.addChatMessage('Wake word config saved, restarting wake word service.', false);
}
} catch (error) {
this.addChatMessage(`应用唤醒词失败: ${error.message}`, false);
this.addChatMessage(`Failed to apply wake word: ${error.message}`, false);
} finally {
if (applyWakewordBtn) {
applyWakewordBtn.disabled = false;
applyWakewordBtn.textContent = '应用唤醒词';
applyWakewordBtn.textContent = 'Apply Wake Word';
}
}
}
// Start AI chat session after connection
startAIChatSession() {
this.addChatMessage('连接成功,开始聊天吧~😊', false);
this.addChatMessage('Connection successful, start chatting~😊', false);
// Check microphone availability and show error messages if needed
if (!window.microphoneAvailable) {
if (window.isHttpNonLocalhost) {
this.addChatMessage('⚠️ 当前由于是http访问,无法录音,只能用文字交互', false);
this.addChatMessage('⚠️ Recording is unavailable over HTTP; text interaction only', false);
} else {
this.addChatMessage('⚠️ 麦克风不可用,请检查权限设置,只能用文字交互', false);
this.addChatMessage('⚠️ Microphone unavailable. Check permissions. Text-only interaction enabled.', false);
}
}
// Start recording only if microphone is available
@ -664,13 +664,13 @@ class UIController {
const cameraBtn = document.getElementById('cameraBtn');
if (cameraBtn) {
cameraBtn.classList.add('camera-active');
cameraBtn.querySelector('.btn-text').textContent = '关闭';
cameraBtn.querySelector('.btn-text').textContent = 'Close';
}
} else {
this.addChatMessage('⚠️ 摄像头启动失败,可能被浏览器拒绝', false);
this.addChatMessage('⚠️ Camera startup failed, possibly denied by browser', false);
}
}).catch(error => {
log(`启动摄像头异常: ${error.message}`, 'error');
log(`Camera startup exception: ${error.message}`, 'error');
});
}
}
@ -679,7 +679,7 @@ class UIController {
async handleConnect() {
const wsHandler = getWebSocketHandler();
if (this.isConnecting || (wsHandler && wsHandler.isConnected())) {
log('连接已存在或正在进行,忽略本次拨号请求', 'info');
log('Connection exists or is in progress, ignoring this dial request', 'info');
return;
}
@ -698,7 +698,7 @@ class UIController {
console.log('otaUrl element:', otaUrlInput);
if (!otaUrlInput || !otaUrlInput.value) {
this.addChatMessage('请输入OTA服务器地址', false);
this.addChatMessage('Please enter the OTA server address', false);
return;
}
@ -709,12 +709,12 @@ class UIController {
const dialBtn = document.getElementById('dialBtn');
if (dialBtn) {
dialBtn.classList.add('dial-active');
dialBtn.querySelector('.btn-text').textContent = '连接中...';
dialBtn.querySelector('.btn-text').textContent = 'Connecting...';
dialBtn.disabled = true;
}
// Show connecting message
this.addChatMessage('正在连接服务器...', false);
this.addChatMessage('Connecting to server...', false);
const chatIpt = document.getElementById('chatIpt');
if (chatIpt) {
@ -739,10 +739,10 @@ class UIController {
if (recordBtn) {
if (isRecording) {
recordBtn.classList.add('recording');
recordBtn.querySelector('.btn-text').textContent = '录音中';
recordBtn.querySelector('.btn-text').textContent = 'Recording';
} else {
recordBtn.classList.remove('recording');
recordBtn.querySelector('.btn-text').textContent = '录音';
recordBtn.querySelector('.btn-text').textContent = 'Record';
}
}
};
@ -757,7 +757,7 @@ class UIController {
if (!micAvailable) {
const isHttp = window.isHttpNonLocalhost;
if (isHttp) {
this.addChatMessage('⚠️ 当前由于是http访问,无法录音,只能用文字交互', false);
this.addChatMessage('⚠️ Recording is unavailable over HTTP; text interaction only', false);
}
// Update global state
window.microphoneAvailable = false;
@ -769,13 +769,13 @@ class UIController {
if (!this.dialBtnDisabled) {
dialBtn.disabled = false;
}
dialBtn.querySelector('.btn-text').textContent = '挂断';
dialBtn.querySelector('.btn-text').textContent = 'Hang up';
dialBtn.classList.add('dial-active');
}
this.hideModal('settingsModal');
} else {
throw new Error('OTA连接失败');
throw new Error('OTA connection failed');
}
} catch (error) {
console.error('Connection error details:', {
@ -786,8 +786,8 @@ class UIController {
// Show error message
const errorMessage = error.message.includes('Cannot set properties of null')
? '连接失败:请检查设备连接'
: `连接失败: ${error.message}`;
? 'Connection failed: check device connection'
: `Connection failed: ${error.message}`;
this.addChatMessage(errorMessage, false);
@ -797,7 +797,7 @@ class UIController {
if (!this.dialBtnDisabled) {
dialBtn.disabled = false;
}
dialBtn.querySelector('.btn-text').textContent = '拨号';
dialBtn.querySelector('.btn-text').textContent = 'Dial';
dialBtn.classList.remove('dial-active');
console.log('Dial button state restored successfully');
}
@ -806,27 +806,27 @@ class UIController {
}
}
async triggerWakewordDial(wakeWord = '唤醒词') {
async triggerWakewordDial(wakeWord = 'wake word') {
const wsHandler = getWebSocketHandler();
const now = Date.now();
if (wsHandler && wsHandler.isConnected()) {
log('页面已连接,忽略自动拨号', 'info');
log('Page already connected, ignoring auto-dial', 'info');
return false;
}
if (this.isConnecting || this.dialBtnDisabled) {
log('页面正在连接中,忽略重复唤醒', 'info');
log('Page is connecting, ignoring duplicate wake', 'info');
return false;
}
if (now - this.lastWakewordDialTime < 3000) {
log('唤醒触发过于频繁,忽略本次自动拨号', 'warning');
log('Wake trigger too frequent, ignoring this auto-dial', 'warning');
return false;
}
this.lastWakewordDialTime = now;
this.addChatMessage(`检测到唤醒词“${wakeWord}”,准备连接服务器...`, false);
this.addChatMessage(`Wake word "${wakeWord}" detected, connecting to server...`, false);
await this.handleConnect();
return true;
}
@ -841,9 +841,9 @@ class UIController {
toolDiv.className = 'properties-container';
toolDiv.innerHTML = `
<div class="property-item">
<input type="text" placeholder="工具名称" value="新工具">
<input type="text" placeholder="工具描述" value="工具描述">
<button class="remove-property" onclick="uiController.removeMCPTool('${toolId}')">删除</button>
<input type="text" placeholder="Tool Name" value="New Tool">
<input type="text" placeholder="Tool description" value="Tool description">
<button class="remove-property" onclick="uiController.removeMCPTool('${toolId}')">Delete </button>
</div>
`;

View file

@ -39,7 +39,7 @@ def main() -> int:
app.setup()
app.start()
except Exception as e:
print(f"警告: 唤醒词服务启动失败({e}),测试页面仍可正常使用")
print(f"Warning: Wake word service failed to start ({e}), test page remains usable")
http_server.serve_forever()
except KeyboardInterrupt:
print("test runtime stopped")

View file

@ -121,17 +121,17 @@ def load_config(runtime_root: Path) -> RuntimeConfig:
DEFAULT_WAKE_WORDS = [
"你好小智",
"你好小志",
"小爱同学",
"你好小鑫",
"你好小新",
"小美同学",
"小龙小龙",
"喵喵同学",
"小滨小滨",
"小冰小冰",
"嘿你好呀",
"Hello Xiaozhi",
"Hello Xiaozhi",
"XiaoAi",
"Hello Xiaoxin",
"Hello Xiaoxin",
"Xiaomei",
"Xiaolong",
"MeowMeow",
"XiaoBin XiaoBin",
"XiaoBing XiaoBing",
"Hey there",
]

View file

@ -162,7 +162,7 @@ class TestRuntimeHttpServer:
"wakeword_config",
{},
success=False,
error=f"读取唤醒词配置失败: {exc}",
error=f"Failed to read wake word config: {exc}",
)
def _handle_bridge_request(self, bridge: WakewordEventBridge, raw_message: str) -> str | None:
@ -191,7 +191,7 @@ class TestRuntimeHttpServer:
{},
request_id=request_id,
success=False,
error=f"保存唤醒词配置失败: {exc}",
error=f"Failed to save wake word config: {exc}",
)
if message_type == "restart_wakeword_service":

View file

@ -3,17 +3,17 @@ package xiaozhi.common.constant;
import lombok.Getter;
/**
* 常量
* Copyright (c) 人人开源 All rights reserved.
* Constant
* Copyright (c) RenRen Open Source All rights reserved.
* Website: https://www.renren.io
*/
public interface Constant {
/**
* 成功
* Success
*/
int SUCCESS = 1;
/**
* 失败
* Failed
*/
int FAIL = 0;
/**
@ -21,177 +21,177 @@ public interface Constant {
*/
String OK = "OK";
/**
* 用户标识
* User ID
*/
String USER_KEY = "userId";
/**
* 菜单根节点标识
* Menu root node identifier
*/
Long MENU_ROOT = 0L;
/**
* 部门根节点标识
* Department root node ID
*/
Long DEPT_ROOT = 0L;
/**
* 数据字典根节点标识
* Root node identifier for data dictionary
*/
Long DICT_ROOT = 0L;
/**
* 升序
* Ascending
*/
String ASC = "asc";
/**
* 降序
* Descending
*/
String DESC = "desc";
/**
* 创建时间字段名
* Creation time field name
*/
String CREATE_DATE = "create_date";
/**
* 创建时间字段名
* Creation time field name
*/
String ID = "id";
/**
* 数据权限过滤
* Filter by data permissions
*/
String SQL_FILTER = "sqlFilter";
/**
* 当前页码
* Current page
*/
String PAGE = "page";
/**
* 每页显示记录数
* Records per page
*/
String LIMIT = "limit";
/**
* 排序字段
* Sort field
*/
String ORDER_FIELD = "orderField";
/**
* 排序方式
* Sort order
*/
String ORDER = "order";
/**
* 请求头授权标识
* Request header authorization token
*/
String AUTHORIZATION = "Authorization";
/**
* 服务器密钥
* Server key
*/
String SERVER_SECRET = "server.secret";
/**
* SM2公钥
* SM2 Public Key
*/
String SM2_PUBLIC_KEY = "server.public_key";
/**
* SM2私钥
* SM2 Private Key
*/
String SM2_PRIVATE_KEY = "server.private_key";
/**
* websocket地址
* WebSocket address
*/
String SERVER_WEBSOCKET = "server.websocket";
/**
* mqtt gateway 配置
* MQTT gateway config
*/
String SERVER_MQTT_GATEWAY = "server.mqtt_gateway";
/**
* ota地址
* OTA URL
*/
String SERVER_OTA = "server.ota";
/**
* 是否允许用户注册
* Allow user registration
*/
String SERVER_ALLOW_USER_REGISTER = "server.allow_user_register";
/**
* 下发六位验证码时显示的控制面板地址
* Control panel address displayed when sending a 6-digit verification code
*/
String SERVER_FRONTED_URL = "server.fronted_url";
/**
* 路径分割符
* Path separator
*/
String FILE_EXTENSION_SEG = ".";
/**
* mcp接入点路径
* MCP endpoint path
*/
String SERVER_MCP_ENDPOINT = "server.mcp_endpoint";
/**
* mcp接入点路径
* MCP endpoint path
*/
String SERVER_VOICE_PRINT = "server.voice_print";
/**
* mqtt密钥
* MQTT key
*/
String SERVER_MQTT_SECRET = "server.mqtt_signature_key";
/**
* WebSocket认证开关
* WebSocket authentication toggle
*/
String SERVER_AUTH_ENABLED = "server.auth.enabled";
/**
* 系统功能菜单配置
* System function menu config
*/
String SYSTEM_WEB_MENU = "system-web.menu";
/**
* 无记忆
* No memory
*/
String MEMORY_NO_MEM = "Memory_nomem";
/**
* 仅上报聊天记录(不总结记忆)
* Report chat history only (no memory summarization)
*/
String MEMORY_MEM_REPORT_ONLY = "Memory_mem_report_only";
/**
* Mem0AI记忆
* Mem0AI memory
*/
String MEMORY_MEM0AI = "Memory_mem0ai";
/**
* PowerMem记忆
* PowerMem Memory
*/
String MEMORY_POWERMEM = "Memory_powermem";
/**
* 火山引擎双声道语音克隆
* Volcano Engine dual-channel voice cloning
*/
String VOICE_CLONE_HUOSHAN_DOUBLE_STREAM = "huoshan_double_stream";
/**
* RAG配置类型
* RAG config type
*/
String RAG_CONFIG_TYPE = "RAG";
enum SysBaseParam {
/**
* ICP备案号
* ICP license number
*/
BEIAN_ICP_NUM("server.beian_icp_num"),
/**
* GA备案号
* GA Filing Number
*/
BEIAN_GA_NUM("server.beian_ga_num"),
/**
* 系统名称
* System name
*/
SERVER_NAME("server.name");
@ -207,23 +207,23 @@ public interface Constant {
}
/**
* 训练状态
* Training status
*/
enum TrainStatus {
/**
* 未训练
* Not trained
*/
NOT_TRAINED(0),
/**
* 训练中
* Training
*/
TRAINING(1),
/**
* 已训练
* Trained
*/
TRAINED(2),
/**
* 训练失败
* Training failed
*/
TRAIN_FAILED(3);
@ -279,19 +279,19 @@ public interface Constant {
}
/**
* 数据状态
* Data status
*/
enum DataOperation {
/**
* 插入
* Insert
*/
INSERT("I"),
/**
* 已修改
* Modified
*/
UPDATE("U"),
/**
* 已删除
* Deleted
*/
DELETE("D");
@ -308,9 +308,9 @@ public interface Constant {
@Getter
enum ChatHistoryConfEnum {
IGNORE(0, "不记录"),
RECORD_TEXT(1, "记录文本"),
RECORD_TEXT_AUDIO(2, "文本音频都记录");
IGNORE(0, "Do Not Log"),
RECORD_TEXT(1, "Record text"),
RECORD_TEXT_AUDIO(2, "Log text and audio");
private final int code;
private final String name;
@ -322,21 +322,21 @@ public interface Constant {
}
/**
* 版本号
* Version
*/
public static final String VERSION = "0.9.7";
/**
* 无效固件URL
* Invalid firmware URL
*/
String INVALID_FIRMWARE_URL = "http://xiaozhi.server.com:8002/xiaozhi/otaMag/download/NOT_ACTIVATED_FIRMWARE_THIS_IS_A_INVALID_URL";
/**
* 字典类型
* Dictionary type
*/
enum DictType {
/**
* 手机区号
* Country code
*/
MOBILE_AREA("MOBILE_AREA");

View file

@ -1,11 +1,11 @@
package xiaozhi.common.exception;
/**
* 错误编码,由5位数字组成,前2位为模块编码,后3位为业务编码
* Error code: 5 digits, first 2 for module, last 3 for business logic
* <p>
* 如:10001(10代表系统模块,001代表业务代码)
* e.g., 10001 (10 represents the system module, 001 represents the business code)
* </p>
* Copyright (c) 人人开源 All rights reserved.
* Copyright (c) RenRen Open Source All rights reserved.
* Website: https://www.renren.io
*/
public interface ErrorCode {
@ -44,7 +44,7 @@ public interface ErrorCode {
int DEL_MYSELF_ERROR = 10032;
int DEVICE_CAPTCHA_ERROR = 10033;
// 参数校验相关错误码
// Parameter validation error codes
int PARAM_VALUE_NULL = 10034;
int PARAM_TYPE_NULL = 10035;
int PARAM_TYPE_INVALID = 10036;
@ -56,7 +56,7 @@ public interface ErrorCode {
int OTA_DEVICE_NOT_FOUND = 10041;
int OTA_DEVICE_NEED_BIND = 10042;
// 新增错误编码
// Add error code
int DELETE_DATA_FAILED = 10043;
int USER_NOT_LOGIN = 10044;
int WEB_SOCKET_CONNECT_FAILED = 10045;
@ -67,7 +67,7 @@ public interface ErrorCode {
int TOKEN_GENERATE_ERROR = 10050;
int RESOURCE_NOT_FOUND = 10051;
// 新增错误编码
// Add error code
int DEFAULT_AGENT_NOT_FOUND = 10052;
int AGENT_NOT_FOUND = 10053;
int VOICEPRINT_API_NOT_CONFIGURED = 10054;
@ -80,184 +80,184 @@ public interface ErrorCode {
int ACTIVATION_CODE_EMPTY = 10061;
int ACTIVATION_CODE_ERROR = 10062;
int DEVICE_ALREADY_ACTIVATED = 10063;
// 默认模型删除错误
// Error deleting default model
int DEFAULT_MODEL_DELETE_ERROR = 10064;
// 登录相关错误码
int ADD_DATA_FAILED = 10065; // 新增数据失败
int UPDATE_DATA_FAILED = 10066; // 修改数据失败
int SMS_CAPTCHA_ERROR = 10067; // 短信验证码错误
int MOBILE_REGISTER_DISABLED = 10068; // 未开启手机注册
int USERNAME_NOT_PHONE = 10069; // 用户名不是手机号码
int PHONE_ALREADY_REGISTERED = 10070; // 手机号码已注册
int PHONE_NOT_REGISTERED = 10071; // 手机号码未注册
int USER_REGISTER_DISABLED = 10072; // 不允许用户注册
int RETRIEVE_PASSWORD_DISABLED = 10073; // 未开启找回密码功能
int PHONE_FORMAT_ERROR = 10074; // 手机号码格式不正确
int SMS_CODE_ERROR = 10075; // 手机验证码错误
// Login-related error codes
int ADD_DATA_FAILED = 10065; // Failed to add data
int UPDATE_DATA_FAILED = 10066; // Failed to update data
int SMS_CAPTCHA_ERROR = 10067; // SMS verification code error
int MOBILE_REGISTER_DISABLED = 10068; // Mobile registration not enabled
int USERNAME_NOT_PHONE = 10069; // Username is not a phone number
int PHONE_ALREADY_REGISTERED = 10070; // Phone number already registered
int PHONE_NOT_REGISTERED = 10071; // Phone number not registered
int USER_REGISTER_DISABLED = 10072; // User registration not allowed
int RETRIEVE_PASSWORD_DISABLED = 10073; // Password recovery feature is disabled
int PHONE_FORMAT_ERROR = 10074; // Invalid phone number format
int SMS_CODE_ERROR = 10075; // Incorrect phone verification code
// 字典类型相关错误码
int DICT_TYPE_NOT_EXIST = 10076; // 字典类型不存在
int DICT_TYPE_DUPLICATE = 10077; // 字典类型编码重复
// Dictionary type error codes
int DICT_TYPE_NOT_EXIST = 10076; // Dictionary type does not exist
int DICT_TYPE_DUPLICATE = 10077; // Duplicate dictionary type code
// 资源处理相关错误码
int RESOURCE_READ_ERROR = 10078; // 读取资源失败
// Resource processing error codes
int RESOURCE_READ_ERROR = 10078; // Failed to Load Resource
// 智能体相关错误码
int LLM_INTENT_PARAMS_MISMATCH = 10079; // LLM大模型和Intent意图识别,选择参数不匹配
// Agent-related error codes
int LLM_INTENT_PARAMS_MISMATCH = 10079; // LLM and Intent recognition parameter mismatch
// 声纹相关错误码
int VOICEPRINT_ALREADY_REGISTERED = 10080; // 此声音声纹已经注册
int VOICEPRINT_DELETE_ERROR = 10081; // 删除声纹出现错误
int VOICEPRINT_UPDATE_NOT_ALLOWED = 10082; // 声纹修改不允许,声音已注册
int VOICEPRINT_UPDATE_ADMIN_ERROR = 10083; // 修改声纹错误,请联系管理员
int VOICEPRINT_API_URI_ERROR = 10084; // 声纹接口地址错误
int VOICEPRINT_AUDIO_NOT_BELONG_AGENT = 10085; // 音频数据不属于智能体
int VOICEPRINT_AUDIO_EMPTY = 10086; // 音频数据为空
int VOICEPRINT_REGISTER_REQUEST_ERROR = 10087; // 声纹保存请求失败
int VOICEPRINT_REGISTER_PROCESS_ERROR = 10088; // 声纹保存处理失败
int VOICEPRINT_UNREGISTER_REQUEST_ERROR = 10089; // 声纹注销请求失败
int VOICEPRINT_UNREGISTER_PROCESS_ERROR = 10090; // 声纹注销处理失败
int VOICEPRINT_IDENTIFY_REQUEST_ERROR = 10091; // 声纹识别请求失败
// Voiceprint-related error codes
int VOICEPRINT_ALREADY_REGISTERED = 10080; // Voiceprint for this voice is already registered
int VOICEPRINT_DELETE_ERROR = 10081; // Error deleting voiceprint
int VOICEPRINT_UPDATE_NOT_ALLOWED = 10082; // Voiceprint modification not allowed; voice already registered
int VOICEPRINT_UPDATE_ADMIN_ERROR = 10083; // Voiceprint modification error, please contact the administrator
int VOICEPRINT_API_URI_ERROR = 10084; // Invalid voiceprint API address
int VOICEPRINT_AUDIO_NOT_BELONG_AGENT = 10085; // Audio data does not belong to the agent
int VOICEPRINT_AUDIO_EMPTY = 10086; // Audio data is empty
int VOICEPRINT_REGISTER_REQUEST_ERROR = 10087; // Voiceprint save request failed
int VOICEPRINT_REGISTER_PROCESS_ERROR = 10088; // Voiceprint save processing failed
int VOICEPRINT_UNREGISTER_REQUEST_ERROR = 10089; // Voiceprint deregistration request failed
int VOICEPRINT_UNREGISTER_PROCESS_ERROR = 10090; // Voiceprint deregistration processing failed
int VOICEPRINT_IDENTIFY_REQUEST_ERROR = 10091; // Voiceprint recognition request failed
int LLM_NOT_EXIST = 10092; // 设置的LLM不存在
int MODEL_REFERENCED_BY_AGENT = 10093; // 该模型配置已被智能体引用,无法删除
int LLM_REFERENCED_BY_INTENT = 10094; // 该LLM模型已被意图识别配置引用,无法删除
int LLM_NOT_EXIST = 10092; // Configured LLM does not exist
int MODEL_REFERENCED_BY_AGENT = 10093; // This model config is referenced by an Agent and cannot be deleted
int LLM_REFERENCED_BY_INTENT = 10094; // This LLM model is referenced by intent recognition config and cannot be deleted
// 服务端管理相关错误码
int INVALID_SERVER_ACTION = 10095; // 无效服务端操作
int SERVER_WEBSOCKET_NOT_CONFIGURED = 10096; // 未配置服务端WebSocket地址
int TARGET_WEBSOCKET_NOT_EXIST = 10097; // 目标WebSocket地址不存在
// Server management-related error codes
int INVALID_SERVER_ACTION = 10095; // Invalid server operation
int SERVER_WEBSOCKET_NOT_CONFIGURED = 10096; // Server WebSocket address not configured
int TARGET_WEBSOCKET_NOT_EXIST = 10097; // Target WebSocket address does not exist
// 参数验证相关错误码
int WEBSOCKET_URLS_EMPTY = 10098; // WebSocket地址列表不能为空
int WEBSOCKET_URL_LOCALHOST = 10099; // WebSocket地址不能使用localhost或127.0.0.1
int WEBSOCKET_URL_FORMAT_ERROR = 10100; // WebSocket地址格式不正确
int WEBSOCKET_CONNECTION_FAILED = 10101; // WebSocket连接测试失败
int OTA_URL_EMPTY = 10102; // OTA地址不能为空
int OTA_URL_LOCALHOST = 10103; // OTA地址不能使用localhost或127.0.0.1
int OTA_URL_PROTOCOL_ERROR = 10104; // OTA地址必须以http或https开头
int OTA_URL_FORMAT_ERROR = 10105; // OTA地址必须以/ota/结尾
int OTA_INTERFACE_ACCESS_FAILED = 10106; // OTA接口访问失败
int OTA_INTERFACE_FORMAT_ERROR = 10107; // OTA接口返回内容格式不正确
int OTA_INTERFACE_VALIDATION_FAILED = 10108; // OTA接口验证失败
int MCP_URL_EMPTY = 10109; // MCP地址不能为空
int MCP_URL_LOCALHOST = 10110; // MCP地址不能使用localhost或127.0.0.1
int MCP_URL_INVALID = 10111; // 不是正确的MCP地址
int MCP_INTERFACE_ACCESS_FAILED = 10112; // MCP接口访问失败
int MCP_INTERFACE_FORMAT_ERROR = 10113; // MCP接口返回内容格式不正确
int MCP_INTERFACE_VALIDATION_FAILED = 10114; // MCP接口验证失败
int VOICEPRINT_URL_EMPTY = 10115; // 声纹接口地址不能为空
int VOICEPRINT_URL_LOCALHOST = 10116; // 声纹接口地址不能使用localhost或127.0.0.1
int VOICEPRINT_URL_INVALID = 10117; // 不是正确的声纹接口地址
int VOICEPRINT_URL_PROTOCOL_ERROR = 10118; // 声纹接口地址必须以http或https开头
int VOICEPRINT_INTERFACE_ACCESS_FAILED = 10119; // 声纹接口访问失败
int VOICEPRINT_INTERFACE_FORMAT_ERROR = 10120; // 声纹接口返回内容格式不正确
int VOICEPRINT_INTERFACE_VALIDATION_FAILED = 10121; // 声纹接口验证失败
int MQTT_SECRET_EMPTY = 10122; // mqtt密钥不能为空
int MQTT_SECRET_LENGTH_INSECURE = 10123; // mqtt密钥长度不安全
int MQTT_SECRET_CHARACTER_INSECURE = 10124; // mqtt密钥必须同时包含大小写字母
int MQTT_SECRET_WEAK_PASSWORD = 10125; // mqtt密钥包含弱密码
int DICT_LABEL_DUPLICATE = 10128; // 字典标签重复
int SM2_KEY_NOT_CONFIGURED = 10129; // SM2密钥未配置
int SM2_DECRYPT_ERROR = 10130; // SM2解密失败
int MODEL_TYPE_PROVIDE_CODE_NOT_NULL = 10131; // modelType和provideCode不能为空
// Parameter verification error codes
int WEBSOCKET_URLS_EMPTY = 10098; // WebSocket address list cannot be empty
int WEBSOCKET_URL_LOCALHOST = 10099; // WebSocket address cannot use localhost or 127.0.0.1
int WEBSOCKET_URL_FORMAT_ERROR = 10100; // Invalid WebSocket address format
int WEBSOCKET_CONNECTION_FAILED = 10101; // WebSocket connection test failed
int OTA_URL_EMPTY = 10102; // OTA address cannot be empty
int OTA_URL_LOCALHOST = 10103; // OTA address cannot use localhost or 127.0.0.1
int OTA_URL_PROTOCOL_ERROR = 10104; // OTA address must start with http or https
int OTA_URL_FORMAT_ERROR = 10105; // OTA address must end with /ota/
int OTA_INTERFACE_ACCESS_FAILED = 10106; // OTA API access failed
int OTA_INTERFACE_FORMAT_ERROR = 10107; // OTA interface returned invalid content format
int OTA_INTERFACE_VALIDATION_FAILED = 10108; // OTA API validation failed
int MCP_URL_EMPTY = 10109; // MCP address cannot be empty
int MCP_URL_LOCALHOST = 10110; // MCP address cannot use localhost or 127.0.0.1
int MCP_URL_INVALID = 10111; // Invalid MCP address
int MCP_INTERFACE_ACCESS_FAILED = 10112; // MCP interface access failed
int MCP_INTERFACE_FORMAT_ERROR = 10113; // MCP interface returned invalid content format
int MCP_INTERFACE_VALIDATION_FAILED = 10114; // MCP interface validation failed
int VOICEPRINT_URL_EMPTY = 10115; // Voiceprint API address cannot be empty
int VOICEPRINT_URL_LOCALHOST = 10116; // The voiceprint API address must not use localhost or 127.0.0.1
int VOICEPRINT_URL_INVALID = 10117; // Invalid voiceprint API endpoint
int VOICEPRINT_URL_PROTOCOL_ERROR = 10118; // Voiceprint API address must start with http or https
int VOICEPRINT_INTERFACE_ACCESS_FAILED = 10119; // Failed to access voiceprint API
int VOICEPRINT_INTERFACE_FORMAT_ERROR = 10120; // Invalid response format from voiceprint API
int VOICEPRINT_INTERFACE_VALIDATION_FAILED = 10121; // Voiceprint API validation failed
int MQTT_SECRET_EMPTY = 10122; // MQTT key cannot be empty
int MQTT_SECRET_LENGTH_INSECURE = 10123; // MQTT key length is insecure
int MQTT_SECRET_CHARACTER_INSECURE = 10124; // MQTT key must contain both uppercase and lowercase letters
int MQTT_SECRET_WEAK_PASSWORD = 10125; // MQTT key contains weak password
int DICT_LABEL_DUPLICATE = 10128; // Duplicate dictionary tag
int SM2_KEY_NOT_CONFIGURED = 10129; // SM2 key not configured
int SM2_DECRYPT_ERROR = 10130; // SM2 decryption failed
int MODEL_TYPE_PROVIDE_CODE_NOT_NULL = 10131; // modelType and provideCode cannot be empty
// 聊天记录相关错误码
int CHAT_HISTORY_NO_PERMISSION = 10132; // 没有权限查看该智能体的聊天记录
int CHAT_HISTORY_SESSION_ID_NOT_NULL = 10133; // 会话ID不能为空
int CHAT_HISTORY_AGENT_ID_NOT_NULL = 10134; // 智能体ID不能为空
int CHAT_HISTORY_DOWNLOAD_FAILED = 10135; // 聊天记录下载失败
int DOWNLOAD_LINK_EXPIRED = 10136; // 下载链接已过期或无效
int DOWNLOAD_LINK_INVALID = 10137; // 下载链接无效
int CHAT_ROLE_USER = 10138; // 用户角色
int CHAT_ROLE_AGENT = 10139; // 智能体角色
// Chat history related error codes
int CHAT_HISTORY_NO_PERMISSION = 10132; // No permission to view this Agent's chat history.
int CHAT_HISTORY_SESSION_ID_NOT_NULL = 10133; // Session ID cannot be empty
int CHAT_HISTORY_AGENT_ID_NOT_NULL = 10134; // Agent ID cannot be empty
int CHAT_HISTORY_DOWNLOAD_FAILED = 10135; // Failed to download chat history
int DOWNLOAD_LINK_EXPIRED = 10136; // Download link expired or invalid
int DOWNLOAD_LINK_INVALID = 10137; // Invalid download link
int CHAT_ROLE_USER = 10138; // User role
int CHAT_ROLE_AGENT = 10139; // Agent role
// 声音克隆相关错误码
int VOICE_CLONE_AUDIO_EMPTY = 10140; // 音频文件不能为空
int VOICE_CLONE_NOT_AUDIO_FILE = 10141; // 只支持音频文件
int VOICE_CLONE_AUDIO_TOO_LARGE = 10142; // 音频文件大小不能超过10MB
int VOICE_CLONE_UPLOAD_FAILED = 10143; // 上传失败
int VOICE_CLONE_RECORD_NOT_EXIST = 10144; // 声音克隆记录不存在
int VOICE_RESOURCE_INFO_EMPTY = 10145; // 音色资源信息不能为空
int VOICE_RESOURCE_PLATFORM_NAME_EMPTY = 10146; // 平台名称不能为空
int VOICE_RESOURCE_ID_EMPTY = 10147; // 音色ID不能为空
int VOICE_RESOURCE_ACCOUNT_EMPTY = 10148; // 归属账号不能为空
int VOICE_RESOURCE_DELETE_ID_EMPTY = 10149; // 删除的音色资源ID不能为空
int VOICE_RESOURCE_NO_PERMISSION = 10150; // 您没有权限操作该记录
int VOICE_CLONE_AUDIO_NOT_UPLOADED = 10151; // 请先上传音频文件
int VOICE_CLONE_MODEL_CONFIG_NOT_FOUND = 10152; // 模型配置未找到
int VOICE_CLONE_MODEL_TYPE_NOT_FOUND = 10153; // 模型类型未找到
int VOICE_CLONE_TRAINING_FAILED = 10154; // 训练失败
int VOICE_CLONE_HUOSHAN_CONFIG_MISSING = 10155; // 火山引擎缺少配置
int VOICE_CLONE_RESPONSE_FORMAT_ERROR = 10156; // 响应格式错误
int VOICE_CLONE_REQUEST_FAILED = 10157; // 请求失败
int VOICE_CLONE_PREFIX = 10158; // 复刻音色前缀
int VOICE_ID_ALREADY_EXISTS = 10159; // 音色ID已存在
int VOICE_CLONE_HUOSHAN_VOICE_ID_ERROR = 10160; // 火山引擎音色ID格式错误
// Voice cloning error codes
int VOICE_CLONE_AUDIO_EMPTY = 10140; // Audio file cannot be empty
int VOICE_CLONE_NOT_AUDIO_FILE = 10141; // Audio files only supported
int VOICE_CLONE_AUDIO_TOO_LARGE = 10142; // Audio file size must not exceed 10MB
int VOICE_CLONE_UPLOAD_FAILED = 10143; // Upload failed
int VOICE_CLONE_RECORD_NOT_EXIST = 10144; // Voice cloning record does not exist
int VOICE_RESOURCE_INFO_EMPTY = 10145; // Voice resource info cannot be empty
int VOICE_RESOURCE_PLATFORM_NAME_EMPTY = 10146; // Platform name cannot be empty
int VOICE_RESOURCE_ID_EMPTY = 10147; // Voice ID cannot be empty
int VOICE_RESOURCE_ACCOUNT_EMPTY = 10148; // Account ID cannot be empty
int VOICE_RESOURCE_DELETE_ID_EMPTY = 10149; // Voice resource ID for deletion cannot be empty
int VOICE_RESOURCE_NO_PERMISSION = 10150; // You do not have permission to operate on this record
int VOICE_CLONE_AUDIO_NOT_UPLOADED = 10151; // Please upload an audio file first
int VOICE_CLONE_MODEL_CONFIG_NOT_FOUND = 10152; // Model config not found
int VOICE_CLONE_MODEL_TYPE_NOT_FOUND = 10153; // Model type not found
int VOICE_CLONE_TRAINING_FAILED = 10154; // Training failed
int VOICE_CLONE_HUOSHAN_CONFIG_MISSING = 10155; // Volcano Engine configuration missing
int VOICE_CLONE_RESPONSE_FORMAT_ERROR = 10156; // Invalid response format
int VOICE_CLONE_REQUEST_FAILED = 10157; // Request Failed
int VOICE_CLONE_PREFIX = 10158; // Voice clone prefix
int VOICE_ID_ALREADY_EXISTS = 10159; // Voice ID already exists
int VOICE_CLONE_HUOSHAN_VOICE_ID_ERROR = 10160; // Invalid voice ID format for Volcano Engine
// 设备相关错误码
int MAC_ADDRESS_ALREADY_EXISTS = 10161; // Mac地址已存在
// 模型相关错误码
int MODEL_PROVIDER_NOT_EXIST = 10162; // 供应器不存在
// Device-related error codes
int MAC_ADDRESS_ALREADY_EXISTS = 10161; // MAC address already exists
// Model-related error codes
int MODEL_PROVIDER_NOT_EXIST = 10162; // Provider does not exist
// 知识库相关错误码
int Knowledge_Base_RECORD_NOT_EXISTS = 10163; // 知识库记录不存在
int RAG_CONFIG_NOT_FOUND = 10164; // RAG配置未找到
int RAG_CONFIG_TYPE_ERROR = 10165; // RAG配置类型错误
int RAG_DEFAULT_CONFIG_NOT_FOUND = 10166; // 默认RAG配置未找到
int RAG_API_ERROR = 10167; // RAG调用失败
int UPLOAD_FILE_ERROR = 10168; // 上传文件失败
int NO_PERMISSION = 10169; // 没有权限
int KNOWLEDGE_BASE_NAME_EXISTS = 10170; // 同名知识库已存在
int RAG_API_ERROR_URL_NULL = 10171; // RAG配置中base_url为空,请完善配置
int RAG_API_ERROR_API_KEY_NULL = 10172; // RAG配置中api_key为空,请完善配置
int RAG_API_ERROR_API_KEY_INVALID = 10173; // RAG配置中api_key包含占位符,请替换为实际的API密钥
int RAG_API_ERROR_URL_INVALID = 10174; // RAG配置中base_url格式不正确,请检查协议是否正确
int RAG_DATASET_ID_NOT_NULL = 10176; // RAG配置中dataset_id不能为空
int RAG_MODEL_ID_NOT_NULL = 10177; // RAG配置中model_id不能为空
int RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL = 10178; // RAG配置中dataset_id和model_id不能为空
int RAG_FILE_NAME_NOT_NULL = 10179; // 文件名称不能为空
int RAG_FILE_CONTENT_EMPTY = 10180; // 文件内容不能为空
// Knowledge base error codes
int Knowledge_Base_RECORD_NOT_EXISTS = 10163; // Knowledge base record does not exist
int RAG_CONFIG_NOT_FOUND = 10164; // RAG config not found
int RAG_CONFIG_TYPE_ERROR = 10165; // Invalid RAG config type
int RAG_DEFAULT_CONFIG_NOT_FOUND = 10166; // Default RAG config not found
int RAG_API_ERROR = 10167; // RAG call failed
int UPLOAD_FILE_ERROR = 10168; // File upload failed
int NO_PERMISSION = 10169; // No permission
int KNOWLEDGE_BASE_NAME_EXISTS = 10170; // A knowledge base with the same name already exists
int RAG_API_ERROR_URL_NULL = 10171; // base_url is empty in RAG config, please complete the configuration
int RAG_API_ERROR_API_KEY_NULL = 10172; // api_key is empty in RAG config, please complete the configuration
int RAG_API_ERROR_API_KEY_INVALID = 10173; // The api_key in RAG config contains a placeholder; replace it with the actual API key
int RAG_API_ERROR_URL_INVALID = 10174; // Invalid base_url format in RAG config; check protocol
int RAG_DATASET_ID_NOT_NULL = 10176; // dataset_id cannot be empty in RAG config
int RAG_MODEL_ID_NOT_NULL = 10177; // model_id cannot be empty in RAG config
int RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL = 10178; // dataset_id and model_id cannot be empty in RAG config
int RAG_FILE_NAME_NOT_NULL = 10179; // File name cannot be empty
int RAG_FILE_CONTENT_EMPTY = 10180; // File content cannot be empty
// 设备相关错误码(补充)
int MCA_NOT_NULL = 10175; // mac地址不能为空
// Device-related error codes (supplementary)
int MCA_NOT_NULL = 10175; // MAC address cannot be empty
// 音色克隆(补充)
int VOICE_CLONE_NAME_NOT_NULL = 10181; // 音色克隆名称不能为空
int VOICE_CLONE_AUDIO_NOT_FOUND = 10182; // 音色克隆音频不存在
// Voice cloning (supplement)
int VOICE_CLONE_NAME_NOT_NULL = 10181; // Voice clone name cannot be empty
int VOICE_CLONE_AUDIO_NOT_FOUND = 10182; // Voice cloning audio does not exist
// 智能体模板相关错误码(补充)
int AGENT_TEMPLATE_NOT_FOUND = 10183; // 默认智能体未找到
// Agent template error codes (supplementary)
int AGENT_TEMPLATE_NOT_FOUND = 10183; // Default Agent not found
// 知识库适配器相关错误码
int RAG_ADAPTER_TYPE_NOT_SUPPORTED = 10184; // 不支持的适配器类型
int RAG_CONFIG_VALIDATION_FAILED = 10185; // RAG配置验证失败
int RAG_ADAPTER_CREATION_FAILED = 10186; // 适配器创建失败
int RAG_ADAPTER_INIT_FAILED = 10187; // 适配器初始化失败
int RAG_ADAPTER_CONNECTION_FAILED = 10188; // 适配器连接测试失败
int RAG_ADAPTER_OPERATION_FAILED = 10189; // 适配器操作失败
int RAG_ADAPTER_NOT_FOUND = 10190; // 适配器未找到
int RAG_ADAPTER_CACHE_ERROR = 10191; // 适配器缓存错误
int RAG_ADAPTER_TYPE_NOT_FOUND = 10192; // 适配器类型未找到
// Knowledge base adapter error codes
int RAG_ADAPTER_TYPE_NOT_SUPPORTED = 10184; // Unsupported adapter type
int RAG_CONFIG_VALIDATION_FAILED = 10185; // RAG config validation failed
int RAG_ADAPTER_CREATION_FAILED = 10186; // Adapter creation failed
int RAG_ADAPTER_INIT_FAILED = 10187; // Adapter initialization failed
int RAG_ADAPTER_CONNECTION_FAILED = 10188; // Adapter connection test failed
int RAG_ADAPTER_OPERATION_FAILED = 10189; // Adapter operation failed
int RAG_ADAPTER_NOT_FOUND = 10190; // Adapter Not Found
int RAG_ADAPTER_CACHE_ERROR = 10191; // Adapter cache error
int RAG_ADAPTER_TYPE_NOT_FOUND = 10192; // Adapter type not found
// 设备工具相关错误码
int DEVICE_ID_NOT_NULL = 10193; // 设备ID不能为空
int DEVICE_NOT_EXIST = 10194; // 设备不存在
int OTA_UPLOAD_COUNT_EXCEED = 10195; // OTA上传次数超过限制
// Device tool error codes
int DEVICE_ID_NOT_NULL = 10193; // Device ID cannot be empty
int DEVICE_NOT_EXIST = 10194; // Device not found
int OTA_UPLOAD_COUNT_EXCEED = 10195; // OTA upload count exceeds limit
// 智能体标签相关错误码
int AGENT_TAG_NAME_DUPLICATE = 10196; // 标签名称已存在
int AGENT_TAG_NAME_EMPTY = 10197; // 标签名称不能为空
int AGENT_TAG_NOT_EXIST = 10198; // 标签不存在
// Agent tag-related error codes
int AGENT_TAG_NAME_DUPLICATE = 10196; // Tag name already exists
int AGENT_TAG_NAME_EMPTY = 10197; // Tag name cannot be empty
int AGENT_TAG_NOT_EXIST = 10198; // Tag does not exist
int RAG_DOCUMENT_PARSING_DELETE_ERROR = 10199; // 文档解析中,禁止删除
int RAG_DOCUMENT_PARSING_DELETE_ERROR = 10199; // Document parsing in progress, deletion prohibited
// 智能体MCP相关错误码
int MCP_ACCESS_POINT_ADDRESS_NO_PERMISSION = 10200; // 没有权限查看该智能体的MCP接入点地址
int MCP_ACCESS_POINT_ADDRESS_NOT_CONFIGURED = 10201; // 请联系管理员进入参数管理配置mcp接入点地址
int MCP_ACCESS_POINT_TOOLS_LIST_NO_PERMISSION = 10202; // 没有权限查看该智能体的MCP工具列表
// Agent MCP error codes
int MCP_ACCESS_POINT_ADDRESS_NO_PERMISSION = 10200; // No permission to view the MCP endpoint address for this Agent
int MCP_ACCESS_POINT_ADDRESS_NOT_CONFIGURED = 10201; // Contact admin to configure MCP endpoint address in parameter management
int MCP_ACCESS_POINT_TOOLS_LIST_NO_PERMISSION = 10202; // No permission to view the MCP tool list for this Agent
// 替换词相关错误码
int CORRECT_WORD_FILE_NAME_EXISTS = 10203; // 文件名已存在
int FILE_SIZE_OVER_LIMIT = 10204; // 文件大小超过限制
// Replacement word-related error codes
int CORRECT_WORD_FILE_NAME_EXISTS = 10203; // File name already exists
int FILE_SIZE_OVER_LIMIT = 10204; // File size exceeds limit
}

View file

@ -189,7 +189,7 @@ public class RedisKeys {
}
/**
* 设备通讯录缓存Key
* Device contacts cache key
*/
public static String getAddressBookKey() {
return "device:address_book:all";

View file

@ -57,7 +57,7 @@ import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
import xiaozhi.modules.agent.vo.AgentInfoVO;
import xiaozhi.modules.security.user.SecurityUser;
@Tag(name = "智能体管理")
@Tag(name = "Agent management")
@AllArgsConstructor
@RestController
@RequestMapping("/agent")
@ -97,24 +97,24 @@ public class AgentController {
}
@GetMapping("/list")
@Operation(summary = "获取用户智能体列表")
@Operation(summary = "Get user agent list")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentDTO>> getUserAgents(
@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "searchType", defaultValue = "name") String searchType) {
UserDetail user = SecurityUser.getUser();
// 直接调用整合后的getUserAgents方法,无需再区分搜索和普通查询
// Directly call the integrated getUserAgents method, no need to distinguish between search and standard queries
List<AgentDTO> agents = agentService.getUserAgents(user.getId(), keyword, searchType);
return new Result<List<AgentDTO>>().ok(agents);
}
@GetMapping("/all")
@Operation(summary = "智能体列表(管理员)")
@Operation(summary = "Agent list (Admin)")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true),
@Parameter(name = Constant.PAGE, description = "Current page number, starting from 1", required = true),
@Parameter(name = Constant.LIMIT, description = "Records per page", required = true),
})
public Result<PageData<AgentEntity>> adminAgentList(
@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
@ -123,7 +123,7 @@ public class AgentController {
}
@GetMapping("/{id}")
@Operation(summary = "获取智能体详情")
@Operation(summary = "Get agent details")
@RequiresPermissions("sys:role:normal")
public Result<AgentInfoVO> getAgentById(@PathVariable("id") String id) {
AgentInfoVO agent = agentService.getAgentById(id, SecurityUser.getUserId());
@ -131,7 +131,7 @@ public class AgentController {
}
@PostMapping
@Operation(summary = "创建智能体")
@Operation(summary = "Create Agent")
@RequiresPermissions("sys:role:normal")
public Result<String> save(@RequestBody @Valid AgentCreateDTO dto) {
String agentId = agentService.createAgent(dto);
@ -139,7 +139,7 @@ public class AgentController {
}
@PutMapping("/saveMemory/{macAddress}")
@Operation(summary = "根据设备id更新智能体")
@Operation(summary = "Update agent by device ID")
@RequiresPermissions("sys:role:normal")
public Result<Void> updateByDeviceId(@PathVariable String macAddress, @RequestBody @Valid AgentMemoryDTO dto) {
agentService.updateAgentMemoryByDeviceMacAddress(macAddress, dto, SecurityUser.getUserId());
@ -147,29 +147,29 @@ public class AgentController {
}
@PostMapping("/chat-summary/{sessionId}/save")
@Operation(summary = "根据会话ID生成聊天记录总结并保存(异步执行)")
@Operation(summary = "Generate and save chat history summary based on session ID (async execution)")
public Result<Void> generateAndSaveChatSummary(@PathVariable String sessionId) {
requireSessionAgent(sessionId);
try {
// 异步执行总结生成任务,立即返回成功响应
// Execute summary generation asynchronously and return success immediately
new Thread(() -> {
try {
agentChatSummaryService.generateAndSaveChatSummary(sessionId);
System.out.println("异步执行会话 " + sessionId + " 的聊天记录总结完成");
System.out.println("Async chat history summary completed for session " + sessionId);
} catch (Exception e) {
System.err.println("异步执行会话 " + sessionId + " 的聊天记录总结失败: " + e.getMessage());
System.err.println("Failed to summarize chat history for async session " + sessionId + ": " + e.getMessage());
}
}).start();
// 立即返回成功响应,不等待总结生成完成
// Return success response immediately without waiting for summary generation
return new Result<Void>().ok(null);
} catch (Exception e) {
return new Result<Void>().error("启动异步总结生成任务失败: " + e.getMessage());
return new Result<Void>().error("Failed to start async summary generation task: " + e.getMessage());
}
}
@PostMapping("/chat-title/{sessionId}/generate")
@Operation(summary = "根据会话ID生成聊天标题")
@Operation(summary = "Generate chat title based on session ID")
public Result<Void> generateAndSaveChatTitle(@PathVariable String sessionId) {
requireSessionAgent(sessionId);
agentChatSummaryService.generateAndSaveChatTitle(sessionId);
@ -177,7 +177,7 @@ public class AgentController {
}
@PutMapping("/{id}")
@Operation(summary = "更新智能体")
@Operation(summary = "Update agent")
@RequiresPermissions("sys:role:normal")
public Result<Void> update(@PathVariable String id, @RequestBody @Valid AgentUpdateDTO dto) {
agentService.updateAgentById(id, dto, SecurityUser.getUserId());
@ -185,7 +185,7 @@ public class AgentController {
}
@DeleteMapping("/{id}")
@Operation(summary = "删除智能体")
@Operation(summary = "Delete Agent")
@RequiresPermissions("sys:role:normal")
public Result<Void> delete(@PathVariable String id) {
agentService.deleteAgentById(id, SecurityUser.getUserId());
@ -193,7 +193,7 @@ public class AgentController {
}
@GetMapping("/template")
@Operation(summary = "智能体模板模板列表")
@Operation(summary = "Agent template list")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentTemplateEntity>> templateList() {
List<AgentTemplateEntity> list = agentTemplateService
@ -202,11 +202,11 @@ public class AgentController {
}
@GetMapping("/{id}/sessions")
@Operation(summary = "获取智能体会话列表")
@Operation(summary = "Get Agent session list")
@RequiresPermissions("sys:role:normal")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true),
@Parameter(name = Constant.PAGE, description = "Current page number, starting from 1", required = true),
@Parameter(name = Constant.LIMIT, description = "Records per page", required = true),
})
public Result<PageData<AgentChatSessionDTO>> getAgentSessions(
@PathVariable("id") String id,
@ -218,61 +218,61 @@ public class AgentController {
}
@GetMapping("/{id}/chat-history/{sessionId}")
@Operation(summary = "获取智能体聊天记录")
@Operation(summary = "Get agent chat history")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentChatHistoryDTO>> getAgentChatHistory(
@PathVariable("id") String id,
@PathVariable("sessionId") String sessionId) {
// 获取当前用户
// Get current user
UserDetail user = SecurityUser.getUser();
// 检查权限
// Check permissions
if (!agentService.checkAgentPermission(id, user.getId())) {
return new Result<List<AgentChatHistoryDTO>>().error("没有权限查看该智能体的聊天记录");
return new Result<List<AgentChatHistoryDTO>>().error("No permission to view this Agent's chat history.");
}
// 查询聊天记录
// Query chat history
List<AgentChatHistoryDTO> result = agentChatHistoryService.getChatHistoryBySessionId(id, sessionId);
return new Result<List<AgentChatHistoryDTO>>().ok(result);
}
@GetMapping("/{id}/chat-history/user")
@Operation(summary = "获取智能体聊天记录(用户)")
@Operation(summary = "Get Agent chat history (user)")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentChatHistoryUserVO>> getRecentlyFiftyByAgentId(
@PathVariable("id") String id) {
// 获取当前用户
// Get current user
UserDetail user = SecurityUser.getUser();
// 检查权限
// Check permissions
if (!agentService.checkAgentPermission(id, user.getId())) {
return new Result<List<AgentChatHistoryUserVO>>().error("没有权限查看该智能体的聊天记录");
return new Result<List<AgentChatHistoryUserVO>>().error("No permission to view this Agent's chat history.");
}
// 查询聊天记录
// Query chat history
List<AgentChatHistoryUserVO> data = agentChatHistoryService.getRecentlyFiftyByAgentId(id);
return new Result<List<AgentChatHistoryUserVO>>().ok(data);
}
@GetMapping("/{id}/chat-history/audio")
@Operation(summary = "获取音频内容")
@Operation(summary = "Get audio content")
@RequiresPermissions("sys:role:normal")
public Result<String> getContentByAudioId(
@PathVariable("id") String id) {
requireAudioPermission(id);
// 查询聊天记录
// Query chat history
String data = agentChatHistoryService.getContentByAudioId(id);
return new Result<String>().ok(data);
}
@PostMapping("/audio/{audioId}")
@Operation(summary = "获取音频下载ID")
@Operation(summary = "Get audio download ID")
@RequiresPermissions("sys:role:normal")
public Result<String> getAudioId(@PathVariable("audioId") String audioId) {
requireAudioPermission(audioId);
byte[] audioData = agentChatAudioService.getAudio(audioId);
if (audioData == null) {
return new Result<String>().error("音频不存在");
return new Result<String>().error("Audio not found");
}
String uuid = UUID.randomUUID().toString();
redisUtils.set(RedisKeys.getAgentAudioIdKey(uuid), audioId, AUDIO_PLAY_TOKEN_EXPIRE_SECONDS);
@ -280,7 +280,7 @@ public class AgentController {
}
@GetMapping("/play/{uuid}")
@Operation(summary = "播放音频")
@Operation(summary = "Play audio")
public ResponseEntity<byte[]> playAudio(@PathVariable("uuid") String uuid) {
String audioId = (String) redisUtils.get(RedisKeys.getAgentAudioIdKey(uuid));
@ -300,19 +300,19 @@ public class AgentController {
}
@PostMapping("/tag")
@Operation(summary = "创建标签")
@Operation(summary = "Create Tag")
@RequiresPermissions("sys:role:normal")
public Result<AgentTagEntity> createTag(@RequestBody Map<String, String> params) {
String tagName = params.get("tagName");
if (StringUtils.isBlank(tagName)) {
return new Result<AgentTagEntity>().error("标签名称不能为空");
return new Result<AgentTagEntity>().error("Tag name cannot be empty");
}
AgentTagEntity tag = agentTagService.saveTag(tagName);
return new Result<AgentTagEntity>().ok(tag);
}
@GetMapping("/tag/list")
@Operation(summary = "获取所有标签列表")
@Operation(summary = "Get all tags list")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentTagDTO>> getAllTags() {
List<AgentTagDTO> tags = agentTagService.getAllTags();
@ -320,7 +320,7 @@ public class AgentController {
}
@DeleteMapping("/tag/{id}")
@Operation(summary = "删除标签")
@Operation(summary = "Delete Tag")
@RequiresPermissions("sys:role:normal")
public Result<Void> deleteTag(@PathVariable String id) {
agentTagService.deleteTag(id);
@ -328,7 +328,7 @@ public class AgentController {
}
@GetMapping("/{id}/tags")
@Operation(summary = "获取智能体的标签")
@Operation(summary = "Get agent tags")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentTagDTO>> getAgentTags(@PathVariable String id) {
requireAgentPermission(id);
@ -337,7 +337,7 @@ public class AgentController {
}
@PutMapping("/{id}/tags")
@Operation(summary = "保存智能体的标签")
@Operation(summary = "Save agent tags")
@RequiresPermissions("sys:role:normal")
public Result<Void> saveAgentTags(@PathVariable String id, @RequestBody Map<String, Object> params) {
requireAgentPermission(id);

View file

@ -25,7 +25,7 @@ import xiaozhi.modules.agent.service.AgentSnapshotService;
import xiaozhi.modules.agent.vo.AgentSnapshotVO;
import xiaozhi.modules.security.user.SecurityUser;
@Tag(name = "智能体快照")
@Tag(name = "Agent snapshot")
@AllArgsConstructor
@RestController
@RequestMapping("/agent/{agentId}/snapshots")
@ -34,7 +34,7 @@ public class AgentSnapshotController {
private final AgentService agentService;
@GetMapping
@Operation(summary = "获取智能体快照列表")
@Operation(summary = "Get Agent snapshot list")
@RequiresPermissions("sys:role:normal")
public Result<PageData<AgentSnapshotVO>> page(
@PathVariable String agentId,
@ -44,7 +44,7 @@ public class AgentSnapshotController {
}
@GetMapping("/{snapshotId}")
@Operation(summary = "获取智能体快照详情")
@Operation(summary = "Get agent snapshot details")
@RequiresPermissions("sys:role:normal")
public Result<AgentSnapshotVO> getSnapshot(@PathVariable String agentId, @PathVariable String snapshotId) {
checkPermission(agentId);
@ -52,7 +52,7 @@ public class AgentSnapshotController {
}
@PostMapping("/{snapshotId}/restore")
@Operation(summary = "恢复智能体快照")
@Operation(summary = "Restore agent snapshot")
@RequiresPermissions("sys:role:normal")
public Result<Void> restore(@PathVariable String agentId, @PathVariable String snapshotId,
@RequestBody @Valid AgentSnapshotRestoreDTO request) {
@ -62,7 +62,7 @@ public class AgentSnapshotController {
}
@DeleteMapping("/{snapshotId}")
@Operation(summary = "删除智能体历史快照")
@Operation(summary = "Delete agent history snapshot")
@RequiresPermissions("sys:role:normal")
public Result<Void> deleteSnapshot(@PathVariable String agentId, @PathVariable String snapshotId) {
checkPermission(agentId);
@ -73,7 +73,7 @@ public class AgentSnapshotController {
private void checkPermission(String agentId) {
UserDetail user = SecurityUser.getUser();
if (user == null || !agentService.checkAgentPermission(agentId, user.getId())) {
throw new RenException("没有权限访问该智能体快照");
throw new RenException("No permission to access this agent snapshot");
}
}
}

View file

@ -38,18 +38,18 @@ public interface AgentDao extends BaseDao<AgentEntity> {
AgentInfoVO selectAgentInfoById(@Param("agentId") String agentId);
/**
* 锁定智能体主记录,用于串行化同一智能体的配置写入
* Lock Agent main record to serialize config writes for the same Agent
*
* @param agentId 智能体ID
* @param agentId Agent ID
*/
AgentEntity selectByIdForUpdate(@Param("agentId") String agentId);
/**
* 精确写入快照覆盖的智能体字段,包括目标快照中的 null 值。
* 不更新所属用户、创建信息等不属于快照的字段。
* Precisely overwrite Agent fields in the snapshot, including null values from the target snapshot.
* Do not update fields not included in the snapshot, such as owner user and creation info
*
* @param agent 已应用目标快照的智能体
* @return 受影响行数
* @param agent Agent with target snapshot applied
* @return Number of affected rows
*/
int updateSnapshotFields(@Param("agent") AgentEntity agent);
}

View file

@ -7,7 +7,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "智能体快照数据")
@Schema(description = "Agent snapshot data")
public class AgentSnapshotDataDTO implements Serializable {
private static final long serialVersionUID = 1L;

View file

@ -4,15 +4,15 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "智能体快照分页查询参数")
@Schema(description = "Agent snapshot pagination parameters")
public class AgentSnapshotPageDTO {
@Schema(description = "当前页码,从1开始", example = "1")
@Schema(description = "Current page number, starting from 1", example = "1")
private Integer page = 1;
@Schema(description = "每页数量", example = "10")
@Schema(description = "Items per page", example = "10")
private Integer limit = 10;
@Schema(description = "版本锚点,只查询小于等于该版本号的历史快照", example = "20")
@Schema(description = "Version anchor; query only historical snapshots with version <= this value", example = "20")
private Integer maxVersionNo;
public int pageOrDefault() {

View file

@ -5,9 +5,9 @@ import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
@Schema(description = "智能体快照恢复请求")
@Schema(description = "Agent snapshot restore request")
public class AgentSnapshotRestoreDTO {
@NotBlank
@Schema(description = "预览时由服务端生成的当前配置状态指纹")
@Schema(description = "Current config state fingerprint generated by server during preview")
private String currentStateToken;
}

View file

@ -6,7 +6,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "智能体快照标签")
@Schema(description = "Agent snapshot tag")
public class AgentSnapshotTagDTO implements Serializable {
private static final long serialVersionUID = 1L;

View file

@ -91,13 +91,13 @@ public class AgentUpdateDTO implements Serializable {
@Schema(description = "Context-provider configuration", nullable = true)
private List<ContextProviderDTO> contextProviders;
@Schema(description = "替换词文件ID列表", nullable = true)
@Schema(description = "List of replacement word file IDs", nullable = true)
private List<String> correctWordFileIds;
@Schema(description = "标签名称列表", nullable = true)
@Schema(description = "Tag name list", nullable = true)
private List<String> tagNames;
@Schema(description = "标签ID列表", nullable = true)
@Schema(description = "Tag ID list", nullable = true)
private List<String> tagIds;
@Data

View file

@ -11,28 +11,28 @@ import lombok.Data;
@Data
@TableName("ai_agent_correct_word_mapping")
@Schema(description = "智能体替换词文件关联")
@Schema(description = "Agent replacement word file association")
public class AgentCorrectWordMappingEntity {
@TableId(type = IdType.ASSIGN_UUID)
@Schema(description = "主键")
@Schema(description = "Primary key")
private String id;
@Schema(description = "智能体ID")
@Schema(description = "Agent ID")
private String agentId;
@Schema(description = "替换词文件ID")
@Schema(description = "Replacement word file ID")
private String fileId;
@Schema(description = "创建者")
@Schema(description = "Creator")
private Long creator;
@Schema(description = "创建时间")
@Schema(description = "Creation Time")
private Date createdAt;
@Schema(description = "更新者")
@Schema(description = "Updated by")
private Long updater;
@Schema(description = "更新时间")
@Schema(description = "Update time")
private Date updatedAt;
}

View file

@ -11,43 +11,43 @@ import lombok.Data;
@Data
@TableName("ai_agent_snapshot")
@Schema(description = "智能体配置快照")
@Schema(description = "Agent config snapshot")
public class AgentSnapshotEntity {
@TableId(type = IdType.ASSIGN_UUID)
@Schema(description = "快照ID")
@Schema(description = "Snapshot ID")
private String id;
@Schema(description = "智能体ID")
@Schema(description = "Agent ID")
private String agentId;
@Schema(description = "所属用户ID")
@Schema(description = "User ID")
private Long userId;
@Schema(description = "版本号")
@Schema(description = "Version")
private Integer versionNo;
@Schema(description = "快照数据JSON")
@Schema(description = "Snapshot data JSON")
private String snapshotData;
@Schema(description = "变更字段JSON")
@Schema(description = "Change field JSON")
private String changedFields;
@Schema(description = "快照来源")
@Schema(description = "Snapshot source")
private String source;
@Schema(description = "恢复来源快照ID")
@Schema(description = "Source snapshot ID for restoration")
private String restoreFromSnapshotId;
@Schema(description = "恢复来源版本号")
@Schema(description = "Restore source version")
private Integer restoreFromVersionNo;
@Schema(description = "创建者")
@Schema(description = "Creator")
private Long creator;
@Schema(description = "创建时间")
@Schema(description = "Creation Time")
private Date createdAt;
@Schema(description = "快照数据脱敏规则版本")
@Schema(description = "Snapshot data masking rule version")
private Integer redactionVersion;
}

View file

@ -38,10 +38,10 @@ public interface AgentChatHistoryService extends IRepository<AgentChatHistoryEnt
List<AgentChatHistoryDTO> getChatHistoryBySessionId(String agentId, String sessionId);
/**
* 根据会话ID获取智能体ID
* Get agent ID by session ID
*
* @param sessionId 会话ID
* @return 智能体ID
* @param sessionId Session ID
* @return Agent ID
*/
String getAgentIdBySessionId(String sessionId);
@ -79,10 +79,10 @@ public interface AgentChatHistoryService extends IRepository<AgentChatHistoryEnt
String getContentByAudioId(String audioId);
/**
* 根据音频ID获取智能体ID
* Get agent ID by audio ID
*
* @param audioId 音频ID
* @return 智能体ID
* @param audioId Audio ID
* @return Agent ID
*/
String getAgentIdByAudioId(String audioId);

View file

@ -7,13 +7,13 @@ import com.baomidou.mybatisplus.extension.repository.IRepository;
import xiaozhi.modules.agent.entity.AgentPluginMapping;
/**
* @description 针对表【ai_agent_plugin_mapping(Agent与插件的唯一映射表)】的数据库操作Service
* @description Database operation Service for table [ai_agent_plugin_mapping (Unique mapping between Agent and Plugin)]
* @createDate 2025-05-25 22:33:17
*/
public interface AgentPluginMappingService extends IRepository<AgentPluginMapping> {
/**
* 根据智能体id获取插件参数
* Get plugin parameters by agent ID
*
* @param agentId
* @return
@ -21,16 +21,16 @@ public interface AgentPluginMappingService extends IRepository<AgentPluginMappin
List<AgentPluginMapping> agentPluginParamsByAgentId(String agentId);
/**
* 根据智能体id删除插件参数
* Delete plugin parameters by agent ID
*
* @param agentId
*/
void deleteByAgentId(String agentId);
/**
* 根据插件ID删除所有智能体的插件映射
* Delete plugin mappings for all Agents by plugin ID
*
* @param pluginId 插件ID
* @param pluginId Plugin ID
*/
void deleteByPluginId(String pluginId);
}

View file

@ -104,18 +104,18 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
agent.setChatHistoryConf(Constant.ChatHistoryConfEnum.RECORD_TEXT_AUDIO.getCode());
}
// 查询上下文源配置
// Query context source configuration
AgentContextProviderEntity contextProviderEntity = agentContextProviderService.getByAgentId(id);
if (contextProviderEntity != null) {
agent.setContextProviders(contextProviderEntity.getContextProviders());
}
// 查询替换词文件ID列表
// Query replacement word file ID list
List<String> correctWordFileIds = correctWordFileService.getAgentCorrectWordFileIds(id);
agent.setCorrectWordFileIds(correctWordFileIds);
agent.setCurrentVersionNo(agentSnapshotService.getCurrentVersionNo(id));
// 无需额外查询插件列表,已通过SQL查询出来
// No additional plugin list query needed; already retrieved via SQL
return agent;
}
@ -180,17 +180,17 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
@Override
public boolean insert(AgentEntity entity) {
// 如果ID为空,自动生成一个UUID作为ID
// If ID is empty, generate a UUID as ID
if (entity.getId() == null || entity.getId().trim().isEmpty()) {
entity.setId(UUID.randomUUID().toString().replace("-", ""));
}
// 如果智能体编码为空,自动生成一个带前缀的编码
// If the Agent code is empty, auto-generate a code with a prefix
if (entity.getAgentCode() == null || entity.getAgentCode().trim().isEmpty()) {
entity.setAgentCode("AGT_" + System.currentTimeMillis());
}
// 如果排序字段为空,设置默认值0
// If sort field is empty, set default value to 0
if (entity.getSort() == null) {
entity.setSort(0);
}
@ -232,10 +232,10 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
if (StringUtils.isNotBlank(keyword)) {
queryWrapper.and(w -> {
// 按名称搜索
// Search by name
w.like("agent_name", keyword);
// 按MAC地址搜索:先查设备,再获取对应的智能体ID
// Search by MAC address: query device first, then retrieve the corresponding Agent ID
List<DeviceEntity> devices = Optional
.ofNullable(deviceService.searchDevicesByMacAddress(keyword, userId))
.orElseGet(ArrayList::new);
@ -247,7 +247,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
w.or().in("id", agentIds);
}
// 按标签名搜索
// Search by tag name
List<String> tagAgentIds = agentTagService.getAgentIdsByTagName(keyword);
if (CollUtil.isNotEmpty(tagAgentIds)) {
w.or().in("id", tagAgentIds);
@ -260,7 +260,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
}
/**
* 将AgentEntity转换为AgentDTO
* Convert AgentEntity to AgentDTO
*/
private AgentDTO buildAgentDTO(AgentEntity agent) {
AgentDTO dto = new AgentDTO();
@ -268,28 +268,28 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
dto.setAgentName(agent.getAgentName());
dto.setSystemPrompt(agent.getSystemPrompt());
// 获取 TTS 模型名称
// Get TTS model name
dto.setTtsModelName(modelConfigService.getModelNameById(agent.getTtsModelId()));
// 获取 LLM 模型名称
// Get LLM model name
dto.setLlmModelName(modelConfigService.getModelNameById(agent.getLlmModelId()));
// 获取 VLLM 模型名称
// Get VLLM model name
dto.setVllmModelName(modelConfigService.getModelNameById(agent.getVllmModelId()));
// 获取记忆模型名称
// Get memory model name
dto.setMemModelId(agent.getMemModelId());
// 获取 TTS 音色名称
// Get TTS voice name
dto.setTtsVoiceName(timbreModelService.getTimbreNameById(agent.getTtsVoiceId()));
// 获取智能体最近的最后连接时长
// Get the Agent's recent last connection duration
dto.setLastConnectedAt(deviceService.getLatestLastConnectionTime(agent.getId()));
// 获取设备数量
// Get device count
dto.setDeviceCount(getDeviceCountByAgentId(agent.getId()));
// 获取标签列表
// Get tag list
List<AgentTagEntity> tags = agentTagDao.selectByAgentId(agent.getId());
if (CollUtil.isNotEmpty(tags)) {
dto.setTags(tags.stream().map(this::convertTagToDTO).collect(Collectors.toList()));
@ -311,16 +311,16 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
return 0;
}
// 先从Redis中获取
// Fetch from Redis first
Integer cachedCount = (Integer) redisUtils.get(RedisKeys.getAgentDeviceCountById(agentId));
if (cachedCount != null) {
return cachedCount;
}
// 如果Redis中没有,则从数据库查询
// If not found in Redis, query from the database
Integer deviceCount = agentDao.getDeviceCountByAgentId(agentId);
// 将结果存入Redis
// Store result in Redis
if (deviceCount != null) {
redisUtils.set(RedisKeys.getAgentDeviceCountById(agentId), deviceCount, 60);
}
@ -342,7 +342,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
return hasAgentPermission(agent, userId);
}
// 根据id更新智能体信息
// Update agent info by ID
@Override
@Transactional(rollbackFor = Exception.class)
public void updateAgentById(String agentId, AgentUpdateDTO dto) {
@ -355,7 +355,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
updateAgentById(agentId, dto, userId, true);
}
// 根据id更新智能体信息
// Update agent info by ID
@Override
@Transactional(rollbackFor = Exception.class)
public void updateAgentById(String agentId, AgentUpdateDTO dto, boolean createSnapshot) {
@ -373,14 +373,14 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
requireAgentPermission(lockedAgent, userId);
}
// 锁定后查询现有实体和关联配置
// Query existing entities and associated configs after locking
AgentEntity existingEntity = this.getAgentById(agentId);
if (createSnapshot) {
int currentVersionNo = agentSnapshotService.getCurrentVersionNo(agentId);
agentSnapshotService.createSnapshot(agentId, currentVersionNo == 0 ? "initial" : "current");
}
// 只更新提供的非空字段
// Update only provided non-empty fields
if (dto.getAgentName() != null) {
existingEntity.setAgentName(dto.getAgentName());
}
@ -445,22 +445,22 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
existingEntity.setSort(dto.getSort());
}
// 更新函数插件信息
// Update function plugin info
List<AgentUpdateDTO.FunctionInfo> functions = dto.getFunctions();
if (functions != null) {
// 1. 收集本次提交的 pluginId
// 1. Collect pluginId for this commit
List<String> newPluginIds = functions.stream()
.map(AgentUpdateDTO.FunctionInfo::getPluginId)
.toList();
// 2. 查询当前agent现有的所有映射
// 2. Query all existing mappings for the current agent
List<AgentPluginMapping> existing = agentPluginMappingService.list(
new QueryWrapper<AgentPluginMapping>()
.eq("agent_id", agentId));
Map<String, AgentPluginMapping> existMap = existing.stream()
.collect(Collectors.toMap(AgentPluginMapping::getPluginId, Function.identity()));
// 3. 构造所有要 保存或更新 的实体
// 3. Construct all entities to save or update
List<AgentPluginMapping> allToPersist = functions.stream().map(info -> {
AgentPluginMapping m = new AgentPluginMapping();
m.setAgentId(agentId);
@ -468,13 +468,13 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
m.setParamInfo(JsonUtils.toJsonString(info.getParamInfo()));
AgentPluginMapping old = existMap.get(info.getPluginId());
if (old != null) {
// 已存在,设置id表示更新
// Already exists, setting id indicates update
m.setId(old.getId());
}
return m;
}).toList();
// 4. 拆分:已有ID的走更新,无ID的走插入
// 4. Split: update existing IDs, insert new ones
List<AgentPluginMapping> toUpdate = allToPersist.stream()
.filter(m -> m.getId() != null)
.toList();
@ -489,7 +489,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
agentPluginMappingService.saveBatch(toInsert, IRepository.DEFAULT_BATCH_SIZE);
}
// 5. 删除本次不在提交列表里的插件映射
// 5. Remove plugin mappings not included in this commit list
List<Long> toDelete = existing.stream()
.filter(old -> !newPluginIds.contains(old.getPluginId()))
.map(AgentPluginMapping::getId)
@ -499,23 +499,23 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
}
}
// 设置更新者信息
// Set updater info
UserDetail user = SecurityUser.getUser();
existingEntity.setUpdater(user.getId());
existingEntity.setUpdatedAt(new Date());
// 更新记忆策略
// 删除所有记录
// Update memory policy
// Delete all records
if (existingEntity.getMemModelId() != null && existingEntity.getMemModelId().equals(Constant.MEMORY_NO_MEM)) {
agentChatHistoryService.deleteByAgentId(existingEntity.getId(), true, true);
existingEntity.setSummaryMemory("");
// 删除记忆
// Delete memory
} else if (existingEntity.getMemModelId() != null
&& existingEntity.getMemModelId().equals(Constant.MEMORY_MEM_REPORT_ONLY)) {
existingEntity.setSummaryMemory("");
}
// 更新上下文源配置
// Update context source config
if (dto.getContextProviders() != null) {
AgentContextProviderEntity contextEntity = new AgentContextProviderEntity();
contextEntity.setAgentId(agentId);
@ -523,12 +523,12 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
agentContextProviderService.saveOrUpdateByAgentId(contextEntity);
}
// 更新替换词文件关联
// Update replacement word file associations
if (dto.getCorrectWordFileIds() != null) {
correctWordFileService.saveAgentCorrectWords(agentId, dto.getCorrectWordFileIds());
}
// 更新智能体标签
// Update agent tag
if (dto.getTagNames() != null || dto.getTagIds() != null) {
agentTagService.saveAgentTags(agentId, dto.getTagIds(), dto.getTagNames());
}
@ -567,11 +567,11 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
}
/**
* 验证大语言模型和意图识别的参数是否符合匹配
* Validate parameters for LLM and intent recognition
*
* @param llmModelId 大语言模型id
* @param intentModelId 意图识别id
* @return T 匹配 : F 不匹配
* @param llmModelId LLM model id
* @param intentModelId Intent recognition ID
* @return T match : F no match
*/
private boolean validateLLMIntentParams(String llmModelId, String intentModelId) {
if (StringUtils.isBlank(llmModelId)) {
@ -579,24 +579,24 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
}
ModelConfigEntity llmModelData = modelConfigService.selectById(llmModelId);
String type = llmModelData.getConfigJson().get("type").toString();
// 如果查询大语言模型是openai或者ollama,意图识别选参数都可以
// If the LLM is OpenAI or Ollama, any intent recognition parameter is acceptable
if ("openai".equals(type) || "ollama".equals(type)) {
return true;
}
// 除了openai和ollama的类型,不可以选择id为Intent_function_call(函数调用)的意图识别
// Except for openai and ollama types, do not select the intent recognition with id Intent_function_call (function call)
return !"Intent_function_call".equals(intentModelId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public String createAgent(AgentCreateDTO dto) {
// 转换为实体
// Convert to entity
AgentEntity entity = ConvertUtils.sourceToTarget(dto, AgentEntity.class);
// 获取默认模板
// Get default template
AgentTemplateEntity template = agentTemplateService.getDefaultTemplate();
if (template != null) {
// 设置模板中的默认值
// Set default values in template
entity.setAsrModelId(template.getAsrModelId());
entity.setVadModelId(template.getVadModelId());
entity.setLlmModelId(template.getLlmModelId());
@ -630,13 +630,13 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
entity.setSummaryMemory("");
}
// 根据记忆模型类型设置默认的chatHistoryConf值
// Set the default chatHistoryConf value based on the memory model type
if (template.getMemModelId() != null) {
if (template.getMemModelId().equals("Memory_nomem")) {
// 无记忆功能的模型,默认不记录聊天记录
// Models without memory do not record chat history by default
entity.setChatHistoryConf(0);
} else {
// 有记忆功能的模型,默认记录文本和语音
// Models with memory record text and voice by default
entity.setChatHistoryConf(2);
}
} else {
@ -654,18 +654,18 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
}
}
// 设置用户ID和创建者信息
// Set user ID and creator info
UserDetail user = SecurityUser.getUser();
entity.setUserId(user.getId());
entity.setCreator(user.getId());
entity.setCreatedAt(new Date());
// 保存智能体
// Save Agent
insert(entity);
// 设置默认插件
// Set Default Plugin
List<AgentPluginMapping> toInsert = new ArrayList<>();
// 播放音乐、查天气、查新闻
// Play music, check weather, check news
String[] pluginIds = new String[] { "SYSTEM_PLUGIN_MUSIC", "SYSTEM_PLUGIN_WEATHER",
"SYSTEM_PLUGIN_NEWS_NEWSNOW" };
for (String pluginId : pluginIds) {
@ -687,7 +687,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
mapping.setAgentId(entity.getId());
toInsert.add(mapping);
}
// 保存默认插件
// Save default plugin
agentPluginMappingService.saveBatch(toInsert, IRepository.DEFAULT_BATCH_SIZE);
agentSnapshotService.createSnapshot(entity.getId(), "initial");
return entity.getId();

View file

@ -157,13 +157,13 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
AgentSnapshotEntity snapshot = getSnapshotEntity(agentId, snapshotId);
AgentSnapshotDataDTO data = parseSnapshotData(snapshot.getSnapshotData());
if (data == null) {
throw new RenException("快照数据为空,无法恢复");
throw new RenException("Snapshot data is empty, cannot restore");
}
AgentInfoVO currentAgent = getAgentInfo(agentId);
AgentSnapshotDataDTO currentData = buildSnapshotData(currentAgent);
if (!Objects.equals(buildCurrentStateToken(currentData), currentStateToken)) {
throw new RenException("当前配置已变化,请重新打开恢复预览后再试");
throw new RenException("Current config has changed; reopen recovery preview and try again");
}
AgentSnapshotDataDTO restoreData = preserveCurrentSensitiveValues(data, currentData);
validateSensitiveRestoreIsReversible(currentData, restoreData);
@ -192,7 +192,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
// The row was already locked and verified above. Some MySQL configurations report 0 changed rows
// when a relation-only restore leaves all scalar columns (including second-precision updated_at) unchanged.
if (updatedRows < 0 || updatedRows > 1) {
throw new RenException("智能体快照恢复失败");
throw new RenException("Failed to restore agent snapshot");
}
restoreFunctions(agentId, restoreData.getFunctions());
@ -218,7 +218,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
AgentSnapshotEntity entity = getSnapshotEntity(agentId, snapshotId);
Integer maxVersionNo = agentSnapshotDao.selectMaxVersionNo(agentId);
if (Objects.equals(entity.getVersionNo(), maxVersionNo)) {
throw new RenException("最新历史版本不能删除");
throw new RenException("Latest history version cannot be deleted");
}
deleteById(snapshotId);
}
@ -248,13 +248,13 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
for (AgentSnapshotEntity snapshot : batch) {
Map<String, Object> rawData = JsonUtils.parseObject(snapshot.getSnapshotData(), OBJECT_MAP_TYPE);
if (rawData == null) {
throw new RenException("历史快照数据无法解析,已中止脱敏迁移: " + snapshot.getId());
throw new RenException("Failed to parse historical snapshot data, aborting desensitization migration: " + snapshot.getId());
}
snapshot.setSnapshotData(JsonUtils.toJsonString(redactSensitiveMap(rawData)));
}
int affected = agentSnapshotDao.updateRedactedSnapshots(batch, CURRENT_REDACTION_VERSION);
if (affected < 0 || affected > batch.size()) {
throw new RenException("历史快照批量脱敏迁移失败");
throw new RenException("Failed to batch migrate and desensitize historical snapshots");
}
migrated += affected;
afterId = batch.get(batch.size() - 1).getId();
@ -289,7 +289,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
entity.setRedactionVersion(CURRENT_REDACTION_VERSION);
int inserted = agentSnapshotDao.insertWithNextVersion(entity);
if (inserted != 1) {
throw new RenException("快照版本号生成失败");
throw new RenException("Failed to generate snapshot version number");
}
if (pruneAfterInsert) {
pruneSnapshots(agentId);
@ -309,7 +309,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
private AgentSnapshotEntity getSnapshotEntity(String agentId, String snapshotId) {
AgentSnapshotEntity entity = selectById(snapshotId);
if (entity == null || !Objects.equals(agentId, entity.getAgentId())) {
throw new RenException("快照不存在");
throw new RenException("Snapshot does not exist");
}
return entity;
}
@ -677,7 +677,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
// Tags are global records shared by every agent that references them. Restoring a
// snapshot must not revive a globally deleted tag as a side effect for other agents
// (or tenants); require the user to recreate/select an active tag explicitly.
throw new RenException("快照引用的标签已被删除,无法恢复,请先重新创建或选择标签");
throw new RenException("The tag referenced by the snapshot has been deleted and cannot be restored. Please recreate or select a tag first.");
}
return tag.getId();
}
@ -744,7 +744,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
try {
return SNAPSHOT_OBJECT_MAPPER.readValue(value, AgentSnapshotDataDTO.class);
} catch (Exception exception) {
throw new RenException("快照数据无法解析");
throw new RenException("Failed to parse snapshot data");
}
}
@ -805,7 +805,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
// preservation fails because snapshots intentionally never store secrets.
preserveCurrentSensitiveValues(current, restored);
} catch (RenException exception) {
throw new RenException("目标版本会移除无法写入历史的敏感配置,请先手动处理相关密钥后再恢复");
throw new RenException("The target version removes sensitive configurations that cannot be written to history. Please manually handle related keys before restoring");
}
}
@ -921,7 +921,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
.toList();
Object currentItem = matchingCurrentItems.size() == 1 ? matchingCurrentItems.get(0) : null;
if (currentItem == null && containsSensitiveMaterial(targetItem)) {
throw new RenException("快照中的敏感列表项缺少唯一稳定标识,无法安全恢复");
throw new RenException("Sensitive list items in the snapshot lack a unique stable identifier; safe recovery not possible");
}
result.add(preserveCurrentSensitiveValue(targetItem, currentItem, parentKey));
}
@ -970,7 +970,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
if (current != null && !SECRET_PLACEHOLDER.equals(current)) {
return current;
}
throw new RenException("快照敏感值无法与当前配置可靠匹配");
throw new RenException("Snapshot sensitive values cannot reliably match current config");
}
private Object getMapValue(Map<?, ?> map, String key) {
@ -1009,7 +1009,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
currentProvider = currentByIdentity.get(identity).get(0);
} else if (hasSensitiveUrlParts(targetProvider.getUrl())
|| containsSensitiveMaterial(targetProvider.getHeaders())) {
throw new RenException("上下文源敏感配置缺少唯一 URL 标识,无法安全恢复");
throw new RenException("Context source sensitive config missing unique URL identifier, cannot safely restore");
}
if (targetProvider.getUrl() != null) {
@ -1054,7 +1054,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
List<String> currentIdentities = structuredSensitiveDiscriminatorIdentities(current);
if (targetIdentities.size() != 1 || currentIdentities.size() != 1
|| !Objects.equals(targetIdentities.get(0), currentIdentities.get(0))) {
throw new RenException("快照结构化敏感值的类型标识无法与当前配置唯一匹配");
throw new RenException("Type identifier for structured sensitive values in the snapshot cannot be uniquely matched with the current config");
}
}
@ -1207,14 +1207,14 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
&& (!isStructuredUrlComponent(targetParts.fragment())
|| containsSensitiveUrlParameter(targetParts.fragment())));
if (copiesSensitiveComponent && !Objects.equals(targetPath.redactedBase(), currentPath.redactedBase())) {
throw new RenException("快照 URL 敏感信息无法与当前配置的公开地址标识匹配");
throw new RenException("Snapshot URL sensitive information does not match the current configured public address identifier");
}
String result = buildSensitiveUrl(preserveSensitiveUrlPath(targetParts.base(), currentParts.base(), semanticKey),
preserveUrlComponent(targetParts.userInfo(), currentParts.userInfo()),
preserveSensitiveUrlParameters(targetParts.query(), currentParts.query()),
preserveSensitiveUrlFragment(targetParts.fragment(), currentParts.fragment()));
if (result.contains(SECRET_PLACEHOLDER)) {
throw new RenException("快照 URL 中仍包含脱敏占位符,无法安全恢复");
throw new RenException("Snapshot URL still contains masked placeholders, cannot safely restore");
}
return result;
}
@ -1224,7 +1224,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
return null;
}
if (current == null || current.contains(SECRET_PLACEHOLDER)) {
throw new RenException("快照 URL 中的敏感信息无法与当前配置可靠匹配");
throw new RenException("Sensitive information in the snapshot URL cannot be reliably matched with the current config");
}
return current;
}
@ -1270,11 +1270,11 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
List<UrlParameter> matchingCurrent = currentSensitiveParameters.getOrDefault(identity,
Collections.emptyList());
if (matchingTargets.size() != 1 || matchingCurrent.size() != 1) {
throw new RenException("快照 URL 中的敏感参数无法与当前配置唯一匹配");
throw new RenException("Sensitive parameters in the snapshot URL cannot be uniquely matched with the current config");
}
UrlParameter currentParameter = matchingCurrent.get(0);
if (currentParameter.rawValue().contains(SECRET_PLACEHOLDER)) {
throw new RenException("快照 URL 中的敏感信息无法与当前配置可靠匹配");
throw new RenException("Sensitive information in the snapshot URL cannot be reliably matched with the current config");
}
result.add(new UrlParameter(targetParameter.rawKey(), currentParameter.rawValue(),
currentParameter.hasEquals()));
@ -1393,7 +1393,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
SensitivePathAnalysis current = analyzeSensitiveUrlPath(currentBase, semanticKey, forceCurrentGenericMarker);
if (!Objects.equals(target.redactedBase(), current.redactedBase())
|| target.slots().size() != current.slots().size()) {
throw new RenException("快照 URL 路径敏感信息无法与当前配置的公开标识唯一匹配");
throw new RenException("Sensitive information in the snapshot URL path cannot uniquely match the current configured public identifier");
}
Map<String, List<SensitivePathSlot>> currentSlots = current.slots().stream()
@ -1404,10 +1404,10 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
if (matches.size() != 1 || matches.get(0).secretSegments().isEmpty()
|| matches.get(0).secretSegments().stream()
.anyMatch(secret -> StringUtils.isBlank(secret) || secret.contains(SECRET_PLACEHOLDER))) {
throw new RenException("快照 URL 路径敏感信息无法与当前配置可靠匹配");
throw new RenException("Sensitive information in the snapshot URL path cannot be reliably matched with the current config");
}
if (replacements.put(targetSlot.identity(), matches.get(0)) != null) {
throw new RenException("快照 URL 路径敏感信息存在歧义,无法安全恢复");
throw new RenException("Ambiguous sensitive information in the snapshot URL path; safe recovery not possible");
}
}
return rebuildSensitivePath(target, replacements);
@ -1704,7 +1704,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl<AgentSnapshotDao,
? schemeIndex + 3
: result.startsWith("//") ? 2 : -1;
if (authorityStart < 0) {
throw new RenException("带用户凭据的 URL 格式无效,无法安全恢复");
throw new RenException("Invalid URL format with user credentials; cannot safely recover");
}
result = result.substring(0, authorityStart) + userInfo + "@" + result.substring(authorityStart);
}

View file

@ -23,9 +23,9 @@ public class AgentInfoVO extends AgentEntity
@Schema(description = "Context-provider configuration")
private List<ContextProviderDTO> contextProviders;
@Schema(description = "替换词文件ID列表")
@Schema(description = "List of replacement word file IDs")
private List<String> correctWordFileIds;
@Schema(description = "当前配置版本号")
@Schema(description = "Current config version")
private Integer currentVersionNo;
}

View file

@ -8,27 +8,27 @@ import lombok.Data;
import xiaozhi.modules.agent.dto.AgentSnapshotDataDTO;
@Data
@Schema(description = "智能体配置快照")
@Schema(description = "Agent config snapshot")
public class AgentSnapshotVO {
private String id;
private String agentId;
@Schema(description = "所属用户ID,表示该快照归属的智能体所有者")
@Schema(description = "Owner user ID, indicating the Agent owner of this snapshot")
private Long userId;
private Integer versionNo;
private List<String> changedFields;
private List<String> fieldOrder;
private String source;
@Schema(description = "恢复来源快照ID,仅恢复结果版本有值")
@Schema(description = "Restore source snapshot ID; only set for restored result versions")
private String restoreFromSnapshotId;
@Schema(description = "恢复来源版本号,仅恢复结果版本有值")
@Schema(description = "Restore source version number, only restore if result version has value")
private Integer restoreFromVersionNo;
@Schema(description = "创建者,表示触发本次快照写入的操作人")
@Schema(description = "Creator, indicating the operator who triggered this snapshot write")
private Long creator;
private Date createdAt;
private AgentSnapshotDataDTO snapshotData;
private AgentSnapshotDataDTO afterSnapshotData;
@Schema(description = "恢复预览对应的脱敏当前配置,仅详情接口有值")
@Schema(description = "Restore desensitized current config for preview; only populated in detail API")
private AgentSnapshotDataDTO currentSnapshotData;
@Schema(description = "恢复预览对应的当前配置状态指纹,仅详情接口有值")
@Schema(description = "Fingerprint of current config state corresponding to restore preview, only present in detail API")
private String currentStateToken;
}

View file

@ -46,7 +46,7 @@ public class ConfigController {
}
@PostMapping("correct-words")
@Operation(summary = "获取智能体替换词")
@Operation(summary = "Get agent replacement words")
public Result<Object> getCorrectWords(@Valid @RequestBody CorrectWordsDTO dto) {
ValidatorUtils.validateEntity(dto);
List<String> list = configService.getCorrectWords(dto.getMacAddress());

View file

@ -5,10 +5,10 @@ import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
@Schema(description = "获取智能体替换词DTO")
@Schema(description = "Get agent replacement word DTO")
public class CorrectWordsDTO {
@NotBlank(message = "设备MAC地址不能为空")
@Schema(description = "设备MAC地址")
@NotBlank(message = "Device MAC address cannot be empty")
@Schema(description = "Device MAC address")
private String macAddress;
}

View file

@ -32,19 +32,19 @@ public class SystemInitConfig {
@PostConstruct
public void init() {
// 检查版本号
// Check version
String redisVersion = (String) redisUtils.get(RedisKeys.getVersionKey());
if (!Constant.VERSION.equals(redisVersion)) {
// 如果版本不一致,清空Redis
// If version mismatch, clear Redis
redisUtils.emptyAll();
// 存储新版本号
// Store new version number
redisUtils.set(RedisKeys.getVersionKey(), Constant.VERSION);
}
sysParamsService.initServerSecret();
configService.getConfig(false);
// 初始化设备通讯录缓存
// Initialize device contact cache
deviceAddressBookService.refreshCache();
}
}

View file

@ -5,27 +5,27 @@ import java.util.Map;
public interface ConfigService {
/**
* 获取服务器配置
* Get server config
*
* @param isCache 是否缓存
* @return 配置信息
* @param isCache Whether to cache
* @return Config info
*/
Map<String, Object> getConfig(Boolean isCache);
/**
* 获取智能体模型配置
* Get agent model config
*
* @param macAddress MAC地址
* @param selectedModule 客户端已实例化的模型
* @return 模型配置信息
* @param macAddress MAC address
* @param selectedModule Model instance initialized by the client
* @return Model configuration info
*/
Map<String, Object> getAgentModels(String macAddress, Map<String, String> selectedModule);
/**
* 获取智能体替换词
* Get agent replacement words
*
* @param macAddress 设备MAC地址
* @return 替换词列表,格式如 ["模板1|模板01", "模板2|模板02"]
* @param macAddress Device MAC address
* @return List of replacement words, format: ["template1|template01", "template2|template02"]
*/
List<String> getCorrectWords(String macAddress);
}

View file

@ -34,14 +34,14 @@ import xiaozhi.modules.correctword.vo.CorrectWordFileVO;
@RestController
@RequestMapping("/correct-word")
@Tag(name = "替换词管理")
@Tag(name = "Replacement word management")
@AllArgsConstructor
public class CorrectWordController {
private final CorrectWordFileService correctWordFileService;
@PostMapping("/file")
@Operation(summary = "创建替换词文件")
@Operation(summary = "Create replacement word file")
@RequiresPermissions("sys:role:normal")
public Result<CorrectWordFileVO> createFile(@Valid @RequestBody CorrectWordFileCreateDTO dto) {
CorrectWordFileVO vo = correctWordFileService.createFile(dto);
@ -49,7 +49,7 @@ public class CorrectWordController {
}
@PutMapping("/file/{fileId}")
@Operation(summary = "修改替换词文件")
@Operation(summary = "Modify replacement word file")
@RequiresPermissions("sys:role:normal")
public Result<Void> updateFile(@PathVariable String fileId, @Valid @RequestBody CorrectWordFileCreateDTO dto) {
correctWordFileService.updateFile(fileId, dto);
@ -57,11 +57,11 @@ public class CorrectWordController {
}
@GetMapping("/file/list")
@Operation(summary = "分页获取当前用户替换词文件列表")
@Operation(summary = "Paginate current user's replacement word file list")
@RequiresPermissions("sys:role:normal")
@Parameters({
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true),
@Parameter(name = Constant.PAGE, description = "Current page number, starting from 1", required = true),
@Parameter(name = Constant.LIMIT, description = "Records per page", required = true),
})
public Result<PageData<CorrectWordFileVO>> listFiles(
@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
@ -70,7 +70,7 @@ public class CorrectWordController {
}
@GetMapping("/file/select")
@Operation(summary = "智能体获取当前用户替换词文件列表")
@Operation(summary = "Agent retrieves the current user's replacement word file list")
@RequiresPermissions("sys:role:normal")
public Result<List<CorrectWordFileVO>> listAllFiles() {
List<CorrectWordFileVO> list = correctWordFileService.listAllFiles();
@ -78,7 +78,7 @@ public class CorrectWordController {
}
@GetMapping("/file/download/{fileId}")
@Operation(summary = "下载替换词文件")
@Operation(summary = "Download replacement word file")
@RequiresPermissions("sys:role:normal")
public ResponseEntity<byte[]> downloadFile(@PathVariable String fileId) {
CorrectWordFileVO vo = correctWordFileService.getFileContent(fileId);
@ -96,7 +96,7 @@ public class CorrectWordController {
}
@DeleteMapping("/file/{fileId}")
@Operation(summary = "删除替换词文件")
@Operation(summary = "Delete replacement word file")
@RequiresPermissions("sys:role:normal")
public Result<Void> deleteFile(@PathVariable String fileId) {
correctWordFileService.deleteFile(fileId);
@ -104,7 +104,7 @@ public class CorrectWordController {
}
@PostMapping("/file/batch-delete")
@Operation(summary = "批量删除替换词文件")
@Operation(summary = "Batch delete replacement word files")
@RequiresPermissions("sys:role:normal")
public Result<Void> batchDeleteFiles(@RequestBody List<String> fileIds) {
if (fileIds == null || fileIds.isEmpty()) {

View file

@ -8,17 +8,17 @@ import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
@Data
@Schema(description = "创建替换词文件DTO")
@Schema(description = "Create replacement word file DTO")
public class CorrectWordFileCreateDTO {
@NotBlank(message = "文件名不能为空")
@Schema(description = "文件名")
@NotBlank(message = "File name cannot be empty")
@Schema(description = "File name")
private String fileName;
@NotEmpty(message = "替换词内容不能为空")
@Schema(description = "替换词内容,每条格式:原词|替换词")
@NotEmpty(message = "Replacement word content cannot be empty")
@Schema(description = "Replacement word content, format per line: original|replacement")
private List<String> content;
@Schema(description = "文件大小(字节),不能超过1MB")
@Schema(description = "File size (bytes), must not exceed 1MB")
private Long fileSize;
}

View file

@ -11,31 +11,31 @@ import lombok.Data;
@Data
@TableName("ai_agent_correct_word_file")
@Schema(description = "智能体替换词文件")
@Schema(description = "Agent replacement word file")
public class CorrectWordFileEntity {
@TableId(type = IdType.ASSIGN_UUID)
@Schema(description = "替换词文件ID")
@Schema(description = "Replacement word file ID")
private String id;
@Schema(description = "原始文件名")
@Schema(description = "Original filename")
private String fileName;
@Schema(description = "替换词数量")
@Schema(description = "Replacement word count")
private Integer wordCount;
@Schema(description = "文件原始内容(用于下载)")
@Schema(description = "Original file content (for download)")
private String content;
@Schema(description = "创建者")
@Schema(description = "Creator")
private Long creator;
@Schema(description = "创建时间")
@Schema(description = "Creation Time")
private Date createdAt;
@Schema(description = "更新者")
@Schema(description = "Updated by")
private Long updater;
@Schema(description = "更新时间")
@Schema(description = "Update time")
private Date updatedAt;
}

View file

@ -9,19 +9,19 @@ import lombok.Data;
@Data
@TableName("ai_agent_correct_word_item")
@Schema(description = "替换词词条")
@Schema(description = "Replacement word entries")
public class CorrectWordItemEntity {
@TableId(type = IdType.ASSIGN_UUID)
@Schema(description = "词条ID")
@Schema(description = "Entry ID")
private String id;
@Schema(description = "所属文件ID")
@Schema(description = "Associated file ID")
private String fileId;
@Schema(description = "原词")
@Schema(description = "Original Word")
private String sourceWord;
@Schema(description = "替换词")
@Schema(description = "Replacement word")
private String targetWord;
}

View file

@ -11,86 +11,86 @@ import xiaozhi.modules.correctword.vo.CorrectWordSimpleVO;
public interface CorrectWordFileService {
/**
* 创建替换词文件
* Create replacement word file
*
* @param dto 创建参数
* @return 文件VO
* @param dto creation parameters
* @return File VO
*/
CorrectWordFileVO createFile(CorrectWordFileCreateDTO dto);
/**
* 修改替换词文件(全量替换词条)
* Update replacement word file (full replacement)
*
* @param fileId 文件ID
* @param dto 修改参数
* @param fileId File ID
* @param dto Modification parameters
*/
void updateFile(String fileId, CorrectWordFileCreateDTO dto);
/**
* 获取当前用户的替换词文件列表
* Get the list of replacement-word files for the current user
*
* @param params 分页参数
* @return 分页数据
* @param params Pagination parameters
* @return Paged data
*/
PageData<CorrectWordFileVO> listFiles(Map<String, Object> params);
/**
* 获取当前用户的替换词文件列表(不分页,用于下拉选择)
* Get current user's replacement word file list (no pagination, for dropdown selection)
*
* @return 文件列表
* @return File list
*/
List<CorrectWordFileVO> listAllFiles();
/**
* 获取文件原始内容(用于下载)
* Get raw file content (for download)
*
* @param fileId 文件ID
* @return 文件实体
* @param fileId File ID
* @return File entity
*/
CorrectWordFileVO getFileContent(String fileId);
/**
* 删除替换词文件及其所有词条和关联记录
* Delete the replacement word file and all its entries and associated records
*
* @param fileId 文件ID
* @param fileId File ID
*/
void deleteFile(String fileId);
/**
* 删除智能体关联的替换词文件关联记录(不删文件本身)
* Delete replacement word file association records for Agent (do not delete files)
*
* @param agentId 智能体ID
* @param agentId Agent ID
*/
void deleteMappingsByAgentId(String agentId);
/**
* 获取智能体的所有替换词条(精简版,供设备端使用)
* Get all replacement terms for the Agent (simplified for device use)
*
* @param agentId 智能体ID
* @return 替换词列表
* @param agentId Agent ID
* @return List of replacement words
*/
List<CorrectWordSimpleVO> getAllItemsByAgentId(String agentId);
/**
* 获取智能体关联的替换词文件ID列表
* Get list of replacement word file IDs associated with the Agent
*
* @param agentId 智能体ID
* @return 文件ID列表
* @param agentId Agent ID
* @return List of file IDs
*/
List<String> getAgentCorrectWordFileIds(String agentId);
/**
* 保存智能体关联的替换词文件(全量替换)
* Save replacement words file associated with Agent (full replacement)
*
* @param agentId 智能体ID
* @param fileIds 文件ID列表
* @param agentId Agent ID
* @param fileIds List of file IDs
*/
void saveAgentCorrectWords(String agentId, List<String> fileIds);
/**
* 批量删除替换词文件
* Batch delete replacement word files
*
* @param fileIds 文件ID列表
* @param fileIds List of file IDs
*/
void batchDeleteFiles(List<String> fileIds);
}

View file

@ -43,12 +43,12 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl<CorrectWordFileD
@Override
@Transactional(rollbackFor = Exception.class)
public CorrectWordFileVO createFile(CorrectWordFileCreateDTO dto) {
// 校验文件大小不能超过1MB
// Validate that file size does not exceed 1MB
if (dto.getFileSize() != null && dto.getFileSize() > 1024 * 1024) {
throw new RenException(ErrorCode.FILE_SIZE_OVER_LIMIT);
}
// 校验文件名是否重复
// Validate if filename is duplicate
Long userId = SecurityUser.getUserId();
LambdaQueryWrapper<CorrectWordFileEntity> nameWrapper = new LambdaQueryWrapper<>();
nameWrapper.eq(CorrectWordFileEntity::getCreator, userId)
@ -59,7 +59,7 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl<CorrectWordFileD
List<CorrectWordItemEntity> items = parseContent(dto.getContent());
// 保存文件记录
// Save file records
CorrectWordFileEntity fileEntity = new CorrectWordFileEntity();
fileEntity.setFileName(dto.getFileName());
fileEntity.setWordCount(items.size());
@ -68,7 +68,7 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl<CorrectWordFileD
fileEntity.setCreatedAt(new Date());
correctWordFileDao.insert(fileEntity);
// 设置fileId并批量保存词条
// Set fileId and batch save entries
String fileId = fileEntity.getId();
for (CorrectWordItemEntity item : items) {
item.setFileId(fileId);
@ -88,22 +88,22 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl<CorrectWordFileD
return;
}
// 校验文件名是否重复(排除自身)
// Check for duplicate filenames (excluding self).
Long userId = SecurityUser.getUserId();
LambdaQueryWrapper<CorrectWordFileEntity> nameWrapper = new LambdaQueryWrapper<>();
nameWrapper.eq(CorrectWordFileEntity::getCreator, userId)
.eq(CorrectWordFileEntity::getFileName, dto.getFileName())
.ne(CorrectWordFileEntity::getId, fileId);
if (correctWordFileDao.selectCount(nameWrapper) > 0) {
throw new RenException("文件名已存在:" + dto.getFileName());
throw new RenException("File name already exists:" + dto.getFileName());
}
// 先删除旧词条
// Delete old entries first
LambdaQueryWrapper<CorrectWordItemEntity> deleteWrapper = new LambdaQueryWrapper<>();
deleteWrapper.eq(CorrectWordItemEntity::getFileId, fileId);
correctWordItemDao.delete(deleteWrapper);
// 解析新词条并批量保存
// Parse new entries and batch save
List<CorrectWordItemEntity> items = parseContent(dto.getContent());
if (!items.isEmpty()) {
for (CorrectWordItemEntity item : items) {
@ -112,7 +112,7 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl<CorrectWordFileD
correctWordItemDao.batchInsert(items);
}
// 更新文件记录
// Update file record
fileEntity.setFileName(dto.getFileName());
fileEntity.setWordCount(items.size());
fileEntity.setContent(String.join("\n", dto.getContent()));
@ -155,13 +155,13 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl<CorrectWordFileD
if (fileId == null || fileId.trim().isEmpty()) {
return;
}
// 先删除关联表记录
// Delete associated table records first
agentCorrectWordMappingDao.deleteByFileId(fileId);
// 删除词条
// Delete entry
LambdaQueryWrapper<CorrectWordItemEntity> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CorrectWordItemEntity::getFileId, fileId);
correctWordItemDao.delete(wrapper);
// 删除文件
// Delete File
correctWordFileDao.deleteById(fileId);
}
@ -173,7 +173,7 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl<CorrectWordFileD
@Override
public List<CorrectWordSimpleVO> getAllItemsByAgentId(String agentId) {
// 通过关联表获取文件ID列表
// Get file ID list via association table
List<AgentCorrectWordMappingEntity> mappings = agentCorrectWordMappingDao.selectByAgentId(agentId);
if (mappings == null || mappings.isEmpty()) {
return new ArrayList<>();
@ -182,7 +182,7 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl<CorrectWordFileD
.map(AgentCorrectWordMappingEntity::getFileId)
.collect(Collectors.toList());
// 根据文件ID列表查询词条
// Query entries by file ID list
LambdaQueryWrapper<CorrectWordItemEntity> wrapper = new LambdaQueryWrapper<>();
wrapper.in(CorrectWordItemEntity::getFileId, fileIds);
List<CorrectWordItemEntity> entities = correctWordItemDao.selectList(wrapper);
@ -203,14 +203,14 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl<CorrectWordFileD
@Override
@Transactional(rollbackFor = Exception.class)
public void saveAgentCorrectWords(String agentId, List<String> fileIds) {
// 先删除旧的关联记录
// Delete old association records first
agentCorrectWordMappingDao.deleteByAgentId(agentId);
if (fileIds == null || fileIds.isEmpty()) {
return;
}
// 批量插入新的关联记录
// Batch insert new association records
Long userId = SecurityUser.getUserId();
Date now = new Date();
List<AgentCorrectWordMappingEntity> mappings = new ArrayList<>();
@ -242,7 +242,7 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl<CorrectWordFileD
}
/**
* 解析替换词内容,每条格式:原词|替换词
* Parse replacement words, each line format: original|replacement
*/
private List<CorrectWordItemEntity> parseContent(List<String> lines) {
List<CorrectWordItemEntity> items = new ArrayList<>();

View file

@ -7,24 +7,24 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "替换词文件列表VO")
@Schema(description = "Replacement word file list VO")
public class CorrectWordFileVO {
@Schema(description = "替换词文件ID")
@Schema(description = "Replacement word file ID")
private String id;
@Schema(description = "原始文件名")
@Schema(description = "Original filename")
private String fileName;
@Schema(description = "替换词数量")
@Schema(description = "Replacement word count")
private Integer wordCount;
@Schema(description = "替换词内容,每行一条")
@Schema(description = "Replacement word content, one per line")
private List<String> content;
@Schema(description = "创建时间")
@Schema(description = "Creation Time")
private Date createdAt;
@Schema(description = "更新时间")
@Schema(description = "Update time")
private Date updatedAt;
}

View file

@ -4,12 +4,12 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "替换词精简VO(设备端使用)")
@Schema(description = "Simplified replacement-word VO (device-side)")
public class CorrectWordSimpleVO {
@Schema(description = "原词")
@Schema(description = "Original Word")
private String sourceWord;
@Schema(description = "替换词")
@Schema(description = "Replacement word")
private String targetWord;
}

View file

@ -37,7 +37,7 @@ import xiaozhi.modules.device.vo.UserShowDeviceListVO;
import xiaozhi.modules.security.user.SecurityUser;
import xiaozhi.modules.sys.service.SysParamsService;
@Tag(name = "设备管理")
@Tag(name = "Device Management")
@RestController
@RequestMapping("/device")
public class DeviceController {
@ -55,7 +55,7 @@ public class DeviceController {
}
@PostMapping("/bind/{agentId}/{deviceCode}")
@Operation(summary = "绑定设备")
@Operation(summary = "Bind device")
@RequiresPermissions("sys:role:normal")
public Result<Void> bindDevice(@PathVariable String agentId, @PathVariable String deviceCode) {
deviceService.deviceActivation(agentId, deviceCode);
@ -63,13 +63,13 @@ public class DeviceController {
}
@PostMapping("/register")
@Operation(summary = "注册设备")
@Operation(summary = "Register device")
public Result<String> registerDevice(@RequestBody DeviceRegisterDTO deviceRegisterDTO) {
String macAddress = deviceRegisterDTO.getMacAddress();
if (StringUtils.isBlank(macAddress)) {
return new Result<String>().error(ErrorCode.MCA_NOT_NULL);
}
// 生成六位验证码
// Generate 6-digit verification code
String code;
String key;
String existsMac = null;
@ -84,7 +84,7 @@ public class DeviceController {
}
@GetMapping("/bind/{agentId}")
@Operation(summary = "获取已绑定设备")
@Operation(summary = "Get bound devices")
@RequiresPermissions("sys:role:normal")
public Result<List<UserShowDeviceListVO>> getUserDevices(@PathVariable String agentId) {
UserDetail user = SecurityUser.getUser();
@ -93,18 +93,18 @@ public class DeviceController {
}
@PostMapping("/bind/{agentId}")
@Operation(summary = "设备在线接口")
@Operation(summary = "Device online API")
@RequiresPermissions("sys:role:normal")
public Result<String> forwardToMqttGateway(@PathVariable String agentId, @RequestBody String requestBody) {
try {
return new Result<String>().ok(deviceService.getDeviceOnlineData(agentId));
} catch (Exception e) {
return new Result<String>().error("转发请求失败: " + e.getMessage());
return new Result<String>().error("Forward request failed: " + e.getMessage());
}
}
@PostMapping("/unbind")
@Operation(summary = "解绑设备")
@Operation(summary = "Unbind device")
@RequiresPermissions("sys:role:normal")
public Result<Void> unbindDevice(@RequestBody DeviceUnBindDTO unDeviveBind) {
UserDetail user = SecurityUser.getUser();
@ -113,16 +113,16 @@ public class DeviceController {
}
@PutMapping("/update/{id}")
@Operation(summary = "更新设备信息")
@Operation(summary = "Update device info")
@RequiresPermissions("sys:role:normal")
public Result<Void> updateDeviceInfo(@PathVariable String id, @Valid @RequestBody DeviceUpdateDTO deviceUpdateDTO) {
DeviceEntity entity = deviceService.selectById(id);
if (entity == null) {
return new Result<Void>().error("设备不存在");
return new Result<Void>().error("Device not found");
}
UserDetail user = SecurityUser.getUser();
if (!entity.getUserId().equals(user.getId())) {
return new Result<Void>().error("设备不存在");
return new Result<Void>().error("Device not found");
}
BeanUtils.copyProperties(deviceUpdateDTO, entity);
if (!deviceService.updateById(entity)) {
@ -132,7 +132,7 @@ public class DeviceController {
}
@PostMapping("/manual-add")
@Operation(summary = "手动添加设备")
@Operation(summary = "Add device manually")
@RequiresPermissions("sys:role:normal")
public Result<Void> manualAddDevice(@RequestBody @Valid DeviceManualAddDTO dto) {
UserDetail user = SecurityUser.getUser();
@ -141,7 +141,7 @@ public class DeviceController {
}
@PostMapping("/tools/list/{deviceId}")
@Operation(summary = "获取设备工具列表")
@Operation(summary = "Get device tool list")
@RequiresPermissions("sys:role:normal")
public Result<Object> getDeviceTools(@PathVariable String deviceId) {
Object toolsData = deviceService.getDeviceTools(deviceId);
@ -153,7 +153,7 @@ public class DeviceController {
}
@PostMapping("/tools/call/{deviceId}")
@Operation(summary = "调用设备工具")
@Operation(summary = "Invoke Device Tool")
@RequiresPermissions("sys:role:normal")
public Result<Object> callDeviceTool(@PathVariable String deviceId,
@Valid @RequestBody DeviceToolsCallReqDTO request) {
@ -171,44 +171,44 @@ public class DeviceController {
}
@GetMapping("/address-book/{macAddress}")
@Operation(summary = "获取设备通讯录")
@Operation(summary = "Get device contacts")
@RequiresPermissions("sys:role:normal")
public Result<Object> getAddressBook(@PathVariable String macAddress) {
return new Result<Object>().ok(deviceAddressBookService.getAddressBookList(macAddress));
}
@GetMapping("/address-book/call")
@Operation(summary = "根据昵称发起呼叫")
@Operation(summary = "Initiate call by nickname")
public Result<Map<String, Object>> callByNickname(String callerMac, String nickname,
@RequestParam(required = false, defaultValue = "false") boolean answer) {
Map<String, Object> result = deviceAddressBookService.callByNickname(callerMac, nickname, answer);
if (result == null) {
return new Result<Map<String, Object>>().error("未找到对应设备");
return new Result<Map<String, Object>>().error("Corresponding device not found");
}
return new Result<Map<String, Object>>().ok(result);
}
@PutMapping("/address-book/alias")
@Operation(summary = "更新设备通讯录别名")
@Operation(summary = "Update device contact alias")
@RequiresPermissions("sys:role:normal")
public Result<Void> updateAlias(@Valid @RequestBody DeviceAddressBookAliasDTO dto) {
UserDetail user = SecurityUser.getUser();
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(dto.getMacAddress());
if (callerDevice == null || !callerDevice.getUserId().equals(user.getId())) {
return new Result<Void>().error("无权限操作该设备");
return new Result<Void>().error("No permission to operate this device");
}
deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), dto.getAlias(), null);
return new Result<Void>();
}
@PutMapping("/address-book/permission")
@Operation(summary = "更新设备通讯录权限")
@Operation(summary = "Update device contact permissions")
@RequiresPermissions("sys:role:normal")
public Result<Void> updatePermission(@Valid @RequestBody DeviceAddressBookPermissionDTO dto) {
UserDetail user = SecurityUser.getUser();
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(dto.getMacAddress());
if (callerDevice == null || !callerDevice.getUserId().equals(user.getId())) {
return new Result<Void>().error("无权限操作该设备");
return new Result<Void>().error("No permission to operate this device");
}
deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), null, dto.getHasPermission());
return new Result<Void>();

View file

@ -13,27 +13,27 @@ import xiaozhi.modules.device.entity.DeviceAddressBookEntity;
public interface DeviceAddressBookDao extends BaseMapper<DeviceAddressBookEntity> {
/**
* 新增设备通讯录记录
* Add device contact record
*/
int insertAddressBook(DeviceAddressBookEntity entity);
/**
* 获取设备通讯录列表
* Get device contacts list
*/
List<DeviceAddressBookEntity> getAddressBookList(@Param("macAddress") String macAddress);
/**
* 更新别名
* Update alias
*/
void updateAlias(@Param("macAddress") String macAddress, @Param("targetMac") String targetMac, @Param("alias") String alias);
/**
* 更新权限
* Update permissions
*/
void updatePermission(@Param("macAddress") String macAddress, @Param("targetMac") String targetMac, @Param("hasPermission") Boolean hasPermission);
/**
* 批量删除设备相关的通讯录记录
* Batch delete contact records associated with devices
*/
void deleteByMacAddresses(@Param("macAddresses") List<String> macAddresses);
}

View file

@ -5,17 +5,17 @@ import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
@Schema(description = "更新设备通讯录别名")
@Schema(description = "Update device contact alias")
public class DeviceAddressBookAliasDTO {
@NotBlank(message = "MAC地址不能为空")
@Schema(description = "本设备MAC地址")
@NotBlank(message = "MAC address cannot be empty")
@Schema(description = "This device MAC address")
private String macAddress;
@NotBlank(message = "目标MAC地址不能为空")
@Schema(description = "对方设备MAC地址")
@NotBlank(message = "Target MAC address cannot be empty")
@Schema(description = "Peer device MAC address")
private String targetMac;
@Schema(description = "我对对方的称呼")
@Schema(description = "My name for the other party")
private String alias;
}

View file

@ -5,17 +5,17 @@ import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
@Schema(description = "更新设备通讯录权限")
@Schema(description = "Update device contact permissions")
public class DeviceAddressBookPermissionDTO {
@NotBlank(message = "MAC地址不能为空")
@Schema(description = "本设备MAC地址")
@NotBlank(message = "MAC address cannot be empty")
@Schema(description = "This device MAC address")
private String macAddress;
@NotBlank(message = "目标MAC地址不能为空")
@Schema(description = "对方设备MAC地址")
@NotBlank(message = "Target MAC address cannot be empty")
@Schema(description = "Peer device MAC address")
private String targetMac;
@Schema(description = "是否有权限呼叫")
@Schema(description = "Has call permission")
private Boolean hasPermission;
}

View file

@ -15,35 +15,35 @@ import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("ai_device_address_book")
@Schema(description = "设备通讯录")
@Schema(description = "Device contacts")
public class DeviceAddressBookEntity {
@TableId(type = IdType.INPUT)
@Schema(description = "本设备MAC地址")
@Schema(description = "This device MAC address")
private String macAddress;
@Schema(description = "对方设备MAC地址")
@Schema(description = "Peer device MAC address")
private String targetMac;
@Schema(description = "我对对方的称呼")
@Schema(description = "My name for the other party")
private String alias;
@Schema(description = "是否有权限呼叫")
@Schema(description = "Has call permission")
private Boolean hasPermission;
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建人")
@Schema(description = "Creator")
private Long creator;
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建时间")
@Schema(description = "Creation Time")
private Date createDate;
@TableField(fill = FieldFill.INSERT_UPDATE)
@Schema(description = "更新人")
@Schema(description = "Updated by")
private Long updater;
@TableField(fill = FieldFill.INSERT_UPDATE)
@Schema(description = "更新时间")
@Schema(description = "Update time")
private Date updateDate;
}

View file

@ -8,45 +8,45 @@ import xiaozhi.modules.device.entity.DeviceAddressBookEntity;
public interface DeviceAddressBookService {
/**
* 获取设备通讯录列表
* Get device contacts list
*/
List<DeviceAddressBookEntity> getAddressBookList(String macAddress);
/**
* 获取所有设备的通讯录(全局缓存用)
* Get contacts for all devices (for global cache)
*/
Map<String, Map<String, String>> getAllAddressBooks();
/**
* 更新别名
* Update alias
*/
void updateAlias(String macAddress, String targetMac, String alias);
/**
* 更新权限
* Update permissions
*/
void updatePermission(String macAddress, String targetMac, Boolean hasPermission);
/**
* 添加或更新通讯录记录
* Add or update contact record
*/
void saveOrUpdate(String macAddress, String targetMac, String alias, Boolean hasPermission);
/**
* 刷新通讯录缓存
* Refresh contacts cache
*/
void refreshCache();
/**
* 根据昵称发起呼叫
* @param callerMac 主叫方MAC地址
* @param nickname 被叫方昵称
* @param isAnswer 是否为接听模式(跳过权限检查)
* Initiate call by nickname
* @param callerMac Caller MAC address
* @param nickname Callee nickname
* @param isAnswer Whether in answer mode (skip permission check)
*/
Map<String, Object> callByNickname(String callerMac, String nickname, boolean isAnswer);
/**
* 批量删除设备相关的通讯录记录
* Batch delete contact records associated with devices
*/
void deleteByMacAddresses(List<String> macAddresses);
}

View file

@ -15,126 +15,126 @@ import xiaozhi.modules.device.vo.UserShowDeviceListVO;
public interface DeviceService extends BaseService<DeviceEntity> {
/**
* 获取设备在线数据
* Get device online data
*/
String getDeviceOnlineData(String agentId);
/**
* 检查设备是否激活
* Check if device is active
*/
DeviceReportRespDTO checkDeviceActive(String macAddress, String clientId,
DeviceReportReqDTO deviceReport);
/**
* 获取用户指定智能体的设备列表,
* Retrieve device list for user-specified Agent,
*/
List<DeviceEntity> getUserDevices(Long userId, String agentId);
/**
* 获取用户指定智能体的设备列表(带时区处理),
* Get device list for user-specified agent (with timezone handling),
*/
List<UserShowDeviceListVO> getUserDeviceList(Long userId, String agentId);
/**
* 解绑设备
* Unbind device
*/
void unbindDevice(Long userId, String deviceId);
/**
* 设备激活
* Device Activation
*/
Boolean deviceActivation(String agentId, String activationCode);
/**
* 删除此用户的所有设备
* Delete all devices for this user
*
* @param userId 用户id
* @param userId User ID
*/
void deleteByUserId(Long userId);
/**
* 删除指定智能体关联的所有设备
* Delete all devices associated with the specified Agent
*
* @param agentId 智能体id
* @param agentId Agent ID
*/
void deleteByAgentId(String agentId);
/**
* 获取指定用户的设备数量
* Get device count for specified user
*
* @param userId 用户id
* @return 设备数量
* @param userId User ID
* @return Device count
*/
Long selectCountByUserId(Long userId);
/**
* 分页获取全部设备信息
* Paginate to retrieve all device information
*
* @param dto 分页查找参数
* @return 用户列表分页数据
* @param dto Pagination search parameters
* @return Paginated user list data
*/
PageData<UserShowDeviceListVO> page(DevicePageUserDTO dto);
/**
* 根据MAC地址获取设备信息
* Get device info by MAC address
*
* @param macAddress MAC地址
* @return 设备信息
* @param macAddress MAC address
* @return Device info
*/
DeviceEntity getDeviceByMacAddress(String macAddress);
/**
* 根据设备ID获取激活码
* Get activation code by device ID
*
* @param deviceId 设备ID
* @return 激活码
* @param deviceId Device ID
* @return activation code
*/
String geCodeByDeviceId(String deviceId);
/**
* 获取这个智能体设备理的最近的最后连接时间
* Get the last connection time for this agent device
*
* @param agentId 智能体id
* @return 返回设备最近的最后连接时间
* @param agentId Agent ID
* @return Returns the device's most recent last connection time
*/
Date getLatestLastConnectionTime(String agentId);
/**
* 手动添加设备
* Add device manually
*/
void manualAddDevice(Long userId, DeviceManualAddDTO dto);
/**
* 更新设备连接信息
* Update device connection info
*/
void updateDeviceConnectionInfo(String agentId, String deviceId, String appVersion);
/**
* 生成WebSocket认证token
* Generate WebSocket authentication token
*
* @param clientId 客户端ID
* @param username 用户名(通常为deviceId)
* @return 认证token字符串
* @throws Exception 生成token时的异常
* @param clientId Client ID
* @param username Username (typically deviceId)
* @return Authentication token string
* @throws Exception Exception during token generation
*/
String generateWebSocketToken(String clientId, String username) throws Exception;
/**
* 根据MAC地址搜索设备
* Search device by MAC address
*
* @param macAddress MAC地址关键词
* @param userId 用户ID
* @return 设备列表
* @param macAddress MAC address keyword
* @param userId User ID
* @return Device list
*/
List<DeviceEntity> searchDevicesByMacAddress(String macAddress, Long userId);
/**
* 获取设备工具列表
* Get device tool list
*/
Object getDeviceTools(String deviceId);
/**
* 调用设备工具
* Invoke Device Tool
*/
Object callDeviceTool(String deviceId, String toolName, Map<String, Object> arguments);

View file

@ -59,27 +59,27 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
Map<String, Map<String, String>> allBooks = getAllAddressBooks();
if (isAnswer) {
return postToMqtt("/api/call/accept", Map.of("mac", callerMac), "接听");
return postToMqtt("/api/call/accept", Map.of("mac", callerMac), "Answer");
}
// 主动呼叫模式
// Active call mode
Map<String, String> callerBook = allBooks.get(callerMac.toLowerCase());
if (callerBook == null) {
return errorResult("未找到备注为'" + nickname + "'的设备");
return errorResult("Device with nickname '" + nickname + "' not found");
}
String targetMacWithPerm = callerBook.get(nickname);
if (targetMacWithPerm == null) {
return errorResult("未找到备注为'" + nickname + "'的设备");
return errorResult("Device with nickname '" + nickname + "' not found");
}
String[] parts = targetMacWithPerm.split("\\|");
String targetMac = parts[0];
boolean hasPermission = parts.length > 1 && "1".equals(parts[1]);
if (!hasPermission) {
return errorResult("呼叫失败,您没有权限呼叫该设备");
return errorResult("Call failed: you do not have permission to call this device");
}
// 获取目标设备如何称呼主叫方
// Get how the target device addresses the caller
Map<String, String> targetBook = allBooks.get(targetMac.toLowerCase());
String callerNickname = null;
if (targetBook != null) {
@ -94,7 +94,7 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
return postToMqtt("/api/call/request",
Map.of("caller_mac", callerMac, "target_mac", targetMac, "caller_nickname", callerNickname),
"呼叫");
"Call");
}
@Override
@ -109,20 +109,20 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
String alias = entity.getAlias();
Boolean hasPermission = entity.getHasPermission();
// 构建正向映射: A对B的映射 nickname -> macB|permission
// Build forward mapping: A-to-B mapping nickname -> macB|permission
if (alias != null && !alias.isEmpty()) {
result.computeIfAbsent(macA, k -> new HashMap<>());
String permStr = (hasPermission != null && hasPermission) ? "1" : "0";
result.get(macA).put(alias, macB + "|" + permStr);
}
// 构建反向记录用于查找B对A的称呼
// Build reverse records to look up how B refers to A
if (alias != null && !alias.isEmpty()) {
reverseMap.put(macB + ":" + macA, alias);
}
}
// 构建反向映射: B对A的映射 macA -> nickname
// Build reverse mapping: B-to-A mapping macA -> nickname
for (DeviceAddressBookEntity entity : allRecords) {
String macA = entity.getMacAddress().toLowerCase();
String macB = entity.getTargetMac().toLowerCase();
@ -159,11 +159,11 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
DeviceAddressBookEntity entity = new DeviceAddressBookEntity();
entity.setMacAddress(macAddress);
entity.setTargetMac(targetMac);
// 如果 alias 为空,就默认使用设备名称
// If alias is empty, default to device name
if (StringUtils.isBlank(alias)) {
alias = deviceService.getDeviceByMacAddress(targetMac).getAlias();
}
// 检查重名
// Check for duplicates
alias = generateUniqueAlias(macAddress, targetMac, alias);
entity.setAlias(alias);
entity.setHasPermission(hasPermission);
@ -204,7 +204,7 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
if (StringUtils.isBlank(mqttGatewayUrl) || "null".equals(mqttGatewayUrl)
|| MqttGatewayAuthorization.isMissingSignatureKey(mqttSignatureKey)) {
result.put("message", action + "失败,网关配置缺失");
result.put("message", action + "Failed, gateway config missing");
return result;
}
@ -224,7 +224,7 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
}
return result;
} catch (Exception e) {
result.put("message", action + "失败,请稍后再试");
result.put("message", action + "Failed, please try again later");
return result;
}
}
@ -234,7 +234,7 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
return mac;
}
String lastTwo = mac.substring(mac.length() - 2);
return "尾号为" + lastTwo + "的设备";
return "Device ending in " + lastTwo;
}
private String generateUniqueAlias(String macAddress, String targetMac, String alias) {

View file

@ -342,7 +342,7 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
wrapper.eq("id", deviceId);
baseDao.delete(wrapper);
// 删除设备相关的通讯录权限记录
// Delete contact permissions related to the device
deviceAddressBookService.deleteByMacAddresses(Collections.singletonList(macAddress));
}
@ -362,17 +362,17 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
@Override
public void deleteByAgentId(String agentId) {
// 先查询该智能体下的所有设备,获取mac地址用于删除通讯录记录
// Query all devices under this Agent first to get MAC addresses for deleting contact records
QueryWrapper<DeviceEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("agent_id", agentId);
List<DeviceEntity> devices = baseDao.selectList(queryWrapper);
// 删除设备
// Delete device
UpdateWrapper<DeviceEntity> wrapper = new UpdateWrapper<>();
wrapper.eq("agent_id", agentId);
baseDao.delete(wrapper);
// 批量删除这些设备相关的所有通讯录权限记录
// Batch delete all contact permissions related to these devices
if (!devices.isEmpty()) {
List<String> macAddresses = devices.stream()
.map(DeviceEntity::getMacAddress)

View file

@ -8,43 +8,43 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "用户显示设备列表VO")
@Schema(description = "User display device list VO")
public class UserShowDeviceListVO {
@Schema(description = "app版本")
@Schema(description = "App Version")
private String appVersion;
@Schema(description = "绑定用户名称")
@Schema(description = "Bind username")
private String bindUserName;
@Schema(description = "设备型号")
@Schema(description = "Device Model")
private String deviceType;
@Schema(description = "设备型号(board)")
@Schema(description = "Device model (board)")
private String board;
@Schema(description = "设备唯一标识符")
@Schema(description = "Device unique identifier")
private String id;
@Schema(description = "mac地址")
@Schema(description = "MAC Address")
private String macAddress;
@Schema(description = "设备别名")
@Schema(description = "Device alias")
private String alias;
@Schema(description = "自动更新开关(0关闭/1开启)")
@Schema(description = "Auto-update switch (0: off / 1: on)")
private Integer autoUpdate;
@Schema(description = "最近对话时间")
@Schema(description = "Last conversation time")
private String recentChatTime;
@Schema(description = "最后连接时间戳(毫秒)", type = "string", example = "1783689702000")
@Schema(description = "Last connection timestamp (ms)", type = "string", example = "1783689702000")
private Long lastConnectedAtTimestamp;
@Schema(description = "绑定时间戳(毫秒)", type = "string", example = "1783689702000")
@Schema(description = "Bind timestamp (ms)", type = "string", example = "1783689702000")
private Long createDateTimestamp;
@Schema(description = "绑定时间(兼容字段,请使用 createDateTimestamp)", deprecated = true)
@Schema(description = "Binding time (legacy field, use createDateTimestamp)", deprecated = true)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "UTC")
private Date createDate;

View file

@ -30,32 +30,32 @@ import xiaozhi.modules.security.user.SecurityUser;
@AllArgsConstructor
@RestController
@RequestMapping("/datasets/{dataset_id}")
@Tag(name = "知识库文档管理")
@Tag(name = "Knowledge base document management")
public class KnowledgeFilesController {
private final KnowledgeFilesService knowledgeFilesService;
private final KnowledgeBaseService knowledgeBaseService;
/**
* 验证当前用户是否有权限操作指定知识库
* Verify if current user has permission to operate specified knowledge base
*
* @param datasetId 知识库ID
* @param datasetId Knowledge base ID
*/
private void validateKnowledgeBasePermission(String datasetId) {
// 获取当前登录用户ID
// Get current logged-in user ID
Long currentUserId = SecurityUser.getUserId();
// 获取知识库信息
// Get knowledge base info
KnowledgeBaseDTO knowledgeBase = knowledgeBaseService.getByDatasetId(datasetId);
// 检查权限:用户只能操作自己创建的知识库
// Check permissions: users can only manage their own knowledge bases
if (knowledgeBase.getCreator() == null || !knowledgeBase.getCreator().equals(currentUserId)) {
throw new RenException(ErrorCode.NO_PERMISSION);
}
}
@GetMapping("/documents")
@Operation(summary = "分页查询文档列表")
@Operation(summary = "Paginated query for document list")
@RequiresPermissions("sys:role:normal")
public Result<PageData<KnowledgeFilesDTO>> getPageList(
@PathVariable("dataset_id") String datasetId,
@ -63,10 +63,10 @@ public class KnowledgeFilesController {
@RequestParam(required = false) String status,
@RequestParam(required = false, defaultValue = "1") Integer page,
@RequestParam(required = false, defaultValue = "10") Integer page_size) {
// 验证知识库权限
// Validate knowledge base permissions
validateKnowledgeBasePermission(datasetId);
// 组装参数
// Assembly parameters
KnowledgeFilesDTO knowledgeFilesDTO = new KnowledgeFilesDTO();
knowledgeFilesDTO.setDatasetId(datasetId);
knowledgeFilesDTO.setName(name);
@ -76,16 +76,16 @@ public class KnowledgeFilesController {
}
@GetMapping("/documents/status/{status}")
@Operation(summary = "根据状态分页查询文档列表")
@Operation(summary = "Query document list by status with pagination")
@RequiresPermissions("sys:role:normal")
public Result<PageData<KnowledgeFilesDTO>> getPageListByStatus(
@PathVariable("dataset_id") String datasetId,
@PathVariable("status") String status,
@RequestParam(required = false, defaultValue = "1") Integer page,
@RequestParam(required = false, defaultValue = "10") Integer page_size) {
// 验证知识库权限
// Validate knowledge base permissions
validateKnowledgeBasePermission(datasetId);
// 组装参数
// Assembly parameters
KnowledgeFilesDTO knowledgeFilesDTO = new KnowledgeFilesDTO();
knowledgeFilesDTO.setDatasetId(datasetId);
knowledgeFilesDTO.setStatus(status);
@ -94,7 +94,7 @@ public class KnowledgeFilesController {
}
@PostMapping("/documents")
@Operation(summary = "上传文档到知识库")
@Operation(summary = "Upload document to knowledge base")
@RequiresPermissions("sys:role:normal")
public Result<KnowledgeFilesDTO> uploadDocument(
@PathVariable("dataset_id") String datasetId,
@ -104,7 +104,7 @@ public class KnowledgeFilesController {
@RequestParam(required = false) String metaFields,
@RequestParam(required = false) String parserConfig) {
// 验证知识库权限
// Validate knowledge base permissions
validateKnowledgeBasePermission(datasetId);
KnowledgeFilesDTO resp = knowledgeFilesService.uploadDocument(datasetId, file, name,
@ -115,11 +115,11 @@ public class KnowledgeFilesController {
}
@DeleteMapping("/documents")
@Operation(summary = "批量删除文档")
@Operation(summary = "Batch delete documents")
@RequiresPermissions("sys:role:normal")
public Result<Void> delete(@PathVariable("dataset_id") String datasetId,
@RequestBody DocumentDTO.BatchIdReq req) {
// 验证知识库权限
// Validate knowledge base permissions
validateKnowledgeBasePermission(datasetId);
knowledgeFilesService.deleteDocuments(datasetId, req);
@ -127,11 +127,11 @@ public class KnowledgeFilesController {
}
@DeleteMapping("/documents/{document_id}")
@Operation(summary = "删除单个文档")
@Operation(summary = "Delete single document")
@RequiresPermissions("sys:role:normal")
public Result<Void> deleteSingle(@PathVariable("dataset_id") String datasetId,
@PathVariable("document_id") String documentId) {
// 验证知识库权限
// Validate knowledge base permissions
validateKnowledgeBasePermission(datasetId);
DocumentDTO.BatchIdReq req = new DocumentDTO.BatchIdReq();
@ -141,28 +141,28 @@ public class KnowledgeFilesController {
}
@PostMapping("/chunks")
@Operation(summary = "解析文档(切块)")
@Operation(summary = "Parse document (chunking)")
@RequiresPermissions("sys:role:normal")
public Result<Void> parseDocuments(@PathVariable("dataset_id") String datasetId,
@RequestBody Map<String, List<String>> requestBody) {
// 验证知识库权限
// Validate knowledge base permissions
validateKnowledgeBasePermission(datasetId);
List<String> documentIds = requestBody.get("document_ids");
if (documentIds == null || documentIds.isEmpty()) {
return new Result<Void>().error("document_ids参数不能为空");
return new Result<Void>().error("document_ids parameter cannot be empty");
}
boolean success = knowledgeFilesService.parseDocuments(datasetId, documentIds);
if (success) {
return new Result<Void>();
} else {
return new Result<Void>().error("文档解析失败,文档可能正在处理中");
return new Result<Void>().error("Document parsing failed, document may be processing");
}
}
@GetMapping("/documents/{document_id}/chunks")
@Operation(summary = "列出指定文档的切片")
@Operation(summary = "List slices of specified document")
@RequiresPermissions("sys:role:normal")
public Result<ChunkDTO.ListVO> listChunks(
@PathVariable("dataset_id") String datasetId,
@ -172,10 +172,10 @@ public class KnowledgeFilesController {
@RequestParam(required = false) String keywords,
@RequestParam(required = false) String id) {
// 验证权限 (内部已包含知识库存在性校验与归属权校验)
// Verify permissions (includes internal knowledge base existence and ownership checks)
validateKnowledgeBasePermission(datasetId);
// 构建请求对象
// Build request object
ChunkDTO.ListReq req = ChunkDTO.ListReq.builder()
.page(page)
.pageSize(pageSize)
@ -183,27 +183,27 @@ public class KnowledgeFilesController {
.id(id)
.build();
// 调用服务层获取强类型切片列表
// Call service layer to get strongly-typed slice list
ChunkDTO.ListVO result = knowledgeFilesService.listChunks(datasetId, documentId, req);
return new Result<ChunkDTO.ListVO>().ok(result);
}
@PostMapping("/retrieval-test")
@Operation(summary = "召回测试")
@Operation(summary = "Recall test")
@RequiresPermissions("sys:role:normal")
public Result<RetrievalDTO.ResultVO> retrievalTest(
@PathVariable("dataset_id") String datasetId,
@RequestBody RetrievalDTO.TestReq req) {
// 验证知识库权限
// Validate knowledge base permissions
validateKnowledgeBasePermission(datasetId);
// 业务下沉逻辑:如果未指定知识库ID,则设为当前路径中的 datasetId
// Business logic fallback: If knowledge base ID is not specified, set it to the datasetId in the current path
if (req.getDatasetIds() == null || req.getDatasetIds().isEmpty()) {
req.setDatasetIds(java.util.Arrays.asList(datasetId));
}
// [Reinforce] 强管控分页参数,防止 RAGFlow 端出现 Negative Slicing 报错
// [Reinforce] Enforce pagination parameters to prevent Negative Slicing errors on the RAGFlow side
if (req.getPage() == null || req.getPage() < 1) {
req.setPage(1);
}
@ -211,13 +211,13 @@ public class KnowledgeFilesController {
req.setPageSize(100);
}
// 调用检索服务,返回强类型聚合对象
// Call retrieval service and return strongly-typed aggregate object
RetrievalDTO.ResultVO result = knowledgeFilesService.retrievalTest(req);
return new Result<RetrievalDTO.ResultVO>().ok(result);
}
/**
* 解析JSON字符串为Map对象
* Parse JSON string into Map object
*/
private Map<String, Object> parseJsonMap(String jsonString) {
try {
@ -225,7 +225,7 @@ public class KnowledgeFilesController {
return objectMapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {
});
} catch (Exception e) {
throw new RuntimeException("解析JSON字符串失败: " + jsonString, e);
throw new RuntimeException("Failed to parse JSON string: " + jsonString, e);
}
}
}

View file

@ -8,66 +8,66 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "知识库知识库")
@Schema(description = "Knowledge base")
public class KnowledgeBaseDTO implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@Schema(description = "唯一标识")
@Schema(description = "Unique identifier")
private String id;
@Schema(description = "知识库ID")
@Schema(description = "Knowledge base ID")
private String datasetId;
@Schema(description = "RAG模型配置ID")
@Schema(description = "RAG model config ID")
private String ragModelId;
@Schema(description = "知识库名称")
@Schema(description = "Knowledge base name")
private String name;
@Schema(description = "知识库头像(Base64)")
@Schema(description = "Knowledge base avatar (Base64)")
private String avatar;
@Schema(description = "知识库描述")
@Schema(description = "Knowledge base description")
private String description;
@Schema(description = "嵌入模型名称")
@Schema(description = "Embedding model name")
private String embeddingModel;
@Schema(description = "权限设置: me/team")
@Schema(description = "Permission settings: me/team")
private String permission;
@Schema(description = "分块方法")
@Schema(description = "Chunking Method")
private String chunkMethod;
@Schema(description = "解析器配置(JSON String)")
@Schema(description = "Parser config (JSON String)")
private String parserConfig;
@Schema(description = "分块总数")
@Schema(description = "Total Chunks")
private Long chunkCount;
@Schema(description = "总Token数")
@Schema(description = "Total tokens")
private Long tokenNum;
@Schema(description = "状态(0:禁用 1:启用)")
@Schema(description = "Status (0: disabled, 1: enabled)")
private Integer status;
@Schema(description = "创建者")
@Schema(description = "Creator")
private Long creator;
@Schema(description = "创建时间")
@Schema(description = "Creation Time")
private Date createdAt;
@Schema(description = "更新者")
@Schema(description = "Updated by")
private Long updater;
@Schema(description = "更新时间")
@Schema(description = "Update time")
private Date updatedAt;
@Schema(description = "文档数量")
@Schema(description = "Document count")
private Integer documentCount;
@Schema(description = "异常提示")
@Schema(description = "Error message")
private String errorMessage;
}

View file

@ -32,11 +32,11 @@ import xiaozhi.modules.knowledge.rag.KnowledgeBaseAdapter;
import xiaozhi.modules.knowledge.rag.RAGFlowClient;
/**
* RAGFlow知识库适配器实现
* RAGFlow knowledge base adapter implementation
* <p>
* 重构说明 (Refactoring Note):
* 本类已升级为使用 {@link RAGFlowClient} 统一处理 HTTP 通信。
* 解决了旧代码中 Timeout 缺失、Error Handling 分散的问题。
* Refactoring Note:
* This class has been upgraded to use {@link RAGFlowClient} for unified HTTP communication.
* Resolved issues in legacy code: missing Timeout and scattered Error Handling.
* </p>
*/
@Slf4j
@ -46,7 +46,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
private Map<String, Object> config;
private ObjectMapper objectMapper;
// Client 实例,初始化时创建
// Client instance, created during initialization
private RAGFlowClient client;
public RAGFlowAdapter() {
@ -66,18 +66,18 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
String baseUrl = getConfigValue(config, "base_url", "baseUrl");
String apiKey = getConfigValue(config, "api_key", "apiKey");
// 初始化 Client,默认超时 30s,可通过 config 扩展
// Initialize Client with a default timeout of 30s, extendable via config
int timeout = 30;
Object timeoutObj = getConfigValue(config, "timeout", "timeout");
if (timeoutObj != null) {
try {
timeout = Integer.parseInt(timeoutObj.toString());
} catch (Exception e) {
log.warn("解析超时配置失败,使用默认值 30s");
log.warn("Failed to parse timeout config, using default 30s");
}
}
this.client = new RAGFlowClient(baseUrl, apiKey, timeout);
log.info("RAGFlow适配器初始化完成,Client已就绪");
log.info("RAGFlow adapter initialized, Client ready");
}
@Override
@ -97,7 +97,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
throw new RenException(ErrorCode.RAG_API_ERROR_API_KEY_NULL);
}
if (apiKey.contains("你")) {
if (apiKey.contains("You")) {
throw new RenException(ErrorCode.RAG_API_ERROR_API_KEY_INVALID);
}
@ -109,7 +109,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
}
/**
* 辅助方法:支持多种键名获取配置(兼容 camelCase 和 snake_case)
* Helper method: retrieve config using multiple key names (supports camelCase and snake_case)
*/
private String getConfigValue(Map<String, Object> config, String snakeKey, String camelKey) {
if (config.containsKey(snakeKey)) {
@ -122,15 +122,15 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
}
/**
* 辅助方法:确保 Client 已初始化
* Helper method: ensure Client is initialized
*/
private RAGFlowClient getClient() {
if (this.client == null) {
// 尝试重新初始化
// Attempt re-initialization
if (this.config != null) {
initialize(this.config);
} else {
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND, "适配器未初始化"); // 应该抛出 RuntimeException
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND, "Adapter not initialized"); // should throw a RuntimeException
}
}
return this.client;
@ -146,9 +146,9 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
@Override
public PageData<KnowledgeFilesDTO> getDocumentList(String datasetId, DocumentDTO.ListReq req) {
try {
log.info("=== [RAGFlow] 获取文档列表: datasetId={} ===", datasetId);
log.info("=== [RAGFlow] Fetching document list: datasetId={} ===", datasetId);
// 使用 Jackson 将 DTO 转为 Map 作为查询参数
// Use Jackson to convert DTO to Map as query parameters
Map<String, Object> params = objectMapper.convertValue(req, new TypeReference<Map<String, Object>>() {
});
@ -159,7 +159,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
req.getPageSize() != null ? req.getPageSize() : 10);
} catch (Exception e) {
log.error("获取文档列表失败", e);
log.error("Failed to get document list", e);
throw convertToRenException(e);
}
}
@ -167,7 +167,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
@Override
public DocumentDTO.InfoVO getDocumentById(String datasetId, String documentId) {
try {
log.info("=== [RAGFlow] 获取文档详情: datasetId={}, documentId={} ===", datasetId, documentId);
log.info("=== [RAGFlow] Fetch document details: datasetId={}, documentId={} ===", datasetId, documentId);
DocumentDTO.ListReq req = DocumentDTO.ListReq.builder()
.id(documentId)
.page(1)
@ -187,7 +187,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
}
return null;
} catch (Exception e) {
log.error("获取文档详情失败: documentId={}", documentId, e);
log.error("Failed to get document details: documentId={}", documentId, e);
throw convertToRenException(e);
}
}
@ -197,7 +197,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
String datasetId = req.getDatasetId();
MultipartFile file = req.getFile();
try {
log.info("=== [RAGFlow] 上传文档: datasetId={} ===", datasetId);
log.info("=== [RAGFlow] Upload document: datasetId={} ===", datasetId);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new MultipartFileResource(file));
@ -209,7 +209,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
body.add("meta", objectMapper.writeValueAsString(req.getMetaFields()));
}
if (req.getChunkMethod() != null) {
// 将枚举值转为 RAGFlow 期待的字符串(如 NAIVE -> naive)
// Convert enum values to strings expected by RAGFlow (e.g., NAIVE -> naive).
body.add("chunk_method", req.getChunkMethod().name().toLowerCase());
}
if (req.getParserConfig() != null) {
@ -226,7 +226,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
return parseUploadResponse(dataObj, datasetId, file);
} catch (Exception e) {
log.error("文档上传失败", e);
log.error("Document upload failed", e);
throw convertToRenException(e);
}
}
@ -268,11 +268,11 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
@Override
public void deleteDocument(String datasetId, DocumentDTO.BatchIdReq req) {
try {
log.info("=== [RAGFlow] 批量删除文档: datasetId={}, count={} ===", datasetId,
log.info("=== [RAGFlow] Batch delete documents: datasetId={}, count={} ===", datasetId,
req.getIds() != null ? req.getIds().size() : 0);
getClient().delete("/api/v1/datasets/" + datasetId + "/documents", req);
} catch (Exception e) {
log.error("批量删除文档失败: datasetId={}", datasetId, e);
log.error("Failed to batch delete documents: datasetId={}", datasetId, e);
throw convertToRenException(e);
}
}
@ -280,14 +280,14 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
@Override
public boolean parseDocuments(String datasetId, List<String> documentIds) {
try {
log.info("=== [RAGFlow] 解析文档 ===");
log.info("=== [RAGFlow] Parsing document ===");
Map<String, Object> body = new HashMap<>();
body.put("document_ids", documentIds);
getClient().post("/api/v1/datasets/" + datasetId + "/chunks", body);
return true;
} catch (Exception e) {
log.error("解析文档失败", e);
log.error("Failed to parse document", e);
throw convertToRenException(e);
}
}
@ -295,7 +295,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
@Override
public ChunkDTO.ListVO listChunks(String datasetId, String documentId, ChunkDTO.ListReq req) {
try {
// [提灯重构] 使用 objectMapper 动态转换查询参数,消除硬编码
// [Lantern Refactor] Use objectMapper to dynamically convert query parameters, eliminating hardcoding
Map<String, Object> params = objectMapper.convertValue(req, new TypeReference<Map<String, Object>>() {
});
@ -304,7 +304,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
Object dataObj = response.get("data");
if (dataObj == null) {
log.warn("[RAGFlow] listChunks 响应 data 为空, docId={}", documentId);
log.warn("[RAGFlow] listChunks response data is empty, docId={}", documentId);
return ChunkDTO.ListVO.builder()
.chunks(new ArrayList<>())
.total(0L)
@ -317,7 +317,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
}
return result;
} catch (Exception e) {
log.error("获取切片失败: docId={}", documentId, e);
log.error("Failed to get slice: docId={}", documentId, e);
throw convertToRenException(e);
}
}
@ -325,18 +325,18 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
@Override
public RetrievalDTO.ResultVO retrievalTest(RetrievalDTO.TestReq req) {
try {
// [Production Reinforce] 参数防御性对齐:RAGFlow Python 端对 0 或负数分页敏感
// 解决 ValueError('Search does not support negative slicing.')
// [Production Reinforce] Defensive parameter alignment: RAGFlow Python side is sensitive to 0 or negative pagination values
// Resolve ValueError('Search does not support negative slicing.')
if (req.getPage() != null && req.getPage() < 1) {
req.setPage(1);
}
if (req.getPageSize() != null && req.getPageSize() < 1) {
req.setPageSize(10); // 默认 10 条
req.setPageSize(10); // Default 10 items
}
if (req.getTopK() != null && req.getTopK() < 1) {
req.setTopK(1024); // RAGFlow 内部默认 TopK
req.setTopK(1024); // RAGFlow internal default TopK
}
// 相似度阈值归一化 (0.0 ~ 1.0)
// Normalize similarity threshold (0.0 ~ 1.0)
if (req.getSimilarityThreshold() != null) {
if (req.getSimilarityThreshold() < 0f)
req.setSimilarityThreshold(0.2f);
@ -344,12 +344,12 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
req.setSimilarityThreshold(1.0f);
}
// [提灯重构] 直接透传强类型 DTO,由 getClient 处理序列化
// [Lantern refactor] Pass through strongly-typed DTOs directly; let getClient handle serialization
Map<String, Object> response = getClient().post("/api/v1/retrieval", req);
Object dataObj = response.get("data");
if (dataObj == null) {
log.warn("[RAGFlow] retrievalTest 响应 data 为空");
log.warn("[RAGFlow] retrievalTest response data is empty");
return RetrievalDTO.ResultVO.builder()
.chunks(new ArrayList<>())
.docAggs(new ArrayList<>())
@ -363,7 +363,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
}
return result;
} catch (Exception e) {
log.error("召回测试失败", e);
log.error("Recall test failed", e);
throw convertToRenException(e);
}
}
@ -374,7 +374,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
getClient().get("/api/v1/health", null);
return true;
} catch (Exception e) {
log.error("连接测试失败: {}", e.getMessage());
log.error("Connection test failed: {}", e.getMessage());
return false;
}
}
@ -383,7 +383,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
public Map<String, Object> getStatus() {
Map<String, Object> status = new HashMap<>();
status.put("adapterType", getAdapterType());
status.put("configKeys", config != null ? config.keySet() : "未配置");
status.put("configKeys", config != null ? config.keySet() : "Not configured");
status.put("connectionTest", testConnection());
status.put("lastChecked", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
return status;
@ -392,9 +392,9 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
@Override
public Map<String, Object> getSupportedConfig() {
Map<String, Object> supportedConfig = new HashMap<>();
supportedConfig.put("base_url", "RAGFlow API基础URL");
supportedConfig.put("api_key", "RAGFlow API密钥");
supportedConfig.put("timeout", "请求超时时间(毫秒)");
supportedConfig.put("base_url", "RAGFlow API base URL");
supportedConfig.put("api_key", "RAGFlow API key");
supportedConfig.put("timeout", "Request timeout (ms)");
return supportedConfig;
}
@ -408,8 +408,8 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
@Override
public DatasetDTO.InfoVO createDataset(DatasetDTO.CreateReq req) {
try {
// [Production Fix] 强化默认值处理,防止 RAGFlow API 因空字符串或缺失字段报错 (Code 101)
// 解决 "Field: <avatar> - Message: <Missing MIME prefix>" 等校验失败
// [Production Fix] Strengthen default value handling to prevent RAGFlow API errors (Code 101) due to empty strings or missing fields
// Resolve validation failures such as "Field: <avatar> - Message: <Missing MIME prefix>"
if (StringUtils.isBlank(req.getPermission())) {
req.setPermission("me");
}
@ -417,33 +417,33 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
req.setChunkMethod("naive");
}
// 🤖 自动补全嵌入模型:优先使用请求传参,其次使用配置中的默认模型
// 🤖 Auto-complete embedding model: prioritize request parameters, then use the default model from config
if (StringUtils.isBlank(req.getEmbeddingModel())) {
String defaultModel = (String) getConfigValue(config, "embedding_model", "embeddingModel");
if (StringUtils.isNotBlank(defaultModel)) {
log.info("RAGFlow: 使用配置中的默认嵌入模型: {}", defaultModel);
log.info("RAGFlow: Using default embedding model from config: {}", defaultModel);
req.setEmbeddingModel(defaultModel);
}
// 若配置中也无默认值,则留空由 RAGFlow 服务端自行兜底(或抛出业务异常)
// If no default value is configured, leave it empty to let the RAGFlow server handle it (or throw a business exception)
}
// 🖼️ 自动补全头像:若为空则提供一个 1x1 透明像素,防止 RAGFlow 校验 MIME Prefix 失败
// 🖼️ Auto-complete avatar: Provide a 1x1 transparent pixel if empty to prevent RAGFlow MIME Prefix validation failures.
if (StringUtils.isBlank(req.getAvatar())) {
req.setAvatar(
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==");
}
// 直接将强类型请求对象传给 Client,Jackson 会处理 JsonProperty 映射
// Pass the strongly-typed request object directly to the Client; Jackson handles JsonProperty mapping.
Map<String, Object> response = getClient().post("/api/v1/datasets", req);
// 安全地获取 data 并通过 DatasetDTO.InfoVO 进行全量映射
// Safely retrieve data and perform full mapping via DatasetDTO.InfoVO.
Object dataObj = response.get("data");
if (dataObj != null) {
return objectMapper.convertValue(dataObj, DatasetDTO.InfoVO.class);
}
throw new RenException(ErrorCode.RAG_API_ERROR, "Invalid response from createDataset: missing data object");
} catch (Exception e) {
log.error("创建数据集失败", e);
log.error("Failed to create dataset", e);
throw convertToRenException(e);
}
}
@ -451,7 +451,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
@Override
public DatasetDTO.InfoVO updateDataset(String datasetId, DatasetDTO.UpdateReq req) {
try {
// RAGFlow API 更新建议路径带 ID
// RAGFlow API update suggestion path with ID
Map<String, Object> response = getClient().put("/api/v1/datasets/" + datasetId, req);
Object dataObj = response.get("data");
@ -460,7 +460,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
}
return null;
} catch (Exception e) {
log.error("更新数据集失败", e);
log.error("Failed to update dataset", e);
throw convertToRenException(e);
}
}
@ -468,7 +468,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
@Override
public DatasetDTO.BatchOperationVO deleteDataset(DatasetDTO.BatchIdReq req) {
try {
// RAGFlow 批量删除接口使用 DELETE /api/v1/datasets
// RAGFlow batch delete API uses DELETE /api/v1/datasets
Map<String, Object> response = getClient().delete("/api/v1/datasets", req);
Object dataObj = response.get("data");
@ -477,7 +477,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
}
return null;
} catch (Exception e) {
log.error("批量删除数据集失败", e);
log.error("Failed to batch delete datasets", e);
throw convertToRenException(e);
}
}
@ -508,10 +508,10 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
return objectMapper.convertValue(list.get(0), DatasetDTO.InfoVO.class);
}
}
// RAGFlow 端不存在该数据集
// Dataset not found in RAGFlow
return null;
} catch (Exception e) {
log.warn("获取数据集信息失败: datasetId={}, error={}", datasetId, e.getMessage());
log.warn("Failed to get dataset info: datasetId={}, error={}", datasetId, e.getMessage());
throw convertToRenException(e);
}
}
@ -521,7 +521,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
try {
getClient().postStream(endpoint, body, onData);
} catch (Exception e) {
log.error("流式请求失败", e);
log.error("Streaming request failed", e);
throw convertToRenException(e);
}
}
@ -529,20 +529,20 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
@Override
public Object postSearchBotAsk(Map<String, Object> config, Object body,
Consumer<String> onData) {
// SearchBot 实际上是 Dataset 检索的一种封装,或者是未公开的 API?
// 假设 RAGFlow 没有显式的 /searchbots 接口供 SDK 调用,而是 Dataset Retrieval 或者 Chat。
// 但根据 BotDTO,它是 /api/v1/searchbots/ask (假设)
// 这里的 config 可能是覆盖用的,或者我们只是用 adapter 实例已有的 client。
// 但 Bot 可能使用不同的 API Key?通常 Adapter 实例绑定了一个 Key。
// 如果 Bot 使用系统 Key,则直接用 getClient()。
// Is SearchBot a wrapper for Dataset retrieval, or an undocumented API?
// Assume RAGFlow does not expose an explicit /searchbots endpoint for SDK calls, but rather Dataset Retrieval or Chat.
// But according to BotDTO, it is /api/v1/searchbots/ask (assumed)
// The config here may be for overriding, or we simply use the existing client from the adapter instance.
// But the Bot might use a different API Key? Typically, an Adapter instance is bound to one Key.
// If the Bot uses the system key, use getClient() directly.
// 暂时假设 endpoint /api/v1/searchbots/ask 存在(或者类似的)
// 如果是流式:
// Temporarily assume endpoint /api/v1/searchbots/ask exists (or similar)
// If streaming:
try {
getClient().postStream("/api/v1/searchbots/ask", body, onData);
return null;
} catch (Exception e) {
log.error("SearchBot Ask 失败", e);
log.error("SearchBot Ask failed", e);
throw convertToRenException(e);
}
}
@ -550,17 +550,17 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
@Override
public void postAgentBotCompletion(Map<String, Object> config, String agentId, Object body,
Consumer<String> onData) {
// AgentBot 对应 /api/v1/agentbots/{id}/completions
// AgentBot maps to /api/v1/agentbots/{id}/completions
try {
getClient().postStream("/api/v1/agentbots/" + agentId + "/completions", body, onData);
} catch (Exception e) {
log.error("AgentBot Completion 失败", e);
log.error("AgentBot Completion failed", e);
throw convertToRenException(e);
}
}
// 复用原有的辅助解析方法,保持兼容
// [Bug Fix] 不再吞掉反序列化异常,避免上层误判"文档已删除"
// Reuse existing helper parsing method for compatibility
// [Bug Fix] No longer swallow deserialization exceptions to prevent upper-layer misjudgment"document deleted"
private PageData<KnowledgeFilesDTO> parseDocumentListResponse(Object dataObj, long curPage, long pageSize) {
if (dataObj == null) {
return new PageData<>(new ArrayList<>(), 0);
@ -569,18 +569,18 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
Map<?, ?> dataMap = Map.class.cast(dataObj);
List<?> documents = List.class.cast(dataMap.get("docs"));
if (documents == null || documents.isEmpty()) {
// RAGFlow 明确返回了空文档列表,这是合法的"真空"
// RAGFlow explicitly returned an empty document list, this is a valid " empty"
return new PageData<>(new ArrayList<>(), 0);
}
List<KnowledgeFilesDTO> list = new ArrayList<>();
for (Object docObj : documents) {
try {
// 单文档转换容错:一个文档反序列化失败不影响其他文档
// Single document conversion fault tolerance: deserialization failure of one document does not affect others
DocumentDTO.InfoVO info = objectMapper.convertValue(docObj, DocumentDTO.InfoVO.class);
list.add(mapToKnowledgeFilesDTO(info, null));
} catch (Exception e) {
log.warn("[RAGFlow] 单文档 DTO 转换失败,跳过该文档: {}", e.getMessage());
log.warn("[RAGFlow] Single-document DTO conversion failed, skipping document: {}", e.getMessage());
}
}
@ -595,7 +595,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
private KnowledgeFilesDTO parseUploadResponse(Object dataObj, String datasetId, MultipartFile file) {
KnowledgeFilesDTO result = null;
// 尝试从响应数据中提取文档ID (documentId)
// Attempt to extract the document ID (documentId) from the response data
if (dataObj != null) {
try {
DocumentDTO.InfoVO info = null;
@ -612,13 +612,13 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
result = mapToKnowledgeFilesDTO(info, datasetId);
}
} catch (Exception e) {
log.warn("解析上传响应数据失败: {}", e.getMessage());
log.warn("Failed to parse upload response data: {}", e.getMessage());
}
}
if (result == null) {
log.error("未能从RAGFlow响应中提取到documentId,响应内容: {}", dataObj);
// 这里应该返回一个最小化的包含基础信息的 DTO 而不是 null,防止上游 NPE
log.error("Failed to extract documentId from RAGFlow response; content: {}", dataObj);
// Return a minimal DTO with basic info instead of null here to prevent upstream NPE
result = new KnowledgeFilesDTO();
result.setDatasetId(datasetId);
result.setName(file.getOriginalFilename());
@ -630,8 +630,8 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
}
/**
* 将 RAGFlow 的强类型 InfoVO 映射到内部使用的 KnowledgeFilesDTO
* 确保所有可用字段(名称、大小、状态、配置等)都得到全量同步
* Map RAGFlow's strongly-typed InfoVO to the internal KnowledgeFilesDTO
* Ensure all available fields (name, size, status, config, etc.) are fully synchronized
*/
private KnowledgeFilesDTO mapToKnowledgeFilesDTO(DocumentDTO.InfoVO info, String datasetId) {
KnowledgeFilesDTO dto = new KnowledgeFilesDTO();
@ -644,7 +644,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
dto.setName(info.getName());
dto.setFileSize(info.getSize());
// 状态映射
// Status mapping
if (info.getRun() != null) {
dto.setRun(info.getRun().name());
}
@ -652,10 +652,10 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
if (StringUtils.isNotBlank(info.getStatus())) {
dto.setStatus(info.getStatus());
} else {
dto.setStatus("1"); // 默认启用
dto.setStatus("1"); // Enabled by Default
}
// 时间同步
// Time sync
if (info.getCreateTime() != null) {
dto.setCreatedAt(new Date(info.getCreateTime()));
}
@ -663,16 +663,16 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
dto.setUpdatedAt(new Date(info.getUpdateTime()));
}
// 核心元数据补齐 (Issue 1)
// Complete core metadata (Issue 1)
dto.setProgress(info.getProgress());
dto.setThumbnail(info.getThumbnail());
dto.setProcessDuration(info.getProcessDuration());
dto.setSourceType(info.getSourceType());
dto.setChunkCount(info.getChunkCount() != null ? info.getChunkCount().intValue() : 0);
dto.setTokenCount(info.getTokenCount());
dto.setError(info.getProgressMsg()); // 将进度描述映射为错误信息提示
dto.setError(info.getProgressMsg()); // Map progress descriptions to error messages
// 扩展字段同步
// Sync extended fields
dto.setMetaFields(info.getMetaFields());
if (info.getChunkMethod() != null) {
dto.setChunkMethod(info.getChunkMethod().name().toLowerCase());

View file

@ -38,8 +38,8 @@ import java.util.List;
import java.util.Map;
/**
* 知识库服务实现类 (Refactored)
* 集成 RAGFlow Adapter 与 Shadow DB 模式
* Knowledge base service implementation (Refactored)
* Integrate RAGFlow Adapter with Shadow DB mode
*/
@Service
@AllArgsConstructor
@ -72,8 +72,8 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
if (pageData != null && pageData.getList() != null) {
pageData.getList().removeIf(dto -> {
enrichDocumentCount(dto);
// syncDatasetFromRAG 检测到 RAGFlow 端已删除时,会将本地记录清理
// 此时 datasetId 被置空作为标记,需要在列表中移除该条目
// syncDatasetFromRAG cleans up local records when deletion is detected on the RAGFlow side.
// datasetId is set to empty as a marker; remove this entry from the list
return dto.getDatasetId() == null;
});
}
@ -85,8 +85,8 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
}
/**
* 从 RAGFlow 同步数据集信息:检测删除、同步名称/简介、获取文档数量
* 每次列表刷新时实时查询 RAGFlow,确保立即感知远端变更
* Sync dataset info from RAGFlow: detect deletions, sync name/description, fetch document count
* Query RAGFlow in real time on every list refresh to immediately detect remote changes
*/
private void syncDatasetFromRAG(KnowledgeBaseDTO dto) {
try {
@ -100,22 +100,22 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
}
DatasetDTO.InfoVO datasetInfo = adapter.getDatasetInfo(dto.getDatasetId());
// getDatasetInfo 正常返回 null 表示远端确实不存在;异常时已抛出 RenException 由外层 catch 接管
// getDatasetInfo returning null normally indicates the resource does not exist remotely; exceptions are thrown as RenException and handled by the outer catch block.
if (datasetInfo == null) {
// RAGFlow 端已确认删除 → 本地级联清理
log.info("数据集 {} 在 RAGFlow 端不存在,执行本地清理", dto.getDatasetId());
// Deletion confirmed on RAGFlow side -> perform local cascade cleanup
log.info("Dataset {} does not exist on the RAGFlow side; performing local cleanup", dto.getDatasetId());
cleanupLocalDataset(dto.getDatasetId(), dto.getId());
// 标记为已删除,让上层从列表中移除
// Mark as deleted so the upper layer removes it from the list
dto.setDatasetId(null);
return;
}
// 同步名称(去掉 username_ 前缀)
// Sync name (remove username_ prefix)
String ragflowName = datasetInfo.getName();
if (StringUtils.isNotBlank(ragflowName)) {
String localName = ragflowName.contains("_") ? ragflowName.substring(ragflowName.indexOf('_') + 1) : ragflowName;
if (!localName.equals(dto.getName())) {
log.info("同步知识库名称: {} -> {}", dto.getName(), localName);
log.info("Sync knowledge base name: {} -> {}", dto.getName(), localName);
KnowledgeBaseEntity entity = knowledgeBaseDao.selectById(dto.getId());
if (entity != null) {
entity.setName(localName);
@ -125,12 +125,12 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
}
}
// 同步简介
// Sync overview
String ragflowDesc = datasetInfo.getDescription();
String localDesc = dto.getDescription();
boolean descChanged = (ragflowDesc == null && localDesc != null) || (ragflowDesc != null && !ragflowDesc.equals(localDesc));
if (descChanged) {
log.info("同步知识库简介: datasetId={}", dto.getDatasetId());
log.info("Sync knowledge base description: datasetId={}", dto.getDatasetId());
KnowledgeBaseEntity entity = knowledgeBaseDao.selectById(dto.getId());
if (entity != null) {
entity.setDescription(ragflowDesc);
@ -139,36 +139,36 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
}
}
// 设置文档数量(保留原有功能)
// Set document count (preserve existing functionality)
if (datasetInfo.getDocumentCount() != null) {
dto.setDocumentCount(datasetInfo.getDocumentCount().intValue());
}
} catch (Exception e) {
log.error("同步数据集信息失败 {}: {}", dto.getName(), e.getMessage());
log.error("Failed to sync dataset info {}: {}", dto.getName(), e.getMessage());
dto.setDocumentCount(0);
dto.setErrorMessage(e.getMessage());
}
}
/**
* 本地级联清理:RAGFlow 端已删除时,清理本地所有关联数据
* 不调用 RAGFlow 删除 API
* Local cascade cleanup: when deleted on RAGFlow, remove all associated local data
* Do not call the RAGFlow delete API
*/
@Transactional(rollbackFor = Exception.class)
public void cleanupLocalDataset(String datasetId, String entityId) {
try {
// 1. 删除文档影子记录
// 1. Delete document shadow records
documentDao.delete(new QueryWrapper<DocumentEntity>().eq("dataset_id", datasetId));
// 2. 删除插件映射
// 2. Delete plugin mappings
knowledgeBaseDao.deletePluginMappingByKnowledgeBaseId(entityId);
// 3. 删除知识库记录
// 3. Delete knowledge base record
knowledgeBaseDao.deleteById(entityId);
// 4. 清理缓存
// 4. Clear cache
redisUtils.delete(RedisKeys.getKnowledgeBaseCacheKey(entityId));
log.info("本地级联清理完成: datasetId={}, entityId={}", datasetId, entityId);
log.info("Local cascade cleanup completed: datasetId={}, entityId={}", datasetId, entityId);
} catch (Exception e) {
log.error("本地级联清理失败: datasetId={}, entityId={}", datasetId, entityId, e);
log.error("Local cascade cleanup failed: datasetId={}, entityId={}", datasetId, entityId, e);
}
}
@ -186,7 +186,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
if (StringUtils.isBlank(datasetId)) {
throw new RenException(ErrorCode.PARAMS_GET_ERROR);
}
// [Production Fix] 兼容性查找:优先通过 dataset_id 找,找不到通过主键 id 找,确保前端传哪种 UUID 都能命中
// [Production Fix] Compatibility lookup: prioritize dataset_id, fallback to primary key id, ensuring frontend UUIDs match regardless of type
KnowledgeBaseEntity entity = knowledgeBaseDao
.selectOne(new QueryWrapper<KnowledgeBaseEntity>()
.eq("dataset_id", datasetId)
@ -208,13 +208,13 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
// 2. RAG Creation
String datasetId = null;
try {
// 若未指定 RAG 模型,自动使用系统默认
// If RAG model is not specified, use system default automatically
if (StringUtils.isBlank(dto.getRagModelId())) {
List<ModelConfigEntity> models = getRAGModels();
if (models != null && !models.isEmpty()) {
dto.setRagModelId(models.get(0).getId());
} else {
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND, "未指定且无可用默认 RAG 模型");
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND, "No default RAG model specified or available");
}
}
@ -227,21 +227,21 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
DatasetDTO.InfoVO ragResponse = adapter.createDataset(createReq);
if (ragResponse == null || StringUtils.isBlank(ragResponse.getId())) {
throw new RenException(ErrorCode.RAG_API_ERROR, "RAG创建返回无效: 缺失ID");
throw new RenException(ErrorCode.RAG_API_ERROR, "Invalid RAG creation response: missing ID");
}
datasetId = ragResponse.getId();
// 3. Local Save (Shadow)
KnowledgeBaseEntity entity = ConvertUtils.sourceToTarget(dto, KnowledgeBaseEntity.class);
// [Production Fix] 统一本地 ID 与 RAGFlow ID,防止前端调用 /delete 或 /update 时因 ID 混淆(本地
// UUID vs RAG UUID)导致 10163 错误
// [Production Fix] Unify local ID and RAGFlow ID to prevent ID confusion when frontend calls /delete or /update (local
// UUID vs RAG UUID) causes error 10163
entity.setId(datasetId);
entity.setDatasetId(datasetId);
entity.setStatus(1); // Default Enabled
// ✅ FULL PERSISTENCE: 严格全量回写 (User Requirement)
// 使用强类型 DTO 属性获取,不再从 Map 中手动解析 Key
// ✅ FULL PERSISTENCE: Strict full write-back (User Requirement)
// Use strongly-typed DTO properties for retrieval instead of manually parsing keys from a Map
entity.setTenantId(ragResponse.getTenantId());
entity.setChunkMethod(ragResponse.getChunkMethod());
entity.setEmbeddingModel(ragResponse.getEmbeddingModel());
@ -261,29 +261,29 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
entity.setDocumentCount(ragResponse.getDocumentCount() != null ? ragResponse.getDocumentCount() : 0L);
entity.setTokenNum(ragResponse.getTokenNum() != null ? ragResponse.getTokenNum() : 0L);
// 清空 creator/updater,让 FieldMetaObjectHandler 从 SecurityUser 自动填充
// ConvertUtils 会把 DTO 中的 creator=0 拷贝过来,导致 strictInsertFill 跳过填充
// Clear creator/updater to allow FieldMetaObjectHandler to auto-fill from SecurityUser
// ConvertUtils copies creator=0 from DTO, causing strictInsertFill to skip population
entity.setCreator(null);
entity.setUpdater(null);
knowledgeBaseDao.insert(entity);
return ConvertUtils.sourceToTarget(entity, KnowledgeBaseDTO.class);
} catch (Exception e) {
log.error("RAG创建或本地保存失败", e);
// 如果datasetId已生成但在保存本地时失败,尝试回滚RAG (Best Effort)
log.error("RAG creation or local save failed", e);
// If datasetId is generated but local save fails, attempt to roll back RAG (Best Effort)
if (StringUtils.isNotBlank(datasetId)) {
try {
if (adapter != null)
adapter.deleteDataset(
DatasetDTO.BatchIdReq.builder().ids(Collections.singletonList(datasetId)).build());
} catch (Exception rollbackEx) {
log.error("RAG回滚失败: {}", datasetId, rollbackEx);
log.error("RAG rollback failed: {}", datasetId, rollbackEx);
}
}
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, "创建知识库失败: " + e.getMessage());
throw new RenException(ErrorCode.RAG_API_ERROR, "Failed to create knowledge base: " + e.getMessage());
}
}
@ -300,7 +300,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
checkDuplicateName(dto.getName(), dto.getId());
// 验证数据集ID是否与其他记录冲突
// Verify if dataset ID conflicts with other records
if (StringUtils.isNotBlank(dto.getDatasetId())) {
KnowledgeBaseEntity conflictEntity = knowledgeBaseDao.selectOne(
new QueryWrapper<KnowledgeBaseEntity>()
@ -314,13 +314,13 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
// RAG Update if needed
if (StringUtils.isNotBlank(entity.getDatasetId()) && StringUtils.isNotBlank(dto.getRagModelId())) {
try {
// 🤖 AUTO-FILL: 若 DTO 未传 ragModelId (极少情况),尝试复用 Entity 中的
// 🤖 AUTO-FILL: If DTO does not pass ragModelId (rare case), attempt to reuse from Entity
if (StringUtils.isBlank(dto.getRagModelId())) {
dto.setRagModelId(entity.getRagModelId());
}
// [FIX] 智能补全:如果 DTO 里的关键字段为空,则使用 Entity 里的旧值
// 确保发给 RAGFlow 的请求包含所有必填项 (Partial Update Support)
// [FIX] Smart completion: If key fields in the DTO are empty, use old values from the Entity
// Ensure requests to RAGFlow include all required fields (Partial Update Support)
if (StringUtils.isBlank(dto.getPermission())) {
dto.setPermission(entity.getPermission());
}
@ -332,32 +332,32 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
if (adapter != null) {
DatasetDTO.UpdateReq updateReq = ConvertUtils.sourceToTarget(dto, DatasetDTO.UpdateReq.class);
// 1. 必填/核心字段前缀处理
// 1. Prefix handling for required/core fields
if (StringUtils.isNotBlank(dto.getName())) {
updateReq.setName(SecurityUser.getUser().getUsername() + "_" + dto.getName());
}
// 2. 解析器配置支持 (如果 DTO 里有字符串形式的配置,尝试转换,但优先建议 DTO 化)
// 2. Parser config support (if the DTO contains string-form configs, attempt conversion, but prefer DTOs)
if (StringUtils.isNotBlank(dto.getParserConfig())) {
try {
DatasetDTO.ParserConfig parserConfig = JsonUtils.parseObject(dto.getParserConfig(),
DatasetDTO.ParserConfig.class);
updateReq.setParserConfig(parserConfig);
} catch (Exception e) {
log.warn("解析 parser_config 失败,跳过同步", e);
log.warn("Failed to parse parser_config; skipping sync", e);
}
}
adapter.updateDataset(entity.getDatasetId(), updateReq);
log.info("RAG更新成功: {}", entity.getDatasetId());
log.info("RAG update succeeded: {}", entity.getDatasetId());
}
} catch (Exception e) {
log.error("RAG更新失败", e);
// 恢复事务一致性:RAG失败则整体回滚
log.error("RAG update failed", e);
// Restore transaction consistency: roll back entirely if RAG fails
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, "RAG更新失败: " + e.getMessage());
throw new RenException(ErrorCode.RAG_API_ERROR, "RAG update failed: " + e.getMessage());
}
}
@ -380,16 +380,16 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
KnowledgeBaseEntity entity = knowledgeBaseDao
.selectOne(new QueryWrapper<KnowledgeBaseEntity>().eq("dataset_id", datasetId));
// 1. 恢复 404 校验:找不到记录抛异常
// 1. Restore 404 validation: throw exception if record not found
if (entity == null) {
log.warn("记录不存在,datasetId: {}", datasetId);
log.warn("Record not found, datasetId: {}", datasetId);
throw new RenException(ErrorCode.Knowledge_Base_RECORD_NOT_EXISTS);
}
log.info("找到记录: ID={}, datasetId={}, ragModelId={}",
log.info("Found record: ID={}, datasetId={}, ragModelId={}",
entity.getId(), entity.getDatasetId(), entity.getRagModelId());
// 2. RAG Delete (Strict Mode)
// 恢复严格一致性:RAG 删除失败则抛出异常,触发事务回滚,不允许已删除本地但保留远程的脏数据
// Restore strict consistency: throw exception on RAG deletion failure to trigger transaction rollback; disallow dirty data where local is deleted but remote is retained
boolean apiDeleteSuccess = false;
if (StringUtils.isNotBlank(entity.getRagModelId()) && StringUtils.isNotBlank(entity.getDatasetId())) {
try {
@ -400,26 +400,26 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
}
apiDeleteSuccess = true;
} catch (Exception e) {
log.error("RAG删除失败,触发回滚", e);
log.error("RAG deletion failed, triggering rollback", e);
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, "RAG删除失败: " + e.getMessage());
throw new RenException(ErrorCode.RAG_API_ERROR, "RAG deletion failed: " + e.getMessage());
}
} else {
log.warn("datasetId或ragModelId为空,跳过RAG删除");
apiDeleteSuccess = true; // 没有RAG数据集,视为成功
log.warn("datasetId or ragModelId is empty, skipping RAG deletion");
apiDeleteSuccess = true; // No RAG dataset, treat as success
}
// 3. Local Delete (Safe Order)
// 恢复正确顺序:先删子表 (Plugin Mapping),再删主表 (Entity)
// Restore correct order: delete child table (Plugin Mapping) first, then main table (Entity)
if (apiDeleteSuccess) {
log.info("开始删除ai_agent_plugin_mapping表中与知识库ID '{}' 相关的映射记录", entity.getId());
log.info("开始删除关联数据, entityId: {}", entity.getId());
log.info("Start deleting mapping records in ai_agent_plugin_mapping table related to knowledge base ID '{}'", entity.getId());
log.info("Starting deletion of associated data, entityId: {}", entity.getId());
knowledgeBaseDao.deletePluginMappingByKnowledgeBaseId(entity.getId());
log.info("插件映射记录删除完成");
log.info("Plugin mapping record deletion complete");
int deleteCount = knowledgeBaseDao.deleteById(entity.getId());
log.info("本地数据库删除结果: {}", deleteCount > 0 ? "成功" : "失败");
log.info("Local database deletion result: {}", deleteCount > 0 ? "Success" : "Failure");
redisUtils.delete(RedisKeys.getKnowledgeBaseCacheKey(entity.getId()));
}
}
@ -429,7 +429,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
if (datasetIdList == null || datasetIdList.isEmpty()) {
return Collections.emptyList();
}
// [Production Fix] 批量兼容性查找
// [Production Fix] Batch compatibility lookup
QueryWrapper<KnowledgeBaseEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.in("dataset_id", datasetIdList).or().in("id", datasetIdList);
List<KnowledgeBaseEntity> list = knowledgeBaseDao.selectList(queryWrapper);
@ -454,7 +454,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
@Override
@Transactional(rollbackFor = Exception.class)
public void updateStatistics(String datasetId, Integer docDelta, Long chunkDelta, Long tokenDelta) {
log.info("递增更新知识库统计: datasetId={}, docs={}, chunks={}, tokens={}", datasetId, docDelta, chunkDelta, tokenDelta);
log.info("Incrementally update knowledge base stats: datasetId={}, docs={}, chunks={}, tokens={}", datasetId, docDelta, chunkDelta, tokenDelta);
knowledgeBaseDao.updateStatsAfterChange(datasetId, docDelta, chunkDelta, tokenDelta);
}

View file

@ -72,20 +72,20 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
@Override
public PageData<KnowledgeFilesDTO> getPageList(KnowledgeFilesDTO knowledgeFilesDTO, Integer page, Integer limit) {
log.info("=== 开始获取知识库文档列表 (Local-First 优化版) ===");
log.info("=== Start fetching knowledge base document list (Local-First optimized) ===");
String datasetId = knowledgeFilesDTO.getDatasetId();
if (StringUtils.isBlank(datasetId)) {
throw new RenException(ErrorCode.RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL);
}
// 全量对账同步: 从RAGFlow拉取远端文档,实时同步确保立即感知远端变更
// Full reconciliation sync: Pull remote documents from RAGFlow for real-time sync to immediately detect remote changes
try {
self.syncDocumentsFromRAG(datasetId);
} catch (Exception e) {
log.warn("从RAGFlow全量同步文档失败(不影响本地查询): datasetId={}, error={}", datasetId, e.getMessage());
log.warn("Failed to sync all documents from RAGFlow (does not affect local queries): datasetId={}, error={}", datasetId, e.getMessage());
}
// 1. 获取本地影子表数据 (MyBatis-Plus 分页)
// 1. Fetch local shadow table data (MyBatis-Plus pagination)
Page<DocumentEntity> pageParams = new Page<>(page, limit);
QueryWrapper<DocumentEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("dataset_id", datasetId);
@ -100,30 +100,30 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
}
queryWrapper.orderByDesc("created_at");
// 2. 执行本地查询
// 2. Execute local query
Page<DocumentEntity> iPage = documentDao.selectPage(pageParams, queryWrapper);
// 3. 手动转换 DTO
// 3. Manually convert DTO
List<KnowledgeFilesDTO> dtoList = new ArrayList<>();
for (DocumentEntity entity : iPage.getRecords()) {
dtoList.add(convertEntityToDTO(entity));
}
PageData<KnowledgeFilesDTO> pageData = new PageData<>(dtoList, iPage.getTotal());
// 4. 动态状态同步 (带限流与保护)
// [Bug Fix] P1: 扩大同步白名单,CANCEL/FAIL 也允许低频同步以支持自愈
// 4. Dynamic state synchronization (with rate limiting and protection)
// [Bug Fix] P1: Expand sync whitelist to allow low-frequency sync for CANCEL/FAIL to support self-healing
if (pageData.getList() != null && !pageData.getList().isEmpty()) {
KnowledgeBaseAdapter adapter = null;
for (KnowledgeFilesDTO dto : pageData.getList()) {
String runStatus = dto.getRun();
// 高优先级同步: RUNNING/UNSTART (5秒冷却)
// High-priority sync: RUNNING/UNSTART (5s cooldown)
boolean isActiveSync = "RUNNING".equals(runStatus) || "UNSTART".equals(runStatus);
// 低频自愈同步: CANCEL/FAIL (60秒冷却), 防止错误状态永久锁死
// Low-frequency self-healing sync: CANCEL/FAIL (60s cooldown) to prevent permanent error state lock.
boolean isRecoverySync = "CANCEL".equals(runStatus) || "FAIL".equals(runStatus);
boolean needSync = isActiveSync || isRecoverySync;
if (needSync) {
// 限流保护:活跃状态 5 秒冷却,自愈状态 60 秒冷却
// Rate limiting protection: 5-second cooldown for active state, 60-second cooldown for self-healing state
long cooldownMs = isActiveSync ? 5000 : 60000;
DocumentEntity localEntity = documentDao.selectOne(new QueryWrapper<DocumentEntity>()
.eq("document_id", dto.getDocumentId()));
@ -134,52 +134,52 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
}
}
// 延迟初始化适配器,仅在确实需要同步时创建
// Lazily initialize adapter; create only when sync is actually needed
if (adapter == null) {
try {
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig);
} catch (Exception e) {
log.warn("同步中断:无法初始化适配器, {}", e.getMessage());
log.warn("Sync interrupt: failed to initialize adapter, {}", e.getMessage());
break;
}
}
// [关键修复] 记录同步前的 Token 数,用于计算增量
// [Critical fix] Record token count before sync to calculate delta
Long oldTokenCount = dto.getTokenCount() != null ? dto.getTokenCount() : 0L;
syncDocumentStatusWithRAG(dto, adapter);
// 计算增量并更新知识库统计 (与定时任务保持一致)
// Calculate delta and update knowledge base stats (consistent with scheduled tasks)
Long newTokenCount = dto.getTokenCount() != null ? dto.getTokenCount() : 0L;
Long tokenDelta = newTokenCount - oldTokenCount;
if (tokenDelta != 0) {
knowledgeBaseService.updateStatistics(datasetId, 0, 0L, tokenDelta);
log.info("懒加载同步: 修正知识库统计, docId={}, tokenDelta={}", dto.getDocumentId(), tokenDelta);
log.info("Lazy sync: correct knowledge base stats, docId={}, tokenDelta={}", dto.getDocumentId(), tokenDelta);
}
}
}
}
log.info("获取文档列表成功,总数: {}", pageData.getTotal());
log.info("Successfully retrieved document list, total: {}", pageData.getTotal());
return pageData;
}
/**
* 将本地记录实体转换为DTO,手动对齐不一致字段 (size -> fileSize, type -> fileType)
* Convert local record entities to DTOs, manually aligning mismatched fields (size -> fileSize, type -> fileType)
*/
private KnowledgeFilesDTO convertEntityToDTO(DocumentEntity entity) {
if (entity == null) {
return null;
}
KnowledgeFilesDTO dto = new KnowledgeFilesDTO();
// 1. 基础字段拷贝
// 1. Copy basic fields
BeanUtils.copyProperties(entity, dto);
// Issue 2: 修正 ID 语义。前端习惯使用 id 作为操作主键。
// 在该模块中,应始终将远程 documentId 映射为 DTO 的 id,确保前端在详情/删除等操作时 ID 一致。
// Issue 2: Correct ID semantics. Frontend convention uses id as the primary key for operations.
// In this module, always map the remote documentId to the DTO id to ensure ID consistency for frontend detail/delete operations.
dto.setId(entity.getDocumentId());
// 2. 将本地记录实体转换为DTO,手动对齐不一致字段 (size -> fileSize, type -> fileType)
// 2. Convert local record entities to DTOs, manually aligning inconsistent fields (size -> fileSize, type -> fileType)
dto.setFileSize(entity.getSize());
dto.setFileType(entity.getType());
dto.setRun(entity.getRun());
@ -187,25 +187,25 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
dto.setTokenCount(entity.getTokenCount());
dto.setError(entity.getError());
// 3. 自定义元数据 JSON 反序列化 (Issue 3)
// 3. Custom metadata JSON deserialization (Issue 3)
if (StringUtils.isNotBlank(entity.getMetaFields())) {
try {
dto.setMetaFields(objectMapper.readValue(entity.getMetaFields(),
new TypeReference<Map<String, Object>>() {
}));
} catch (Exception e) {
log.warn("反序列化 MetaFields 失败, entityId: {}, error: {}", entity.getId(), e.getMessage());
log.warn("Failed to deserialize MetaFields, entityId: {}, error: {}", entity.getId(), e.getMessage());
}
}
// 4. 解析配置 JSON 反序列化
// 4. Parse config JSON deserialization
if (StringUtils.isNotBlank(entity.getParserConfig())) {
try {
dto.setParserConfig(objectMapper.readValue(entity.getParserConfig(),
new com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>() {
}));
} catch (Exception e) {
log.warn("反序列化 ParserConfig 失败, entityId: {}, error: {}", entity.getId(), e.getMessage());
log.warn("Failed to deserialize ParserConfig, entityId: {}, error: {}", entity.getId(), e.getMessage());
}
}
return dto;
@ -213,12 +213,12 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
}
/**
* 同步文档状态与RAG实际状态
* 优化状态同步逻辑,确保解析中状态能够正常显示
* 只有当文档有切片且解析时间超过30秒时,才更新为完成状态
* Sync document status with actual RAG status
* Optimize state synchronization logic to ensure the parsing state displays correctly
* Update to completed status only if document has slices and parsing time exceeds 30 seconds
*/
/**
* 同步文档状态与RAG实际状态 (增强型:支持外部传入适配器)
* Sync document status with actual RAG status (enhanced: supports external adapter injection)
*/
private void syncDocumentStatusWithRAG(KnowledgeFilesDTO dto, KnowledgeBaseAdapter adapter) {
if (dto == null || StringUtils.isBlank(dto.getDocumentId()) || adapter == null) {
@ -229,7 +229,7 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
String datasetId = dto.getDatasetId();
try {
// 使用强类型 ListReq 配合 ID 过滤来获取状态
// Use strongly-typed ListReq with ID filtering to retrieve status
DocumentDTO.ListReq listReq = DocumentDTO.ListReq.builder()
.id(documentId)
.page(1)
@ -242,17 +242,17 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
KnowledgeFilesDTO remoteDto = remoteList.getList().get(0);
String remoteStatus = remoteDto.getStatus();
// 核心状态对齐判别逻辑
// Core state alignment discrimination logic
boolean statusChanged = remoteStatus != null && !remoteStatus.equals(dto.getStatus());
boolean runChanged = remoteDto.getRun() != null && !remoteDto.getRun().equals(dto.getRun());
boolean isProcessing = "RUNNING".equals(remoteDto.getRun()) || "UNSTART".equals(remoteDto.getRun());
// 只要状态有变,或者运行状态有变,或者文件仍在解析中(实时刷进度),就执行同步
// Sync whenever state changes, runtime status changes, or file is still parsing (real-time progress update)
if (statusChanged || runChanged || isProcessing) {
log.info("影子同步:状态变化={},解析中={},文档={},最新状态={},进度={}",
log.info("Shadow sync: state change={}, parsing={}, documents={}, latest state={}, progress={}",
statusChanged, isProcessing, documentId, remoteStatus, remoteDto.getProgress());
// 1. 同步内存 DTO
// 1. Sync in-memory DTO
dto.setStatus(remoteStatus);
dto.setRun(remoteDto.getRun());
dto.setProgress(remoteDto.getProgress());
@ -262,7 +262,7 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
dto.setProcessDuration(remoteDto.getProcessDuration());
dto.setThumbnail(remoteDto.getThumbnail());
// 2. 同步本地影子表
// 2. Sync local shadow table
UpdateWrapper<DocumentEntity> updateWrapper = new UpdateWrapper<DocumentEntity>()
.set("status", remoteStatus)
.set("run", remoteDto.getRun())
@ -275,43 +275,43 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
.eq("document_id", documentId)
.eq("dataset_id", datasetId);
// 序列化元数据同步
// Serialize metadata sync
if (remoteDto.getMetaFields() != null) {
try {
updateWrapper.set("meta_fields",
objectMapper.writeValueAsString(remoteDto.getMetaFields()));
} catch (Exception e) {
log.warn("同步元数据序列化失败: {}", e.getMessage());
log.warn("Failed to serialize sync metadata: {}", e.getMessage());
}
}
// 优先同步 RAG 侧的更新时间,避免本地同步行为覆盖业务修改时间
// Prioritize syncing the update time from the RAG side to prevent local sync from overwriting business modification times
Date lastUpdate = remoteDto.getUpdatedAt() != null ? remoteDto.getUpdatedAt() : new Date();
updateWrapper.set("updated_at", lastUpdate);
updateWrapper.set("last_sync_at", new Date()); // 记录影子库同步时间
updateWrapper.set("last_sync_at", new Date()); // Record shadow DB sync time
documentDao.update(null, updateWrapper);
}
} else {
// Issue 6: 远程列表为空,可能是文档已删除,也可能是适配器调用出了问题
// [Bug Fix] P2: 仅当远程确实返回了合法空列表时才标记 CANCEL
// 同时更新 last_sync_at,配合 P1 冷却机制防止高频误判
log.warn("远程同步感知:RAGFlow 返回空文档列表, docId={}, 当前本地状态={}",
// Issue 6: Remote list is empty; documents may have been deleted or the adapter call failed
// [Bug Fix] P2: Mark CANCEL only if the remote returns a valid empty list
// Update last_sync_at simultaneously, working with P1 cooldown mechanism to prevent high-frequency false positives
log.warn("Remote sync detected: RAGFlow returned empty document list, docId={}, current local state={}",
documentId, dto.getRun());
dto.setRun("CANCEL");
dto.setError("文档在远程服务中已被删除");
dto.setError("Document has been deleted on remote service");
documentDao.update(null, new UpdateWrapper<DocumentEntity>()
.set("run", "CANCEL")
.set("error", "文档在远程服务中已被删除")
.set("error", "Document has been deleted on remote service")
.set("updated_at", new Date())
.set("last_sync_at", new Date())
.eq("document_id", documentId));
}
} catch (Exception e) {
// [Bug Fix] P2: 适配器调用异常时不标记 CANCEL,避免因网络/反序列化问题导致误判
// 仅记录日志,等下次同步周期重试
log.warn("同步文档状态时适配器调用失败(不标记CANCEL), documentId: {}, error: {}",
// [Bug Fix] P2: Do not mark CANCEL when adapter call throws an exception, to avoid false positives due to network/deserialization issues
// Log only; retry on next sync cycle
log.warn("Adapter call failed during document status sync (do not mark CANCEL), documentId: {}, error: {}",
documentId, e.getMessage());
}
}
@ -322,38 +322,38 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
throw new RenException(ErrorCode.RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL);
}
log.info("=== 开始根据documentId获取文档 ===");
log.info("=== Start fetching document by documentId ===");
log.info("documentId: {}, datasetId: {}", documentId, datasetId);
try {
// 获取RAG配置
// Get RAG config
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
// 提取适配器类型
// Extract adapter type
String adapterType = extractAdapterType(ragConfig);
// 使用适配器工厂获取适配器实例
// Get adapter instance via adapter factory
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(adapterType, ragConfig);
// 使用适配器获取文档详情
// Fetch document details using the adapter
DocumentDTO.InfoVO info = adapter.getDocumentById(datasetId, documentId);
if (info != null) {
log.info("获取文档详情成功,documentId: {}", documentId);
log.info("Successfully retrieved document details, documentId: {}", documentId);
return info;
} else {
throw new RenException(ErrorCode.Knowledge_Base_RECORD_NOT_EXISTS);
}
} catch (Exception e) {
log.error("根据documentId获取文档失败: {}", e.getMessage(), e);
log.error("Failed to get document by documentId: {}", e.getMessage(), e);
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} finally {
log.info("=== 根据documentId获取文档操作结束 ===");
log.info("=== End of document operation based on documentId ===");
}
}
@ -365,21 +365,21 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
throw new RenException(ErrorCode.PARAMS_GET_ERROR);
}
log.info("=== 开始文档上传操作 (强一致性优化) ===");
log.info("=== Starting document upload operation (strong consistency optimization) ===");
// 1. 准备工作 (非事务性)
// 1. Preparation (non-transactional)
String fileName = StringUtils.isNotBlank(name) ? name : file.getOriginalFilename();
if (StringUtils.isBlank(fileName)) {
throw new RenException(ErrorCode.RAG_FILE_NAME_NOT_NULL);
}
log.info("1. 发起远程上传: datasetId={}, fileName={}", datasetId, fileName);
log.info("1. Initiate remote upload: datasetId={}, fileName={}", datasetId, fileName);
// 获取适配器 (非事务性)
// Get adapter (non-transactional)
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig);
// 构造强类型请求 DTO
// Construct strongly-typed request DTO
DocumentDTO.UploadReq uploadReq = DocumentDTO.UploadReq.builder()
.datasetId(datasetId)
.file(file)
@ -387,40 +387,40 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
.metaFields(metaFields)
.build();
// 转换分块方法 (String -> Enum)
// Convert chunking method (String -> Enum)
if (StringUtils.isNotBlank(chunkMethod)) {
try {
uploadReq.setChunkMethod(DocumentDTO.InfoVO.ChunkMethod.valueOf(chunkMethod.toUpperCase()));
} catch (Exception e) {
log.warn("无效的分块方法: {}, 将使用后台默认配置", chunkMethod);
log.warn("Invalid chunking method: {}, using backend default config", chunkMethod);
}
}
// 转换解析配置 (Map -> DTO)
// Convert parse config (Map -> DTO)
if (parserConfig != null && !parserConfig.isEmpty()) {
uploadReq.setParserConfig(objectMapper.convertValue(parserConfig, DocumentDTO.InfoVO.ParserConfig.class));
}
// 执行远程上传 (耗时 IO,在事务之外)
// Execute remote upload (time-consuming IO, outside transaction)
KnowledgeFilesDTO result = adapter.uploadDocument(uploadReq);
if (result == null || StringUtils.isBlank(result.getDocumentId())) {
throw new RenException(ErrorCode.RAG_API_ERROR, "远程上传成功但未返回有效 DocumentID");
throw new RenException(ErrorCode.RAG_API_ERROR, "Remote upload succeeded but returned no valid DocumentID");
}
// 2. 本地持久化 (通过 self 调用以激活 @Transactional 代理)
log.info("2. 同步保存本地影子记录: documentId={}", result.getDocumentId());
// 2. Local persistence (call via self to activate @Transactional proxy)
log.info("2. Synchronously save local shadow record: documentId={}", result.getDocumentId());
self.saveDocumentShadow(datasetId, result, fileName, chunkMethod, parserConfig);
log.info("=== 文档上传与影子记录保存成功 ===");
log.info("=== Document upload and shadow record saved successfully ===");
return result;
}
/**
* 原子化保存影子记录(Upsert 语义)
* 若 document_id 已存在则更新,不存在则插入,避免 UNIQUE 约束冲突
* Atomically save shadow record (Upsert semantics)
* Update if document_id exists, insert otherwise, to avoid UNIQUE constraint conflicts
*
* @return true=新插入, false=更新已有记录
* @return true=New insertion, false=Update existing record
*/
@Transactional(rollbackFor = Exception.class)
public boolean saveDocumentShadow(String datasetId, KnowledgeFilesDTO result, String originalName, String chunkMethod,
@ -437,7 +437,7 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
try {
entity.setParserConfig(objectMapper.writeValueAsString(parserConfig));
} catch (Exception e) {
log.warn("序列化解析配置失败: {}", e.getMessage());
log.warn("Failed to parse serialized config: {}", e.getMessage());
}
}
@ -452,34 +452,34 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
entity.setTokenCount(result.getTokenCount());
entity.setEnabled(1);
// 持久化元数据
// Persist metadata
if (result.getMetaFields() != null) {
try {
entity.setMetaFields(objectMapper.writeValueAsString(result.getMetaFields()));
} catch (Exception e) {
log.warn("持久化影子元数据失败: {}", e.getMessage());
log.warn("Failed to persist shadow metadata: {}", e.getMessage());
}
}
// 优先同步 RAG 侧的时间戳,若无则使用本地时间
// Prefer syncing RAG-side timestamp; fall back to local time if unavailable
entity.setCreatedAt(result.getCreatedAt() != null ? result.getCreatedAt() : new Date());
entity.setUpdatedAt(result.getUpdatedAt() != null ? result.getUpdatedAt() : new Date());
// Upsert: 检查 document_id 是否已存在,存在则更新,不存在则插入
// Upsert: Check if document_id exists; update if present, insert if not
DocumentEntity existing = documentDao.selectOne(
new QueryWrapper<DocumentEntity>().eq("document_id", entity.getDocumentId()));
if (existing != null) {
entity.setId(existing.getId());
entity.setCreatedAt(existing.getCreatedAt()); // 保留原始创建时间
entity.setCreatedAt(existing.getCreatedAt()); // Preserve original creation time
documentDao.updateById(entity);
log.info("影子记录已更新: documentId={}", entity.getDocumentId());
log.info("Shadow record updated: documentId={}", entity.getDocumentId());
return false;
} else {
documentDao.insert(entity);
// 新增记录时递增数据集文档总数统计
// Increment dataset document count when adding new record
knowledgeBaseService.updateStatistics(datasetId, 1, 0L, 0L);
log.info("影子记录已插入: documentId={}, datasetId={}", entity.getDocumentId(), datasetId);
log.info("Shadow record inserted: documentId={}, datasetId={}", entity.getDocumentId(), datasetId);
return true;
}
}
@ -492,16 +492,16 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
}
List<String> documentIds = req.getIds();
log.info("=== 开始批量删除文档: datasetId={}, count={} ===", datasetId, documentIds.size());
log.info("=== Starting batch document deletion: datasetId={}, count={} ===", datasetId, documentIds.size());
// 1. 批量权限与状态预审
// 1. Batch permission and status pre-check
List<DocumentEntity> entities = documentDao.selectList(
new QueryWrapper<DocumentEntity>()
.eq("dataset_id", datasetId)
.in("document_id", documentIds));
if (entities.size() != documentIds.size()) {
log.warn("部分文档不存在或归属权异常: 预期={}, 实际={}", documentIds.size(), entities.size());
log.warn("Some documents are missing or have ownership issues: expected={}, actual={}", documentIds.size(), entities.size());
throw new RenException(ErrorCode.NO_PERMISSION);
}
@ -509,69 +509,69 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
long totalTokenDelta = 0;
for (DocumentEntity entity : entities) {
// 拦截正在解析中的文档的删除请求
// [Bug Fix] 判断解析中应该用 run 字段(RUNNING), 而非 status 字段
// status="1" 是"启用/正常"的意思, 不是"解析中"
// Intercept delete requests for documents currently being parsed
// [Bug Fix] Use the run field (RUNNING) instead of the status field to determine parsing state
// status="1" means "Enabled/Normal", not "Parsing"
if ("RUNNING".equals(entity.getRun())) {
log.warn("拦截解析中文件的删除请求: docId={}", entity.getDocumentId());
log.warn("Intercepting delete request for file being parsed: docId={}", entity.getDocumentId());
throw new RenException(ErrorCode.RAG_DOCUMENT_PARSING_DELETE_ERROR);
}
totalChunkDelta += entity.getChunkCount() != null ? entity.getChunkCount() : 0L;
totalTokenDelta += entity.getTokenCount() != null ? entity.getTokenCount() : 0L;
}
// 2. 获取适配器 (非事务性)
// 2. Get adapter (non-transactional)
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig);
// 3. 执行远程删除
// 3. Execute remote deletion
try {
adapter.deleteDocument(datasetId, req);
log.info("远程批量删除请求成功");
log.info("Remote batch delete request succeeded");
} catch (Exception e) {
log.error("远程删除请求失败,中止本地清理以避免数据不一致: {}", e.getMessage());
log.error("Remote deletion request failed; aborting local cleanup to prevent data inconsistency: {}", e.getMessage());
throw new RenException(e.getMessage());
}
// 4. 原子化清理本地影子记录并同步统计数据
// 4. Atomically clean up local shadow records and sync statistics
self.deleteDocumentShadows(documentIds, datasetId, totalChunkDelta, totalTokenDelta);
// 5. 清理缓存
// 5. Clear cache
try {
String cacheKey = RedisKeys.getKnowledgeBaseCacheKey(datasetId);
redisUtils.delete(cacheKey);
log.info("已驱逐数据集缓存: {}", cacheKey);
log.info("Evicted dataset cache: {}", cacheKey);
} catch (Exception e) {
log.warn("驱逐 Redis 缓存失败: {}", e.getMessage());
log.warn("Failed to evict Redis cache: {}", e.getMessage());
}
log.info("=== 批量文档清理完成 ===");
log.info("=== Batch document cleanup complete ===");
}
/**
* 批量原子化删除影子记录并同步父表统计
* Atomically delete shadow records in batch and sync parent table statistics
*/
@Transactional(rollbackFor = Exception.class)
public void deleteDocumentShadows(List<String> documentIds, String datasetId, Long chunkDelta, Long tokenDelta) {
// 1. 物理删除记录
// 1. Physically delete records
int deleted = documentDao.delete(
new QueryWrapper<DocumentEntity>()
.eq("dataset_id", datasetId)
.in("document_id", documentIds));
if (deleted > 0) {
// 2. 同步更新数据集统计信息
// 2. Synchronously update dataset statistics
knowledgeBaseService.updateStatistics(datasetId, -documentIds.size(), -chunkDelta, -tokenDelta);
log.info("已同步扣减数据集统计: datasetId={}, chunks={}, tokens={}", datasetId, chunkDelta, tokenDelta);
log.info("Synced dataset stats deduction: datasetId={}, chunks={}, tokens={}", datasetId, chunkDelta, tokenDelta);
}
}
/**
* 获取文件类型 - 支持RAG四种文档格式类型
* Get file type - supports four RAG document format types
*/
private String getFileType(String fileName) {
if (StringUtils.isBlank(fileName)) {
log.warn("文件名为空,返回unknown类型");
log.warn("Filename is empty, returning unknown type");
return "unknown";
}
@ -580,57 +580,57 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1) {
String extension = fileName.substring(lastDotIndex + 1).toLowerCase();
// 文档格式类型
// Document format type
String[] documentTypes = { "pdf", "doc", "docx", "txt", "md", "mdx" };
String[] spreadsheetTypes = { "csv", "xls", "xlsx" };
String[] presentationTypes = { "ppt", "pptx" };
// 检查文档类型
// Check document type
for (String type : documentTypes) {
if (type.equals(extension)) {
return "document";
}
}
// 检查表格类型
// Check table type
for (String type : spreadsheetTypes) {
if (type.equals(extension)) {
return "spreadsheet";
}
}
// 检查幻灯片类型
// Check slide type
for (String type : presentationTypes) {
if (type.equals(extension)) {
return "presentation";
}
}
// 返回原始扩展名作为文件类型
// Return original extension as file type
return extension;
}
return "unknown";
} catch (Exception e) {
log.error("获取文件类型失败: ", e);
log.error("Failed to get file type: ", e);
return "unknown";
}
}
/**
* 从RAG配置中提取适配器类型
* Extract adapter type from RAG config
*/
private String extractAdapterType(Map<String, Object> config) {
if (config == null) {
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND);
}
// 从配置中提取type字段
// Extract type field from config
String adapterType = (String) config.get("type");
if (StringUtils.isBlank(adapterType)) {
throw new RenException(ErrorCode.RAG_ADAPTER_TYPE_NOT_FOUND);
}
// 验证适配器类型是否已注册
// Verify if adapter type is registered
if (!KnowledgeBaseAdapterFactory.isAdapterTypeRegistered(adapterType)) {
throw new RenException(ErrorCode.RAG_ADAPTER_TYPE_NOT_SUPPORTED, "适配器类型未注册: " + adapterType);
throw new RenException(ErrorCode.RAG_ADAPTER_TYPE_NOT_SUPPORTED, "Adapter type not registered: " + adapterType);
}
return adapterType;
@ -642,27 +642,27 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
throw new RenException(ErrorCode.RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL);
}
log.info("=== 开始解析文档(切块) ===");
log.info("=== Start parsing document (chunking) ===");
log.info("datasetId: {}, documentIds: {}", datasetId, documentIds);
try {
// 获取RAG配置
// Get RAG config
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
// 提取适配器类型
// Extract adapter type
String adapterType = extractAdapterType(ragConfig);
// 获取知识库适配器
// Get knowledge base adapter
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(adapterType, ragConfig);
log.debug("解析文档参数: documentIds: {}", documentIds);
log.debug("Parsing document parameters: documentIds: {}", documentIds);
// 调用适配器解析文档
// Call adapter to parse document
boolean result = adapter.parseDocuments(datasetId, documentIds);
if (result) {
log.info("文档解析命令发送成功,准备同步本地影子库状态,datasetId: {}, documentIds: {}", datasetId, documentIds);
// 指令成功后立即更新本地影子状态为 RUNNING 和 解析中(1),确保 Local-First 列表能立即反馈
log.info("Document parsing command sent successfully, preparing to sync local shadow DB state, datasetId: {}, documentIds: {}", datasetId, documentIds);
// Immediately update the local shadow state to RUNNING and Parsing(1) after command success to ensure the Local-First list reflects changes instantly.
documentDao.update(null, new UpdateWrapper<DocumentEntity>()
.set("run", "RUNNING")
.set("status", "1")
@ -670,23 +670,23 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
.eq("dataset_id", datasetId)
.in("document_id", documentIds));
log.info("文档本地状态已更新为 RUNNING");
log.info("Local document status updated to RUNNING");
} else {
log.error("文档解析失败,datasetId: {}, documentIds: {}", datasetId, documentIds);
throw new RenException(ErrorCode.RAG_API_ERROR, "文档解析失败");
log.error("Document parsing failed, datasetId: {}, documentIds: {}", datasetId, documentIds);
throw new RenException(ErrorCode.RAG_API_ERROR, "Document parsing failed");
}
return result;
} catch (Exception e) {
log.error("解析文档失败: {}", e.getMessage(), e);
log.error("Failed to parse document: {}", e.getMessage(), e);
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} finally {
log.info("=== 解析文档操作结束 ===");
log.info("=== Parse document operations end ===");
}
}
@ -696,7 +696,7 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
throw new RenException(ErrorCode.RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL);
}
log.info("=== 开始列出切片: datasetId={}, documentId={}, req={} ===", datasetId, documentId, req);
log.info("=== Start listing chunks: datasetId={}, documentId={}, req={} ===", datasetId, documentId, req);
try {
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
@ -704,27 +704,27 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
ragConfig);
ChunkDTO.ListVO result = adapter.listChunks(datasetId, documentId, req);
log.info("切片列表获取成功: datasetId={}, total={}", datasetId, result.getTotal());
log.info("Slice list retrieved successfully: datasetId={}, total={}", datasetId, result.getTotal());
return result;
} catch (Exception e) {
log.error("列出切片失败: {}", e.getMessage(), e);
log.error("Failed to list slices: {}", e.getMessage(), e);
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} finally {
log.info("=== 列出切片操作结束 ===");
log.info("=== List slice operations end ===");
}
}
@Override
public RetrievalDTO.ResultVO retrievalTest(RetrievalDTO.TestReq req) {
if (CollectionUtils.isEmpty(req.getDatasetIds())) {
throw new RenException("未指定召回测试的知识库");
throw new RenException("Knowledge base not specified for recall test");
}
log.info("=== 开始召回测试: req={} ===", req);
log.info("=== Starting recall test: req={} ===", req);
try {
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(req.getDatasetIds().get(0));
@ -732,24 +732,24 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
ragConfig);
RetrievalDTO.ResultVO result = adapter.retrievalTest(req);
log.info("召回测试成功: total={}", result != null ? result.getTotal() : 0);
log.info("Recall test successful: total={}", result != null ? result.getTotal() : 0);
return result;
} catch (Exception e) {
log.error("召回测试失败: {}", e.getMessage(), e);
log.error("Recall test failed: {}", e.getMessage(), e);
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} finally {
log.info("=== 召回测试操作结束 ===");
log.info("=== Recall test operations end ===");
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteDocumentsByDatasetId(String datasetId) {
log.info("级联清理数据集文档: datasetId={}", datasetId);
log.info("Cascade cleanup of dataset documents: datasetId={}", datasetId);
List<DocumentEntity> list = documentDao
.selectList(new QueryWrapper<DocumentEntity>().eq("dataset_id", datasetId));
if (list == null || list.isEmpty())
@ -757,20 +757,20 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
List<String> docIds = list.stream().map(DocumentEntity::getDocumentId).toList();
// 封包调用现有删除逻辑 (含 RAG 物理删除)
// Package call to existing deletion logic (including RAG physical deletion)
DocumentDTO.BatchIdReq req = DocumentDTO.BatchIdReq.builder().ids(docIds).build();
this.deleteDocuments(datasetId, req);
}
@Override
public int syncDocumentsFromRAG(String datasetId) {
log.info("=== 开始从RAGFlow全量同步文档到本地影子表: datasetId={} ===", datasetId);
log.info("=== Starting full document sync from RAGFlow to local shadow table: datasetId={} ===", datasetId);
// 1. 获取适配器
// 1. Get adapter
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig);
// 2. 分页拉取远端所有文档
// 2. Fetch all remote documents via pagination
List<KnowledgeFilesDTO> allRemoteDocs = new ArrayList<>();
int pageNum = 1;
int pageSize = 100;
@ -790,20 +790,20 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
pageNum++;
}
// 3. 获取本地已有文档
// 3. Get existing local documents
List<DocumentEntity> localDocs = documentDao.selectList(
new QueryWrapper<DocumentEntity>().eq("dataset_id", datasetId));
Set<String> localDocIds = localDocs.stream()
.map(DocumentEntity::getDocumentId)
.collect(Collectors.toSet());
// 4. 远端文档ID集合
// 4. Remote document ID set
Set<String> remoteDocIds = allRemoteDocs.stream()
.map(KnowledgeFilesDTO::getDocumentId)
.filter(id -> id != null)
.collect(Collectors.toSet());
// 5. 补充: 插入远端存在但本地缺失的文档
// 5. Supplement: insert documents present remotely but missing locally
List<KnowledgeFilesDTO> newDocs = allRemoteDocs.stream()
.filter(doc -> doc.getDocumentId() != null && !localDocIds.contains(doc.getDocumentId()))
.collect(Collectors.toList());
@ -813,7 +813,7 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
for (KnowledgeFilesDTO doc : newDocs) {
try {
self.saveDocumentShadow(datasetId, doc, doc.getName(), doc.getChunkMethod(), doc.getParserConfig());
// 同步远端已有的 token/chunk 统计
// Synchronize existing token/chunk statistics from the remote
Long tokenCount = doc.getTokenCount() != null ? doc.getTokenCount() : 0L;
long chunkCount = doc.getChunkCount() != null ? doc.getChunkCount().longValue() : 0L;
if (tokenCount > 0 || chunkCount > 0) {
@ -821,13 +821,13 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
}
syncCount++;
} catch (Exception e) {
log.warn("同步单个文档影子记录失败: docId={}, error={}", doc.getDocumentId(), e.getMessage());
log.warn("Failed to sync shadow record for single document: docId={}, error={}", doc.getDocumentId(), e.getMessage());
}
}
log.info("从RAGFlow新增同步 {} 个文档影子记录, datasetId={}", syncCount, datasetId);
log.info("Synced {} new document shadow records from RAGFlow, datasetId={}", syncCount, datasetId);
}
// 6. 清理: 删除远端已不存在但本地仍保留的影子记录
// 6. Cleanup: Remove shadow records that exist locally but no longer exist remotely
List<DocumentEntity> deletedDocs = localDocs.stream()
.filter(entity -> !remoteDocIds.contains(entity.getDocumentId()))
.collect(Collectors.toList());
@ -844,14 +844,14 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
}
try {
self.deleteDocumentShadows(deletedDocIds, datasetId, totalChunkDelta, totalTokenDelta);
log.info("清理远端已删除的影子记录: {} 个, datasetId={}", deletedDocs.size(), datasetId);
log.info("Cleaned up shadow records deleted remotely: {} items, datasetId={}", deletedDocs.size(), datasetId);
} catch (Exception e) {
log.warn("清理远端已删除的影子记录失败: datasetId={}, error={}", datasetId, e.getMessage());
log.warn("Failed to clean up shadow records deleted remotely: datasetId={}, error={}", datasetId, e.getMessage());
}
}
// 7. 全量更新: 远端和本地都存在的文档,以远端为准同步所有字段
// 处理 RAGFlow 复用 documentId 重传、远端编辑后元数据变化等场景
// 7. Full update: For documents existing in both remote and local, sync all fields using remote as the source of truth
// Handle scenarios such as RAGFlow reusing documentId for re-upload and metadata changes after remote editing
Map<String, KnowledgeFilesDTO> remoteDocMap = allRemoteDocs.stream()
.filter(doc -> doc.getDocumentId() != null)
.collect(Collectors.toMap(KnowledgeFilesDTO::getDocumentId, doc -> doc, (a, b) -> b));
@ -864,11 +864,11 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
String docId = entry.getKey();
DocumentEntity local = localDocMap.get(docId);
if (local == null) {
continue; // 不在本地,由步骤5处理
continue; // Not local, handled by step 5
}
KnowledgeFilesDTO remote = entry.getValue();
// 全量字段更新(以远端为准),确保本地与 RAGFlow 完全一致
// Full field update (remote as source of truth) to ensure local data is fully consistent with RAGFlow
UpdateWrapper<DocumentEntity> updateWrapper = new UpdateWrapper<DocumentEntity>()
.set("run", remote.getRun())
.set("status", remote.getStatus() != null ? remote.getStatus() : local.getStatus())
@ -893,13 +893,13 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
try {
updateWrapper.set("meta_fields", objectMapper.writeValueAsString(remote.getMetaFields()));
} catch (Exception e) {
log.warn("同步更新元数据序列化失败: docId={}, error={}", docId, e.getMessage());
log.warn("Failed to serialize metadata for sync update: docId={}, error={}", docId, e.getMessage());
}
}
documentDao.update(null, updateWrapper);
// 同步统计差异(chunk/token 计数变化时修正父表)
// Synchronize statistical discrepancies (correct parent table when chunk/token counts change)
Long remoteTokenCount = remote.getTokenCount() != null ? remote.getTokenCount() : 0L;
Long localTokenCount = local.getTokenCount() != null ? local.getTokenCount() : 0L;
long remoteChunkCount = remote.getChunkCount() != null ? remote.getChunkCount().longValue() : 0L;
@ -908,16 +908,16 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
long chunkDelta = remoteChunkCount - localChunkCount;
if (tokenDelta != 0 || chunkDelta != 0) {
knowledgeBaseService.updateStatistics(datasetId, 0, chunkDelta, tokenDelta);
log.info("影子更新: 修正知识库统计, docId={}, chunkDelta={}, tokenDelta={}", docId, chunkDelta, tokenDelta);
log.info("Shadow update: corrected knowledge base stats, docId={}, chunkDelta={}, tokenDelta={}", docId, chunkDelta, tokenDelta);
}
updateCount++;
}
if (syncCount == 0 && deletedDocs.isEmpty() && updateCount == 0) {
log.info("本地影子表已与RAGFlow完全同步, datasetId={}", datasetId);
log.info("Local shadow table fully synced with RAGFlow, datasetId={}", datasetId);
} else {
log.info("同步完成: 新增={}, 清理={}, 更新={}, datasetId={}", syncCount, deletedDocs.size(), updateCount, datasetId);
log.info("Sync complete: added={}, cleaned={}, updated={}, datasetId={}", syncCount, deletedDocs.size(), updateCount, datasetId);
}
return syncCount;
@ -925,54 +925,54 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
@Override
public void syncRunningDocuments() {
// 1. 查询所有 RUNNING 状态的文档
// 1. Query all documents in RUNNING state
List<DocumentEntity> runningDocs = documentDao.selectList(
new QueryWrapper<DocumentEntity>()
.eq("run", "RUNNING")
.eq("status", "1") // 仅同步启用的文档
.eq("status", "1") // Sync only enabled documents
);
if (runningDocs == null || runningDocs.isEmpty()) {
return;
}
log.info("定时任务: 发现 {} 个文档正在解析中,开始同步...", runningDocs.size());
log.info("Scheduled task: Found {} documents being parsed, starting sync...", runningDocs.size());
// 2. 按 DatasetID 分组,复用 Adapter
// 2. Group by DatasetID, reuse Adapter
Map<String, List<DocumentEntity>> groupedDocs = runningDocs.stream()
.collect(Collectors.groupingBy(DocumentEntity::getDatasetId));
groupedDocs.forEach((datasetId, docs) -> {
KnowledgeBaseAdapter adapter = null;
try {
// 初始化 Adapter (每个数据集只初始化一次)
// Initialize Adapter (initialize once per dataset)
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig);
} catch (Exception e) {
log.warn("无法为数据集 {} 初始化适配器,跳过同步: {}", datasetId, e.getMessage());
log.warn("Failed to initialize adapter for dataset {}, skipping sync: {}", datasetId, e.getMessage());
return;
}
for (DocumentEntity doc : docs) {
try {
// 构造临时 DTO 传给同步方法
// Construct a temporary DTO to pass to the sync method.
KnowledgeFilesDTO dto = convertEntityToDTO(doc);
// 记录同步前的 Token 数
// Record token count before sync
Long oldTokenCount = dto.getTokenCount() != null ? dto.getTokenCount() : 0L;
syncDocumentStatusWithRAG(dto, adapter);
// 3. [关键修复] 计算增量并更新知识库统计
// 3. [Critical Fix] Calculate the delta and update knowledge base statistics
Long newTokenCount = dto.getTokenCount() != null ? dto.getTokenCount() : 0L;
Long tokenDelta = newTokenCount - oldTokenCount;
// 仅当状态变为 SUCCESS 且 Token 数有变化时更新统计
// Update statistics only when status changes to SUCCESS and token count changes
if (tokenDelta != 0) {
knowledgeBaseService.updateStatistics(datasetId, 0, 0L, tokenDelta);
log.info("定时任务: 同步修正知识库统计, docId={}, tokenDelta={}", dto.getDocumentId(), tokenDelta);
log.info("Scheduled task: Sync and correct knowledge base stats, docId={}, tokenDelta={}", dto.getDocumentId(), tokenDelta);
}
} catch (Exception e) {
log.error("同步文档 {} 失败: {}", doc.getDocumentId(), e.getMessage());
log.error("Failed to sync document {}: {}", doc.getDocumentId(), e.getMessage());
}
}
});

View file

@ -24,14 +24,14 @@ import xiaozhi.modules.model.entity.ModelConfigEntity;
import xiaozhi.modules.model.service.ModelConfigService;
/**
* OpenAI风格API的LLM服务实现
* 支持阿里云、DeepSeek、ChatGLM等兼容OpenAI API的模型
* LLM service implementation for OpenAI-style API
* Supports models compatible with OpenAI API, such as Alibaba Cloud, DeepSeek, and ChatGLM
*/
@Slf4j
@Service
public class OpenAIStyleLLMServiceImpl implements LLMService {
// 需要禁用思考模式的平台域名及其对应参数
// Platform domains requiring thinking mode disabled and their corresponding parameters
private static final Map<String, Map<String, Object>> THINKING_DISABLED_DOMAINS = new LinkedHashMap<>();
static {
THINKING_DISABLED_DOMAINS.put("aliyuncs.com", Map.of("enable_thinking", false));
@ -48,21 +48,21 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
private final RestTemplate restTemplate = new RestTemplate();
/**
* 根据域名自动禁用思考模式
* Automatically disable thinking mode based on domain
*/
private void applyThinkingDisabled(String baseUrl, Map<String, Object> requestBody) {
for (Map.Entry<String, Map<String, Object>> entry : THINKING_DISABLED_DOMAINS.entrySet()) {
if (baseUrl.contains(entry.getKey())) {
requestBody.putAll(entry.getValue());
log.info("为域名 {} 禁用思考模式,参数: {}", baseUrl, entry.getValue());
log.info("Disable thinking mode for domain {}, params: {}", baseUrl, entry.getValue());
break;
}
}
}
private static final String DEFAULT_SUMMARY_PROMPT = "你是一个经验丰富的记忆总结者,擅长将对话内容进行总结摘要,遵循以下规则:\n1、总结用户的重要信息,以便在未来的对话中提供更个性化的服务\n2、不要重复总结,不要遗忘之前记忆,除非原来的记忆超过了1800字,否则不要遗忘、不要压缩用户的历史记忆\n3、用户操控的设备音量、播放音乐、天气、退出、不想对话等和用户本身无关的内容,这些信息不需要加入到总结中\n4、聊天内容中的今天的日期时间、今天的天气情况与用户事件无关的数据,这些信息如果当成记忆存储会影响后续对话,这些信息不需要加入到总结中\n5、不要把设备操控的成果结果和失败结果加入到总结中,也不要把用户的一些废话加入到总结中\n6、不要为了总结而总结,如果用户的聊天没有意义,请返回原来的历史记录也是可以的\n7、只需要返回总结摘要,严格控制在1800字内\n8、不要包含代码、xml,不需要解释、注释和说明,保存记忆时仅从对话提取信息,不要混入示例内容\n9、如果提供了历史记忆,请将新对话内容与历史记忆进行智能合并,保留有价值的历史信息,同时添加新的重要信息\n\n历史记忆:\n{history_memory}\n\n新对话内容:\n{conversation}";
private static final String DEFAULT_SUMMARY_PROMPT = "You are an experienced memory summarizer, skilled at summarizing conversation content. Follow these rules: \n 1. Summarize important user information to provide more personalized service in future conversations. 2. Do not repeat summaries or forget previous memories. Unless the original memory exceeds 1800 characters, do not forget or compress the user's historical memory. 3. Do not include content unrelated to the user, such as device volume control, music playback, weather, exit commands, or refusal to converse. 4. Do not include data unrelated to user events, such as today's date/time or today's weather, as storing this as memory affects subsequent conversations. 5. Do not include success or failure results of device control, nor include user filler words. 6. Do not summarize for the sake of summarizing. If the user's chat is meaningless, returning the original history is acceptable. 7. Return only the summary, strictly within 1800 characters. 8. Do not include code or XML. No explanations, comments, or descriptions. Extract information only from the conversation when saving memory; do not mix in example content. 9. If historical memory is provided, intelligently merge new conversation content with historical memory, preserving valuable historical information while adding new important information. Historical Memory: {history_memory} New Conversation Content: {conversation}";
private static final String DEFAULT_TITLE_PROMPT = "请根据以下对话内容,生成一个简洁的会话标题(约15字以内),只返回标题,不要包含任何解释或标点符号:\n{conversation}";
private static final String DEFAULT_TITLE_PROMPT = "Generate a concise session title (approx. 15 chars) based on the following conversation. Return only the title, with no explanations or punctuation: \n{conversation}";
@Override
public String generateSummary(String conversation) {
@ -77,24 +77,24 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
@Override
public String generateSummary(String conversation, String promptTemplate, String modelId) {
if (!isAvailable()) {
log.warn("LLM服务不可用,无法生成总结");
return "LLM服务不可用,无法生成总结";
log.warn("LLM service unavailable, unable to generate summary");
return "LLM service unavailable, unable to generate summary";
}
try {
// 从智控台获取LLM模型配置
// Fetch LLM model config from Console
ModelConfigEntity llmConfig;
if (modelId != null && !modelId.trim().isEmpty()) {
// 通过具体模型ID获取配置
// Get config by specific model ID
llmConfig = modelConfigService.getModelByIdFromCache(modelId);
} else {
// 保持向后兼容,使用默认配置
// Maintain backward compatibility using default config
llmConfig = getDefaultLLMConfig();
}
if (llmConfig == null || llmConfig.getConfigJson() == null) {
log.error("未找到可用的LLM模型配置,modelId: {}", modelId);
return "未找到可用的LLM模型配置";
log.error("No available LLM model config found, modelId: {}", modelId);
return "No available LLM model config found";
}
JSONObject configJson = llmConfig.getConfigJson();
@ -105,15 +105,15 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
Integer maxTokens = configJson.getInt("max_tokens");
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
log.error("LLM配置不完整,baseUrl或apiKey为空");
return "LLM配置不完整,无法生成总结";
log.error("LLM config incomplete: baseUrl or apiKey is empty");
return "LLM config incomplete, unable to generate summary";
}
// 构建提示词
// Build prompt
String prompt = (promptTemplate != null ? promptTemplate : DEFAULT_SUMMARY_PROMPT).replace("{conversation}",
conversation);
// 构建请求体
// Build request body
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("model", model != null ? model : "gpt-3.5-turbo");
@ -125,17 +125,17 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
requestBody.put("temperature", temperature != null ? temperature : 0.7);
requestBody.put("max_tokens", maxTokens != null ? maxTokens : 2000);
// 禁用思考模式
// Disable thinking mode
applyThinkingDisabled(baseUrl, requestBody);
// 发送HTTP请求
// Send HTTP request
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer " + apiKey);
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
// 构建完整的API URL
// Build the complete API URL
String apiUrl = baseUrl;
if (!apiUrl.endsWith("/chat/completions")) {
if (!apiUrl.endsWith("/")) {
@ -156,13 +156,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
return messageObj.getStr("content");
}
} else {
log.error("LLM API调用失败,状态码:{},响应:{}", response.getStatusCode(), response.getBody());
log.error("LLM API call failed, status code: {}, response: {}", response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
log.error("调用LLM服务生成总结时发生异常,modelId: {}", modelId, e);
log.error("Exception occurred while calling LLM service to generate summary, modelId: {}", modelId, e);
}
return "生成总结失败,请稍后重试";
return "Failed to generate summary, please try again later";
}
@Override
@ -174,12 +174,12 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
public String generateSummaryWithHistory(String conversation, String historyMemory, String promptTemplate,
String modelId) {
if (!isAvailable()) {
log.warn("LLM服务不可用,无法生成总结");
return "LLM服务不可用,无法生成总结";
log.warn("LLM service unavailable, unable to generate summary");
return "LLM service unavailable, unable to generate summary";
}
try {
// 从智控台获取LLM模型配置
// Fetch LLM model config from Console
ModelConfigEntity llmConfig;
if (modelId != null && !modelId.trim().isEmpty()) {
llmConfig = modelConfigService.getModelByIdFromCache(modelId);
@ -188,8 +188,8 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
}
if (llmConfig == null || llmConfig.getConfigJson() == null) {
log.error("未找到可用的LLM模型配置,modelId: {}", modelId);
return "未找到可用的LLM模型配置";
log.error("No available LLM model config found, modelId: {}", modelId);
return "No available LLM model config found";
}
JSONObject configJson = llmConfig.getConfigJson();
@ -198,16 +198,16 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String apiKey = configJson.getStr("api_key");
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
log.error("LLM配置不完整,baseUrl或apiKey为空");
return "LLM配置不完整,无法生成总结";
log.error("LLM config incomplete: baseUrl or apiKey is empty");
return "LLM config incomplete, unable to generate summary";
}
// 构建提示词,包含历史记忆
// Build the prompt including historical memory
String prompt = (promptTemplate != null ? promptTemplate : DEFAULT_SUMMARY_PROMPT)
.replace("{history_memory}", historyMemory != null ? historyMemory : "无历史记忆")
.replace("{history_memory}", historyMemory != null ? historyMemory : "No history memory")
.replace("{conversation}", conversation);
// 构建请求体
// Build request body
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("model", model != null ? model : "gpt-3.5-turbo");
@ -219,17 +219,17 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
requestBody.put("temperature", 0.2);
requestBody.put("max_tokens", 2000);
// 禁用思考模式
// Disable thinking mode
applyThinkingDisabled(baseUrl, requestBody);
// 发送HTTP请求
// Send HTTP request
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer " + apiKey);
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
// 构建完整的API URL
// Build the complete API URL
String apiUrl = baseUrl;
if (!apiUrl.endsWith("/chat/completions")) {
if (!apiUrl.endsWith("/")) {
@ -250,13 +250,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
return messageObj.getStr("content");
}
} else {
log.error("LLM API调用失败,状态码:{},响应:{}", response.getStatusCode(), response.getBody());
log.error("LLM API call failed, status code: {}, response: {}", response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
log.error("调用LLM服务生成总结时发生异常,modelId: {}", modelId, e);
log.error("Exception occurred while calling LLM service to generate summary, modelId: {}", modelId, e);
}
return "生成总结失败,请稍后重试";
return "Failed to generate summary, please try again later";
}
@Override
@ -274,7 +274,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
return baseUrl != null && !baseUrl.trim().isEmpty() &&
apiKey != null && !apiKey.trim().isEmpty();
} catch (Exception e) {
log.error("检查LLM服务可用性时发生异常:", e);
log.error("Exception occurred while checking LLM service availability:", e);
return false;
}
}
@ -286,10 +286,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
return isAvailable();
}
// 通过具体模型ID获取配置
// Get config by specific model ID
ModelConfigEntity modelConfig = modelConfigService.getModelByIdFromCache(modelId);
if (modelConfig == null || modelConfig.getConfigJson() == null) {
log.warn("未找到指定的LLM模型配置,modelId: {}", modelId);
log.warn("Specified LLM model config not found, modelId: {}", modelId);
return false;
}
@ -300,23 +300,23 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
return baseUrl != null && !baseUrl.trim().isEmpty() &&
apiKey != null && !apiKey.trim().isEmpty();
} catch (Exception e) {
log.error("检查LLM服务可用性时发生异常,modelId: {}", modelId, e);
log.error("Exception while checking LLM service availability, modelId: {}", modelId, e);
return false;
}
}
/**
* 从智控台获取默认的LLM模型配置
* Get default LLM model config from Console
*/
private ModelConfigEntity getDefaultLLMConfig() {
try {
// 获取所有启用的LLM模型配置
// Get all enabled LLM model configs
List<ModelConfigEntity> llmConfigs = modelConfigService.getEnabledModelsByType("LLM");
if (llmConfigs == null || llmConfigs.isEmpty()) {
return null;
}
// 优先返回默认配置,如果没有默认配置则返回第一个启用的配置
// Return default config first; if none exists, return the first enabled config
for (ModelConfigEntity config : llmConfigs) {
if (config.getIsDefault() != null && config.getIsDefault() == 1) {
return config;
@ -325,7 +325,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
return llmConfigs.get(0);
} catch (Exception e) {
log.error("获取LLM模型配置时发生异常:", e);
log.error("Exception occurred while retrieving LLM model config:", e);
return null;
}
}
@ -333,7 +333,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
@Override
public String generateTitle(String conversation, String modelId) {
if (!isAvailable()) {
log.warn("LLM服务不可用,无法生成标题");
log.warn("LLM service unavailable, unable to generate title");
return null;
}
@ -346,7 +346,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
}
if (llmConfig == null || llmConfig.getConfigJson() == null) {
log.error("未找到可用的LLM模型配置,modelId: {}", modelId);
log.error("No available LLM model config found, modelId: {}", modelId);
return null;
}
@ -356,7 +356,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String apiKey = configJson.getStr("api_key");
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
log.error("LLM配置不完整,baseUrl或apiKey为空");
log.error("LLM config incomplete: baseUrl or apiKey is empty");
return null;
}
@ -373,7 +373,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
requestBody.put("temperature", 0.3);
requestBody.put("max_tokens", 50);
// 禁用思考模式
// Disable thinking mode
applyThinkingDisabled(baseUrl, requestBody);
HttpHeaders headers = new HttpHeaders();
@ -409,10 +409,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
}
}
} else {
log.error("LLM API调用失败,状态码:{},响应:{}", response.getStatusCode(), response.getBody());
log.error("LLM API call failed, status code: {}, response: {}", response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
log.error("调用LLM服务生成标题时发生异常,modelId: {}", modelId, e);
log.error("Exception occurred while calling LLM service to generate title, modelId: {}", modelId, e);
}
return null;

View file

@ -385,7 +385,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
}
}
// 删除在新JSON中不存在的非敏感字段
// Delete non-sensitive fields that do not exist in the new JSON
for (String oldKey : originalJson.keySet().toArray(new String[0])) {
if (!modelConfigBodyDTO.getConfigJson().containsKey(oldKey)
&& !SensitiveDataUtils.isSensitiveField(oldKey)) {
@ -419,16 +419,16 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
original.set(key, new JSONObject());
}
// 获取 original 中的子对象
// Get sub-object from original
Object originalValue = original.get(key);
JSONObject originalChild;
// 检查 originalValue 是否是 JSONObject 类型
// Check if originalValue is of JSONObject type
if (originalValue instanceof JSONObject) {
originalChild = (JSONObject) originalValue;
} else {
// 如果不是 JSONObject 类型,记录警告并创建新的 JSON 对象
log.warn("mergeJson: key '{}' 的值不是 JSONObject 类型 (实际类型:{}),将创建新对象",
// If not a JSONObject type, log a warning and create a new JSON object
log.warn("mergeJson: value for key '{}' is not a JSONObject type (actual type: {}), creating new object",
key, originalValue != null ? originalValue.getClass().getSimpleName() : "null");
originalChild = new JSONObject();
original.set(key, originalChild);
@ -446,7 +446,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
}
}
// 删除在新 JSON 中不存在的非敏感子字段
// Delete non-sensitive subfields that do not exist in the new JSON
for (String oldChildKey : originalChild.keySet().toArray(new String[0])) {
if (!updated.containsKey(oldChildKey) && !SensitiveDataUtils.isSensitiveField(oldChildKey)) {
originalChild.remove(oldChildKey);
@ -523,7 +523,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
if (!agents.isEmpty()) {
String agentNames = agents.stream()
.map(AgentEntity::getAgentName)
.collect(Collectors.joining("、"));
.collect(Collectors.joining(","));
throw new RenException(ErrorCode.MODEL_REFERENCED_BY_AGENT, agentNames);
}
}

View file

@ -114,7 +114,7 @@ public class SysParamsController {
// Validate MQTT secret length
validateMqttSecretLength(dto.getParamCode(), dto.getParamValue());
// 如果是系统功能菜单配置,使用特殊处理
// If it is a system function menu config, apply special handling
if (Constant.SYSTEM_WEB_MENU.equals(dto.getParamCode())) {
sysParamsService.updateSystemWebMenu(dto.getParamValue());
} else {

View file

@ -55,17 +55,17 @@ public interface SysParamsService extends BaseService<SysParamsEntity> {
void initServerSecret();
/**
* 获取系统功能菜单配置
* Get system function menu configuration
*
* @param fromCache 是否从缓存获取
* @return 系统功能菜单配置JSON字符串
* @param fromCache Whether retrieved from cache
* @return System function menu config JSON string
*/
String getSystemWebMenu(boolean fromCache);
/**
* 更新系统功能菜单配置(自动处理功能相关的插件清理)
* Update system feature menu config (automatically handles cleanup of feature-related plugins)
*
* @param configJson 新的系统功能菜单配置JSON
* @param configJson New system feature menu config JSON
*/
void updateSystemWebMenu(String configJson);
}

View file

@ -30,7 +30,7 @@ import xiaozhi.modules.sys.redis.SysParamsRedis;
import xiaozhi.modules.sys.service.SysParamsService;
/**
* 参数管理
* Parameter management
*/
@AllArgsConstructor
@Service
@ -96,7 +96,7 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
}
/**
* 校验参数值类型
* Validate parameter value type
*/
private void validateParamValue(SysParamsDTO dto) {
if (dto == null) {
@ -133,12 +133,12 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
break;
case "json":
try {
// 首先检查是否以 { 开头,以 } 结尾
// First check if it starts with { and ends with }
String trimmedValue = paramValue.trim();
if (!trimmedValue.startsWith("{") || !trimmedValue.endsWith("}")) {
throw new RenException(ErrorCode.PARAM_JSON_INVALID);
}
// 然后尝试解析JSON
// Then attempt to parse JSON
JsonUtils.parseObject(paramValue, Object.class);
} catch (Exception e) {
throw new RenException(ErrorCode.PARAM_JSON_INVALID);
@ -152,14 +152,14 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(String[] ids) {
// 删除Redis数据
// Delete Redis data
List<String> paramCodeList = baseDao.getParamCodeList(ids);
String[] paramCodes = paramCodeList.toArray(new String[paramCodeList.size()]);
if (paramCodes.length > 0) {
sysParamsRedis.delete(paramCodes);
}
// 删除
// Delete
deleteBatchIds(Arrays.asList(ids));
}
@ -203,56 +203,56 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
@Override
public void initServerSecret() {
// 获取服务器密钥
// Get server key
String secretParam = getValue(Constant.SERVER_SECRET, false);
if (StringUtils.isBlank(secretParam) || "null".equals(secretParam)) {
String newSecret = UUID.randomUUID().toString();
updateValueByCode(Constant.SERVER_SECRET, newSecret);
}
// 初始化SM2密钥对
// Initialize SM2 key pair
initSM2KeyPair();
}
/**
* 初始化SM2密钥对
* Initialize SM2 key pair
*/
private void initSM2KeyPair() {
// 获取SM2公钥
// Get SM2 public key
String publicKey = getValue(Constant.SM2_PUBLIC_KEY, false);
// 获取SM2私钥
// Get SM2 private key
String privateKey = getValue(Constant.SM2_PRIVATE_KEY, false);
// 如果公钥或私钥为空,则生成新的密钥对
// If the public or private key is empty, generate a new key pair
if (StringUtils.isBlank(publicKey) || StringUtils.isBlank(privateKey) ||
"null".equals(publicKey) || "null".equals(privateKey)) {
Map<String, String> keyPair = SM2Utils.createKey();
String newPublicKey = keyPair.get(SM2Utils.KEY_PUBLIC_KEY);
String newPrivateKey = keyPair.get(SM2Utils.KEY_PRIVATE_KEY);
// 更新数据库中的密钥对
// Update key pair in database
updateValueByCode(Constant.SM2_PUBLIC_KEY, newPublicKey);
updateValueByCode(Constant.SM2_PRIVATE_KEY, newPrivateKey);
}
}
/**
* 检测短信参数是否符合要求
* Validate SMS parameters
*
* @param paramCode 参数编码
* @param paramValue 参数值
* @return 是否通过
* @param paramCode Parameter code
* @param paramValue Parameter value
* @return Whether passed
*/
private boolean detectingSMSParameters(String paramCode, String paramValue) {
// 判断是否是开启手机注册的参数编码,如果不是参数编码,着不需要检测其他短信参数,直接返回true
// Check if the parameter code enables mobile registration; if not, skip other SMS parameter checks and return true directly.
if (!Constant.SysMSMParam.SERVER_ENABLE_MOBILE_REGISTER.getValue().equals(paramCode)) {
return true;
}
// 判断是否为关闭,如果是关闭短信注册,着不需要检测其他短信参数,直接返回true
// Check if it is a close SMS registration; if so, skip other SMS parameter checks and return true directly.
if ("false".equalsIgnoreCase(paramValue)) {
return true;
}
// 检测短信关联参数是否为空
// Check if SMS association parameters are empty
ArrayList<String> list = new ArrayList<String>();
list.add(Constant.SysMSMParam.SERVER_SMS_MAX_SEND_COUNT.getValue());
list.add(Constant.SysMSMParam.TWILIO_SMS_ACCOUNT_SID.getValue());
@ -266,7 +266,7 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
}
});
if (!str.isEmpty()) {
String promptStr = "%s这些参数不可以为空";
String promptStr = "%sthese parameters cannot be empty";
String substring = str.substring(1, str.length());
throw new RenException(promptStr.formatted(substring));
}
@ -280,7 +280,7 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
@Override
@Transactional(rollbackFor = Exception.class)
public void updateSystemWebMenu(String configJson) {
// 获取当前配置
// Get current config
String currentConfig = getSystemWebMenu(false);
Map<String, Object> currentMap = null;
Map<String, Object> newMap = null;
@ -296,7 +296,7 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
throw new RenException(ErrorCode.PARAM_JSON_INVALID);
}
// 检查addressBook功能是否被关闭
// Check if addressBook feature is disabled
if (currentMap != null && newMap != null) {
Map<?, ?> currentFeatures = Map.class.cast(currentMap.get("features"));
Map<?, ?> newFeatures = Map.class.cast(newMap.get("features"));
@ -318,14 +318,14 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
newEnabled = enabled != null ? Boolean.class.cast(enabled) : false;
}
// 如果之前是启用状态,现在被禁用,删除所有call_device插件
// If previously enabled but now disabled, remove all call_device plugins
if (Boolean.TRUE.equals(currentEnabled) && !Boolean.TRUE.equals(newEnabled)) {
agentPluginMappingService.deleteByPluginId("SYSTEM_PLUGIN_CALL_DEVICE");
}
}
}
// 更新配置
// Update config
updateValueByCode(Constant.SYSTEM_WEB_MENU, configJson);
}
}

View file

@ -280,7 +280,7 @@ class AgentSnapshotServiceImplTest {
params.put("callbackUrl",
"https://function-user:function-pass@example.com/hook?access_token=function-token#function-fragment");
params.put("endpoint",
"https://example.com/signed?locale=zh-CN&X-Amz-Signature=endpoint-signature");
"https://example.com/signed?locale=en-US&X-Amz-Signature=endpoint-signature");
params.put("transport",
"https://example.com/transport?mode=push&key=transport-key");
params.put("mirrors", List.of(
@ -303,7 +303,7 @@ class AgentSnapshotServiceImplTest {
assertEquals("https://__SNAPSHOT_SECRET_REDACTED__@example.com/context"
+ "?token=__SNAPSHOT_SECRET_REDACTED__#__SNAPSHOT_SECRET_REDACTED__",
redacted.getContextProviders().get(0).getUrl());
assertEquals("https://example.com/signed?locale=zh-CN&X-Amz-Signature=__SNAPSHOT_SECRET_REDACTED__",
assertEquals("https://example.com/signed?locale=en-US&X-Amz-Signature=__SNAPSHOT_SECRET_REDACTED__",
redacted.getFunctions().get(0).getParamInfo().get("endpoint"));
assertEquals("https://example.com/transport?mode=push&key=__SNAPSHOT_SECRET_REDACTED__",
redacted.getFunctions().get(0).getParamInfo().get("transport"));
@ -1055,7 +1055,7 @@ class AgentSnapshotServiceImplTest {
current.setTtsLanguage(null);
AgentSnapshotDataDTO next = new AgentSnapshotDataDTO();
next.setTtsVoiceId("voice-id");
next.setTtsLanguage("普通话");
next.setTtsLanguage("Mandarin");
List<String> changedFields = (List<String>) method.invoke(service, current, next);
@ -1160,7 +1160,7 @@ class AgentSnapshotServiceImplTest {
template.setSummaryMemory(null);
when(templateService.getDefaultTemplate()).thenReturn(template);
when(timbreService.getDefaultLanguageById("TTS_EdgeTTS0001")).thenReturn("普通话");
when(timbreService.getDefaultLanguageById("TTS_EdgeTTS0001")).thenReturn("Mandarin");
when(agentDao.insert(any(AgentEntity.class))).thenReturn(1);
AgentCreateDTO dto = new AgentCreateDTO();
@ -1170,7 +1170,7 @@ class AgentSnapshotServiceImplTest {
InOrder inOrder = inOrder(agentDao, pluginMappingService, snapshotService);
inOrder.verify(agentDao).insert(argThat((AgentEntity agent) -> "test123".equals(agent.getAgentName())
&& "普通话".equals(agent.getTtsLanguage())
&& "Mandarin".equals(agent.getTtsLanguage())
&& "".equals(agent.getSummaryMemory())
&& Integer.valueOf(0).equals(agent.getChatHistoryConf())));
inOrder.verify(pluginMappingService).saveBatch(any(), eq(IRepository.DEFAULT_BATCH_SIZE));
@ -1235,7 +1235,7 @@ class AgentSnapshotServiceImplTest {
RenException error = assertThrows(RenException.class,
() -> service.restoreSnapshot(agentId, targetId, "stale-token"));
assertTrue(error.getMessage().contains("重新打开恢复预览"));
assertTrue(error.getMessage().contains("reopen recovery preview"));
verify(snapshotDao, never()).selectLatestSnapshot(agentId);
verify(snapshotDao, never()).insertWithNextVersion(any());
verify(agentDao, never()).updateSnapshotFields(any());
@ -1430,7 +1430,7 @@ class AgentSnapshotServiceImplTest {
AgentEntity lockedAgent = new AgentEntity();
lockedAgent.setId(agentId);
lockedAgent.setUserId(7L);
lockedAgent.setTtsLanguage("普通话");
lockedAgent.setTtsLanguage("Mandarin");
lockedAgent.setTtsVolume(0);
lockedAgent.setTtsRate(0);
lockedAgent.setTtsPitch(0);
@ -1440,7 +1440,7 @@ class AgentSnapshotServiceImplTest {
lockedAgent.setSystemPrompt("old prompt");
AgentInfoVO currentInfo = snapshotAgentInfo(agentId, 7L, "same-name", "same-summary");
currentInfo.setTtsLanguage("普通话");
currentInfo.setTtsLanguage("Mandarin");
currentInfo.setTtsVolume(0);
currentInfo.setTtsRate(0);
currentInfo.setTtsPitch(0);
@ -1451,7 +1451,7 @@ class AgentSnapshotServiceImplTest {
AgentInfoVO restoredInfo = snapshotAgentInfo(agentId, 7L, "same-name", "same-summary");
AgentSnapshotDataDTO currentData = snapshotData("same-name", "same-summary");
currentData.setTtsLanguage("普通话");
currentData.setTtsLanguage("Mandarin");
currentData.setTtsVolume(0);
currentData.setTtsRate(0);
currentData.setTtsPitch(0);
@ -1834,7 +1834,7 @@ class AgentSnapshotServiceImplTest {
() -> method.invoke(service, snapshotTag, new Date()));
assertTrue(error.getCause() instanceof RenException);
assertEquals("快照引用的标签已被删除,无法恢复,请先重新创建或选择标签", error.getCause().getMessage());
assertEquals("The tag referenced by the snapshot has been deleted and cannot be restored. Please recreate or select a tag first.", error.getCause().getMessage());
verify(tagDao, never()).updateById(any(AgentTagEntity.class));
verify(tagDao, never()).insert(any(AgentTagEntity.class));
}

View file

@ -22,14 +22,14 @@ import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.modules.security.user.SecurityUser;
import xiaozhi.modules.sys.service.SysParamsService;
@DisplayName("设备更新接口回归测试")
@DisplayName("Device update API regression test")
class DeviceControllerTest {
private static final String DEVICE_ID = "device-id";
private static final long USER_ID = 1L;
@Test
@DisplayName("数据库未更新时不误报自动升级状态修改成功")
@DisplayName("Do not falsely report auto-upgrade status change success when the database is not updated")
void updateFailureIsReturnedToCaller() {
DeviceService deviceService = mock(DeviceService.class);
DeviceEntity entity = ownedDevice();

View file

@ -19,7 +19,7 @@ import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.service.OtaService;
import xiaozhi.modules.sys.service.SysParamsService;
@DisplayName("设备自动升级回归测试")
@DisplayName("Device auto-upgrade regression test")
class DeviceAutoUpdateTest {
private static final String MAC_ADDRESS = "00:11:22:33:44:55";
@ -27,7 +27,7 @@ class DeviceAutoUpdateTest {
private static final String CURRENT_VERSION = "1.0.0";
@Test
@DisplayName("#3299 自动升级关闭时 OTA 响应不包含固件")
@DisplayName("#3299 OTA response excludes firmware when auto-upgrade is disabled")
void disabledAutoUpdateOmitsFirmware() {
OtaService otaService = mock(OtaService.class);
DeviceServiceImpl service = proxiedService(deviceWithAutoUpdate(0), otaService);
@ -40,7 +40,7 @@ class DeviceAutoUpdateTest {
}
@Test
@DisplayName("自动升级开启时继续执行固件查询")
@DisplayName("Continue firmware query when auto-upgrade is enabled.")
void enabledAutoUpdateChecksFirmware() {
OtaService otaService = mock(OtaService.class);
when(otaService.getLatestOta(BOARD_TYPE)).thenReturn(null);

View file

@ -21,12 +21,12 @@ import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.vo.UserShowDeviceListVO;
import xiaozhi.modules.security.config.WebMvcConfig;
@DisplayName("设备时间序列化回归测试")
@DisplayName("Device time serialization regression test")
class DeviceTimeSerializationTest {
@ParameterizedTest(name = "浏览器时区 {0}")
@ParameterizedTest(name = "Browser timezone {0}")
@ValueSource(strings = { "Asia/Shanghai", "America/Sao_Paulo" })
@DisplayName("#3280 绑定时间和最后连接时间在任意浏览器时区都表示同一时刻")
@DisplayName("#3280 Bind time and last connection time represent the same moment in any browser timezone")
void serializedDeviceTimesDescribeTheSameInstantAcrossBrowserTimeZones(String browserTimeZone) {
Instant connectedAt = Instant.parse("2026-07-10T13:21:42Z");
DeviceEntity entity = new DeviceEntity();
@ -46,22 +46,22 @@ class DeviceTimeSerializationTest {
assertAll(
() -> assertTrue(payload.path("createDateTimestamp").isTextual(),
"Long 时间戳必须遵循现有 JSON 契约序列化为字符串"),
"Long timestamps must be serialized as strings per existing JSON contract"),
() -> assertTrue(payload.path("lastConnectedAtTimestamp").isTextual(),
"Long 时间戳必须遵循现有 JSON 契约序列化为字符串"),
"Long timestamps must be serialized as strings per existing JSON contract"),
() -> assertEquals(connectedAt, createDate,
"createDateTimestamp 必须保留源时间点"),
"createDateTimestamp must preserve source timestamp"),
() -> assertEquals(connectedAt, lastConnectedAt,
"lastConnectedAtTimestamp 必须保留源时间点"),
"lastConnectedAtTimestamp must preserve the original timestamp"),
() -> assertEquals(lastConnectedAt.atZone(browserZone).toLocalDateTime(),
createDate.atZone(browserZone).toLocalDateTime(),
"绑定时间和最后连接时间在同一浏览器中必须显示为相同的本地时间"),
"Bound time and last connection time must display as the same local time in the same browser"),
() -> assertTrue(payload.path("createDate").isTextual(),
"兼容字段 createDate 必须继续保留"));
"Retain the legacy field createDate for compatibility"));
}
@Test
@DisplayName("时间为空时新旧字段均保持 null")
@DisplayName("When time is empty, both old and new fields remain null")
void nullDeviceTimesRemainNull() {
DeviceEntity entity = new DeviceEntity();
DeviceServiceImpl deviceService = serviceReturning(entity);
@ -76,9 +76,9 @@ class DeviceTimeSerializationTest {
() -> assertTrue(payload.path("createDate").isNull()));
}
@ParameterizedTest(name = "自动升级状态 {0}")
@ParameterizedTest(name = "Auto-upgrade status {0}")
@ValueSource(ints = { 0, 1 })
@DisplayName("#3299 设备列表按 autoUpdate 契约返回真实开关状态")
@DisplayName("#3299 Device list returns actual toggle states per autoUpdate contract")
void serializedDeviceContainsAutoUpdateState(int autoUpdate) {
DeviceEntity entity = new DeviceEntity();
entity.setAutoUpdate(autoUpdate);
@ -92,7 +92,7 @@ class DeviceTimeSerializationTest {
() -> assertEquals(autoUpdate, device.getAutoUpdate()),
() -> assertEquals(autoUpdate, payload.path("autoUpdate").asInt()),
() -> assertTrue(payload.path("otaUpgrade").isMissingNode(),
"设备列表不应继续暴露未映射的旧字段 otaUpgrade"));
"Device list should not continue exposing unmapped legacy field otaUpgrade"));
}
private DeviceServiceImpl serviceReturning(DeviceEntity entity) {

View file

@ -30,7 +30,7 @@ import com.sun.net.httpserver.HttpServer;
import cn.hutool.crypto.digest.DigestUtil;
@DisplayName("MQTT Gateway 日期鉴权回归测试")
@DisplayName("MQTT Gateway date authentication regression test")
class MqttGatewayAuthorizationTest {
private static final String SIGNATURE_KEY = "test-signature-key";
@ -46,7 +46,7 @@ class MqttGatewayAuthorizationTest {
}
@Test
@DisplayName("以 UTC 日期生成当天、前一天和后一天三个候选 token")
@DisplayName("Generate three candidate tokens for today, yesterday, and tomorrow based on UTC date")
void generatesUtcDateCandidates() {
List<String> tokens = MqttGatewayAuthorization.generateDailyTokens(SIGNATURE_KEY, FIXED_INSTANT);
@ -56,9 +56,9 @@ class MqttGatewayAuthorizationTest {
tokenFor("2026-07-15")), tokens);
}
@ParameterizedTest(name = "Gateway 时区 {0}")
@ParameterizedTest(name = "Gateway timezone {0}")
@MethodSource("gatewayTimeZones")
@DisplayName("候选 token 覆盖上海和圣保罗 Gateway 的本地日期")
@DisplayName("Candidate tokens cover local dates for Shanghai and São Paulo Gateways")
void coversGatewayLocalDate(String gatewayTimeZone, Instant now, int expectedTokenIndex) {
String gatewayDate = now.atZone(ZoneId.of(gatewayTimeZone)).toLocalDate().toString();
List<String> tokens = MqttGatewayAuthorization.generateDailyTokens(SIGNATURE_KEY, now);
@ -67,7 +67,7 @@ class MqttGatewayAuthorizationTest {
}
@Test
@DisplayName("仅在 401 时按日期候选重试并保留请求体")
@DisplayName("Retry with date candidates and preserve request body only on 401")
void retriesOnlyAuthenticationFailures() throws IOException {
AtomicInteger requestCount = new AtomicInteger();
List<String> authorizationHeaders = new ArrayList<>();
@ -98,7 +98,7 @@ class MqttGatewayAuthorizationTest {
@ParameterizedTest(name = "HTTP {0}")
@ValueSource(ints = { 403, 500 })
@DisplayName("非 401 错误不重试且向上抛出")
@DisplayName("Do not retry non-401 errors and propagate them")
void doesNotRetryNonAuthenticationFailure(int statusCode) throws IOException {
AtomicInteger requestCount = new AtomicInteger();
startServer(exchange -> {
@ -117,7 +117,7 @@ class MqttGatewayAuthorizationTest {
}
@Test
@DisplayName("所有日期候选被拒绝时不把错误响应当作设备离线数据")
@DisplayName("Do not treat error responses as device offline data when all date candidates are rejected")
void propagatesAuthenticationFailureAfterAllCandidatesAreRejected() throws IOException {
AtomicInteger requestCount = new AtomicInteger();
startServer(exchange -> {
@ -135,10 +135,10 @@ class MqttGatewayAuthorizationTest {
assertEquals(3, requestCount.get());
}
@ParameterizedTest(name = "密钥值 [{0}]")
@ParameterizedTest(name = "Key value [{0}]")
@NullAndEmptySource
@ValueSource(strings = { " ", "null", " NULL " })
@DisplayName("缺少或占位签名密钥时在发起 HTTP 请求前失败")
@DisplayName("Fail before HTTP request if signature key is missing or placeholder")
void rejectsMissingSignatureKeyBeforeSendingRequest(String signatureKey) {
MqttGatewayAuthorization.GatewayRequestException exception = assertThrows(
MqttGatewayAuthorization.GatewayRequestException.class,

View file

@ -27,10 +27,10 @@ class TimbreServiceImplTest {
VoiceCloneDao voiceCloneDao = mock(VoiceCloneDao.class);
TimbreServiceImpl service = new TimbreServiceImpl(timbreDao, voiceCloneDao, mock(RedisUtils.class));
TimbreEntity timbre = new TimbreEntity();
timbre.setLanguages(",, ; 普通话;粤语");
timbre.setLanguages(",, ; Mandarin; Cantonese");
when(timbreDao.selectById("voice-id")).thenReturn(timbre);
assertEquals("普通话", service.getDefaultLanguageById("voice-id"));
assertEquals("Mandarin", service.getDefaultLanguageById("voice-id"));
verify(voiceCloneDao, never()).selectById("voice-id");
}
@ -41,7 +41,7 @@ class TimbreServiceImplTest {
VoiceCloneDao voiceCloneDao = mock(VoiceCloneDao.class);
TimbreServiceImpl service = new TimbreServiceImpl(timbreDao, voiceCloneDao, mock(RedisUtils.class));
VoiceCloneEntity voiceClone = new VoiceCloneEntity();
voiceClone.setLanguages("、, English,中文");
voiceClone.setLanguages(",, English, Chinese");
when(voiceCloneDao.selectById("clone-id")).thenReturn(voiceClone);
assertEquals("English", service.getDefaultLanguageById("clone-id"));
@ -53,7 +53,7 @@ class TimbreServiceImplTest {
VoiceCloneDao voiceCloneDao = mock(VoiceCloneDao.class);
TimbreServiceImpl service = new TimbreServiceImpl(timbreDao, voiceCloneDao, mock(RedisUtils.class));
TimbreEntity timbre = new TimbreEntity();
timbre.setLanguages(",,、;;;,,");
timbre.setLanguages(",,,;;;,,");
when(timbreDao.selectById("voice-id")).thenReturn(timbre);
assertNull(service.getDefaultLanguageById("voice-id"));
@ -100,7 +100,7 @@ class TimbreServiceImplTest {
service.save(validTimbreData());
verify(timbreDao).insert(argThat((TimbreEntity entity) ->
"测试音色".equals(entity.getName()) && entity.getSort() == 0L));
"Test voice".equals(entity.getName()) && entity.getSort() == 0L));
}
@Test
@ -122,8 +122,8 @@ class TimbreServiceImplTest {
private TimbreDataDTO validTimbreData() {
TimbreDataDTO dto = new TimbreDataDTO();
dto.setLanguages("中文");
dto.setName("测试音色");
dto.setLanguages("Chinese");
dto.setName("Test voice");
dto.setTtsModelId("TTS_Test");
dto.setTtsVoice("test-voice");
return dto;

View file

@ -1,13 +1,13 @@
root = true
[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
end_of_line = lf # 控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字符
insert_final_newline = true # 始终在文件末尾插入一个新行
[*] # Indicates all files apply
charset = utf-8 # Set file character encoding to utf-8
indent_style = space # Indentation style (tab | space)
indent_size = 2 # Indent size
end_of_line = lf # Control newline type (lf | cr | crlf)
trim_trailing_whitespace = true # Strip leading whitespace
insert_final_newline = true # Always insert a new line at the end of the file
[*.md] # 表示仅 md 文件适用以下规则
max_line_length = off # 关闭最大行长度限制
trim_trailing_whitespace = false # 关闭末尾空格修剪
[*.md] # Indicates the following rules apply only to md files
max_line_length = off # Disable max line length limit
trim_trailing_whitespace = false # Disable trailing whitespace trimming

View file

@ -29,16 +29,16 @@ docs/.vitepress/cache
src/types
# lock 文件还是不要了,我主要的版本写死就好了
# Remove lock file; hardcode the main version instead
# pnpm-lock.yaml
# package-lock.json
# TIPS:如果某些文件已经加入了版本管理,现在重新加入 .gitignore 是不生效的,需要执行下面的操作
# `git rm -r --cached .` 然后提交 commit 即可。
# TIPS: If files are already tracked by version control, adding them to .gitignore now has no effect; perform the following steps instead
# `git rm -r --cached .` then commit the changes.
# git rm -r --cached file1 file2 ## 针对某些文件
# git rm -r --cached dir1 dir2 ## 针对某些文件夹
# git rm -r --cached . ## 针对所有文件
# git rm -r --cached file1 file2 ## For specific files
# git rm -r --cached dir1 dir2 ## For specific folders
# git rm -r --cached . ## For all files
# 更新 uni-app 官方版本
# Update to the official uni-app version.
# npx @dcloudio/uvm@latest

View file

@ -12,7 +12,7 @@ import type {
} from './types'
import { http } from '@/http/request/alova'
// 获取智能体详情
// Get agent details
export function getAgentDetail(id: string) {
return http.Get<AgentDetail>(`/agent/${id}`, {
meta: {
@ -25,7 +25,7 @@ export function getAgentDetail(id: string) {
})
}
// 获取角色模板列表
// Get role template list
export function getRoleTemplates() {
return http.Get<RoleTemplate[]>('/agent/template', {
meta: {
@ -38,7 +38,7 @@ export function getRoleTemplates() {
})
}
// 获取模型选项
// Get model options
export function getModelOptions(modelType: string, modelName: string = '') {
return http.Get<ModelOption[]>('/models/names', {
params: {
@ -55,7 +55,7 @@ export function getModelOptions(modelType: string, modelName: string = '') {
})
}
// 获取智能体列表
// Get Agent list
export function getAgentList() {
return http.Get<Agent[]>('/agent/list', {
meta: {
@ -68,7 +68,7 @@ export function getAgentList() {
})
}
// 创建智能体
// Create Agent
export function createAgent(data: AgentCreateData) {
return http.Post<string>('/agent', data, {
meta: {
@ -78,7 +78,7 @@ export function createAgent(data: AgentCreateData) {
})
}
// 删除智能体
// Delete Agent
export function deleteAgent(id: string) {
return http.Delete(`/agent/${id}`, {
meta: {
@ -88,7 +88,7 @@ export function deleteAgent(id: string) {
})
}
// 获取TTS音色列表
// Get TTS voice list
export function getTTSVoices(ttsModelId: string, voiceName: string = '') {
return http.Get<TtsVoice[]>(`/models/${ttsModelId}/voices`, {
params: {
@ -104,7 +104,7 @@ export function getTTSVoices(ttsModelId: string, voiceName: string = '') {
})
}
// 更新智能体
// Update agent
export function updateAgent(id: string, data: Partial<AgentDetail> & { tagNames?: string[] }) {
return http.Put(`/agent/${id}`, data, {
meta: {
@ -117,7 +117,7 @@ export function updateAgent(id: string, data: Partial<AgentDetail> & { tagNames?
})
}
// 获取插件列表
// Get plugin list
export function getPluginFunctions() {
return http.Get<any[]>(`/models/provider/plugin/names`, {
meta: {
@ -130,7 +130,7 @@ export function getPluginFunctions() {
})
}
// 获取mcp接入点
// Get MCP endpoint
export function getMcpAddress(agentId: string) {
return http.Get<string>(`/agent/mcp/address/${agentId}`, {
meta: {
@ -141,7 +141,7 @@ export function getMcpAddress(agentId: string) {
})
}
// 获取mcp工具
// Get MCP tools
export function getMcpTools(agentId: string) {
return http.Get<string[]>(`/agent/mcp/tools/${agentId}`, {
meta: {
@ -154,7 +154,7 @@ export function getMcpTools(agentId: string) {
})
}
// 获取声纹列表
// Get voiceprint list
export function getVoicePrintList(agentId: string) {
return http.Get<any[]>(`/agent/voice-print/list/${agentId}`, {
meta: {
@ -167,7 +167,7 @@ export function getVoicePrintList(agentId: string) {
})
}
// 获取语音对话记录
// Get voice conversation records
export function getChatHistoryUser(agentId: string) {
return http.Get<any[]>(`/agent/${agentId}/chat-history/user`, {
meta: {
@ -180,7 +180,7 @@ export function getChatHistoryUser(agentId: string) {
})
}
// 新增声纹说话人
// Add voiceprint speaker
export function createVoicePrint(data: { agentId: string, audioId: string, sourceName: string, introduce: string }) {
return http.Post('/agent/voice-print', data, {
meta: {
@ -190,7 +190,7 @@ export function createVoicePrint(data: { agentId: string, audioId: string, sourc
})
}
// 获取智能体标签
// Get agent tags
export function getAgentTags(agentId: string) {
return http.Get<any[]>(`/agent/${agentId}/tags`, {
meta: {
@ -203,7 +203,7 @@ export function getAgentTags(agentId: string) {
})
}
// 更新智能体标签
// Update agent tag
export function updateAgentTags(agentId: string, data) {
return http.Put(`/agent/${agentId}/tags`, data, {
meta: {
@ -213,7 +213,7 @@ export function updateAgentTags(agentId: string, data) {
})
}
// 获取所有语言
// Get all languages
export function getAllLanguage(modelId: string) {
return http.Get<TtsVoice[]>(`/models/${modelId}/voices`, {
meta: {
@ -227,8 +227,8 @@ export function getAllLanguage(modelId: string) {
}
/**
* 获取克隆音色的临时播放ID
* @param cloneId 克隆音色记录ID
* Get temporary playback ID for cloned voice
* @param cloneId Cloned voice record ID
*/
export function getVoiceCloneAudioId(cloneId: string) {
return http.Post<string>(`/voiceClone/audio/${cloneId}`, {}, {
@ -239,7 +239,7 @@ export function getVoiceCloneAudioId(cloneId: string) {
})
}
// 获取智能体历史版本列表
// Get agent history version list
export function getAgentSnapshots(agentId: string, params: AgentSnapshotPageParams) {
return http.Get<PageData<AgentSnapshot>>(`/agent/${agentId}/snapshots`, {
params,
@ -253,7 +253,7 @@ export function getAgentSnapshots(agentId: string, params: AgentSnapshotPagePara
})
}
// 获取智能体历史版本详情
// Get agent history version details
export function getAgentSnapshot(agentId: string, snapshotId: string) {
return http.Get<AgentSnapshot>(`/agent/${agentId}/snapshots/${snapshotId}`, {
meta: {
@ -266,7 +266,7 @@ export function getAgentSnapshot(agentId: string, snapshotId: string) {
})
}
// 恢复智能体历史版本
// Restore agent historical version
export function restoreAgentSnapshot(agentId: string, snapshotId: string, currentStateToken: string) {
return http.Post(`/agent/${agentId}/snapshots/${snapshotId}/restore`, { currentStateToken }, {
meta: {
@ -276,7 +276,7 @@ export function restoreAgentSnapshot(agentId: string, snapshotId: string, curren
})
}
// 删除智能体历史版本
// Delete agent history version
export function deleteAgentSnapshot(agentId: string, snapshotId: string) {
return http.Delete(`/agent/${agentId}/snapshots/${snapshotId}`, {
meta: {
@ -286,7 +286,7 @@ export function deleteAgentSnapshot(agentId: string, snapshotId: string) {
})
}
// 获取所有替换词文件
// Get all replacement word files
export function getCorrectWordFiles() {
return http.Get<CorrectWordFile[]>('/correct-word/file/select', {
meta: {

View file

@ -1,4 +1,4 @@
// 智能体列表数据类型
// Agent list data type
export interface Agent {
id: string
agentName: string
@ -14,12 +14,12 @@ export interface Agent {
tags: Record<string, string>[]
}
// 智能体创建数据类型
// Agent creation data type
export interface AgentCreateData {
agentName: string
}
// 智能体详情数据类型
// Agent details data type
export interface AgentDetail {
id: string
userId: string
@ -122,7 +122,7 @@ export interface TtsVoice {
isClone?: boolean | null
}
// 角色模板数据类型
// Role template data type
export interface RoleTemplate {
id: string
agentCode: string
@ -148,7 +148,7 @@ export interface RoleTemplate {
updatedAt: string
}
// 模型选项数据类型
// Model option data type
export interface ModelOption {
id: string
modelName: string
@ -168,7 +168,7 @@ export interface PluginDefinition {
modelType: string
providerCode: string
name: string
fields: PluginField[] // 注意:原始是字符串,需要先 JSON.parse
fields: PluginField[] // Note: Original is a string; JSON.parse is required first
sort: number
updater: string
updateDate: string

View file

@ -97,7 +97,7 @@
"type": "page",
"layout": "default",
"style": {
"navigationBarTitleText": "编辑源",
"navigationBarTitleText": "Edit source",
"navigationStyle": "custom"
}
},
@ -106,7 +106,7 @@
"type": "page",
"layout": "default",
"style": {
"navigationBarTitleText": "语音设置",
"navigationBarTitleText": "Voice Settings",
"navigationStyle": "custom"
}
},
@ -194,7 +194,7 @@
"type": "page",
"layout": "default",
"style": {
"navigationBarTitleText": "设置",
"navigationBarTitleText": "Settings",
"navigationStyle": "custom"
}
},

View file

@ -19,7 +19,7 @@ test('rejects empty TTS metadata while keeping language-less voices selectable w
assert.equal(hasUsableTtsVoiceMetadata([]), false)
assert.equal(hasUsableTtsVoiceMetadata(voices), true)
assert.deepEqual(filterTtsVoicesByLanguage(voices, ''), voices)
assert.deepEqual(filterTtsVoicesByLanguage(voices, 'zh-CN'), [])
assert.deepEqual(filterTtsVoicesByLanguage(voices, 'en-US'), [])
})
test('keeps inherited TTS values distinct from explicit zero', () => {

View file

@ -18,14 +18,14 @@ const props = withDefaults(defineProps<Props>(), {
agentId: '',
})
// 组件参数
// Component parameters
interface Props {
agentId?: string
}
const agentId = computed(() => props.agentId)
// 表单数据
// Form data
const formData = ref<Partial<AgentDetail>>({
agentName: '',
systemPrompt: '',
@ -45,9 +45,9 @@ const formData = ref<Partial<AgentDetail>>({
ttsPitch: 0,
})
// 显示名称数据
// Display name data
const displayNames = ref({
// 显示名称数据
// Display name data
vad: t('agent.pleaseSelect'),
asr: t('agent.pleaseSelect'),
llm: t('agent.pleaseSelect'),
@ -61,11 +61,11 @@ const displayNames = ref({
language: t('agent.pleaseSelect'),
})
// 角色模板数据
// Role template data
const roleTemplates = ref<RoleTemplate[]>([])
const selectedTemplateId = ref('')
// 加载状态
// Loading status
const loading = ref(false)
const saving = ref(false)
const showSnapshotPanel = ref(false)
@ -73,7 +73,7 @@ const currentVersionNo = ref<number | null>(null)
const snapshotReloadBlocked = ref(false)
const snapshotReloadFailed = ref(false)
// 模型选项数据
// Model option data
const modelOptions = ref<{
[key: string]: ModelOption[]
}>({
@ -96,18 +96,18 @@ interface VoiceOption {
train_status?: number
}
// 音色选项数据
// Voice option data
const voiceOptions = ref<VoiceOption[]>([])
// 保存完整的音色信息
// Save complete voice info
const voiceDetails = ref<Record<string, TtsVoice>>({})
// 上报模式选项数据
// Report mode option data
const reportOptions = [
{ name: t('agent.reportText'), value: 1 },
{ name: t('agent.reportTextVoice'), value: 2 },
]
// 选择器显示状态
// Selector display state
const pickerShow = ref<{
[key: string]: boolean
}>({
@ -148,12 +148,12 @@ interface SnapshotRestoreContext {
actionSequence: number
}
// 音频播放相关
// Audio playback related
const audioRef = ref<UniApp.InnerAudioContext | null>(null)
const playingVoiceId = ref<string>('')
const voicePreviewRequestGate = createVoicePreviewRequestGate()
// 使用插件store
// Use plugin store
const pluginStore = usePluginStore()
const speedPitchStore = useSpeedPitch()
const providerStore = useProvider()
@ -286,7 +286,7 @@ function handleInputConfirm() {
inputVisible.value = false
}
// 是否禁用历史记忆输入框
// Is history memory input disabled
const isMemoryDisabled = computed(() => formData.value.memModelId !== 'Memory_mem_local_short')
function normalizeFunctionParams(paramInfo: any) {
@ -311,7 +311,7 @@ function normalizeAgentFunctions(functions: any[] = []) {
}))
}
// 打开上下文源编辑弹窗
// Open context source edit dialog
function openContextProviderDialog() {
uni.navigateTo({
url: '/pages/agent/provider',
@ -324,7 +324,7 @@ function handleRegulate() {
})
}
// 加载智能体详情
// Load agent details
async function loadAgentDetail(targetAgentId = agentId.value) {
if (!targetAgentId)
return false
@ -343,7 +343,7 @@ async function loadAgentDetail(targetAgentId = agentId.value) {
}
catch (error) {
if (isActiveAgentDetailRequest(targetAgentId, requestId)) {
console.error('加载智能体详情失败:', error)
console.error('Failed to load Agent details:', error)
toast.error(t('agent.loadFail'))
}
return false
@ -416,28 +416,28 @@ function invalidateTtsMetadataRequest() {
ttsOptionsModelId.value = ''
}
// 获取音色显示名称
// Get voice display name
function getVoiceDisplayName(ttsVoiceId: string) {
if (!ttsVoiceId)
return t('agent.pleaseSelect')
console.log('=== 音色映射调试 ===')
console.log('当前音色ID:', ttsVoiceId)
console.log('当前TTS模型:', formData.value.ttsModelId)
console.log('可用音色选项:', voiceOptions.value)
console.log('=== Voice mapping debug ===')
console.log('Current voice ID:', ttsVoiceId)
console.log('Current TTS model:', formData.value.ttsModelId)
console.log('Available voice options:', voiceOptions.value)
// 首先尝试直接从音色选项中匹配ID
// First try to match ID directly from voice options
const voice = voiceOptions.value.find(v => v.id === ttsVoiceId)
if (voice) {
console.log('直接匹配成功:', voice)
console.log('Direct match succeeded:', voice)
return voice.name
}
// 如果没找到,尝试兼容性映射
// If not found, try compatibility mapping
if (voiceOptions.value.length > 0) {
console.log('直接匹配失败,尝试兼容性映射')
console.log('Direct match failed, trying compatibility mapping')
// 创建索引映射:voice1 → 第1个音色,voice2 → 第2个音色
// Create index mapping: voice1 -> 1st voice, voice2 -> 2nd voice
const indexMap = {
voice1: 0,
voice2: 1,
@ -449,16 +449,16 @@ function getVoiceDisplayName(ttsVoiceId: string) {
const index = indexMap[ttsVoiceId]
if (index !== undefined && voiceOptions.value[index]) {
const mappedVoice = voiceOptions.value[index]
console.log(`索引映射: ${ttsVoiceId} → index ${index} → ${mappedVoice.name}`)
console.log(`Index mapping: ${ttsVoiceId} → index ${index} → ${mappedVoice.name}`)
return mappedVoice.name
}
}
console.log('所有映射方式都失败,返回原始ID:', ttsVoiceId)
console.log('All mapping methods failed, returning original ID:', ttsVoiceId)
return ttsVoiceId
}
// 更新显示名称
// Update display name
function updateDisplayNames() {
if (!formData.value)
return
@ -472,46 +472,46 @@ function updateDisplayNames() {
displayNames.value.memory = getModelDisplayName('Memory', formData.value.memModelId)
displayNames.value.tts = getModelDisplayName('TTS', formData.value.ttsModelId)
// 角色音色特殊处理
// Special handling for role voice
displayNames.value.report = reportOptions.find(item => item.value === formData.value.chatHistoryConf)?.name
isVisibleReport.value = formData.value.memModelId !== 'Memory_nomem'
console.log('最终音色显示名称:', displayNames.value.voiceprint)
console.log('Final voice display name:', displayNames.value.voiceprint)
}
// 加载角色模板
// Load role templates
async function loadRoleTemplates() {
try {
const templates = await getRoleTemplates()
roleTemplates.value = templates
}
catch (error) {
console.error('加载角色模板失败:', error)
console.error('Failed to load role templates:', error)
}
}
// 加载模型选项
// Load model options
async function loadModelOptions() {
const modelTypes = ['VAD', 'ASR', 'LLM', 'VLLM', 'Intent', 'Memory', 'TTS']
try {
await Promise.all(
modelTypes?.map(async (type) => {
console.log(`加载模型类型: ${type}`)
console.log(`Loading model type: ${type}`)
const options = await getModelOptions(type)
modelOptions.value[type] = options
console.log(`${type} 选项:`, options)
console.log(`${type} options:`, options)
}) || [],
)
console.log('所有模型选项加载完成:', modelOptions.value)
console.log('All model options loaded:', modelOptions.value)
}
catch (error) {
console.error('加载模型选项失败:', error)
console.error('Failed to load model options:', error)
}
}
// 根据语言筛选音色
// Filter voices by language
interface VoiceSelectionOptions {
autoSelectVoice?: boolean
preferredLanguage?: string | null
@ -580,7 +580,7 @@ function filterVoicesByLanguage(options: VoiceSelectionOptions = {}) {
const allVoices = Object.values(voiceDetails.value)
// 根据选中的语言筛选音色
// Filter voices by selected language
const filteredVoices = filterTtsVoicesByLanguage(allVoices, selectedTtsLanguage.value)
voiceOptions.value = filteredVoices.map(voice => ({
@ -592,7 +592,7 @@ function filterVoicesByLanguage(options: VoiceSelectionOptions = {}) {
train_status: voice.trainStatus,
}))
// 检查当前选中的音色是否支持当前语言,如果不支持则选择第一个
// Check if the currently selected voice supports the current language; if not, select the first one
const currentVoiceSupportsLanguage = formData.value.ttsVoiceId
&& filteredVoices.some(voice => voice.id === formData.value.ttsVoiceId)
@ -618,7 +618,7 @@ function getVoiceDefaultLanguage(ttsVoiceId: string) {
return languages[0] || ''
}
// 根据语音合成模型加载语言
// Load language based on text-to-speech model
async function fetchAllLanguag(ttsModelId: string, options: VoiceSelectionOptions = {}): Promise<'loaded' | 'failed' | 'stale'> {
const requestId = ++ttsOptionsRequestSequence
ttsOptionsLoading.value = true
@ -636,12 +636,12 @@ async function fetchAllLanguag(ttsModelId: string, options: VoiceSelectionOption
if (!hasUsableTtsVoiceMetadata(res)) {
throw new Error('No TTS voice metadata is available')
}
// 保存完整的音色信息
// Save complete voice info
voiceDetails.value = res.reduce<Record<string, TtsVoice>>((acc, voice) => {
acc[voice.id] = voice
return acc
}, {})
// 提取所有语言选项并去重
// Extract and deduplicate all language options
const allLanguages = new Set()
res.forEach((voice) => {
if (voice.languages) {
@ -662,7 +662,7 @@ async function fetchAllLanguag(ttsModelId: string, options: VoiceSelectionOption
// exposes no language dimension.
selectedTtsLanguage.value = ''
displayNames.value.language = ''
// 优先使用调用方指定的语言或音色默认语言,再回退到智能体当前配置
// Prefer the language specified by the caller or the voice's default language, then fall back to the Agent's current config
if (requestedLanguage && languageOptions.value.some(option => option.value === requestedLanguage)) {
selectedTtsLanguage.value = requestedLanguage
displayNames.value.language = requestedLanguage
@ -684,7 +684,7 @@ async function fetchAllLanguag(ttsModelId: string, options: VoiceSelectionOption
displayNames.value.language = languageOptions.value[0].value
}
// 根据选中的语言筛选音色
// Filter voices by selected language
filterVoicesByLanguage(options)
ttsOptionsModelId.value = ttsModelId
return 'loaded'
@ -703,24 +703,24 @@ async function fetchAllLanguag(ttsModelId: string, options: VoiceSelectionOption
}
}
// 加载TTS音色选项
// Load TTS voice options
// async function loadVoiceOptions(ttsModelId?: string) {
// if (!ttsModelId)
// return
// try {
// console.log(`加载音色选项: ${ttsModelId}`)
// console.log(`Loading voice options: ${ttsModelId}`)
// const voices = await getTTSVoices(ttsModelId)
// voiceOptions.value = voices
// console.log('音色选项:', voices)
// console.log('Voice options:', voices)
// }
// catch (error) {
// console.error('加载音色选项失败:', error)
// console.error('Failed to load voice options:', error)
// voiceOptions.value = []
// }
// }
// 选择角色模板
// Select role template
async function selectRoleTemplate(templateId: string) {
if (ttsOptionsLoading.value) {
return
@ -777,7 +777,7 @@ async function selectRoleTemplate(templateId: string) {
}
}
// 打开选择器
// Open selector
function openPicker(type: string) {
if (ttsOptionsLoading.value && (type === 'tts' || type === 'language' || type === 'voiceprint')) {
return
@ -785,12 +785,12 @@ function openPicker(type: string) {
pickerShow.value[type] = true
}
// 选择器确认
// Selector confirmed
async function onPickerConfirm(type: string, value: any, name: string) {
console.log('选择器确认:', type, value, name)
console.log('Selector confirmed:', type, value, name)
const previousTtsState = type === 'tts' ? captureTtsSelectionState() : null
// 保存显示名称
// Save display name
displayNames.value[type] = name
switch (type) {
@ -811,12 +811,12 @@ async function onPickerConfirm(type: string, value: any, name: string) {
break
case 'intent':
formData.value.intentModelId = value
displayNames.value.intent = name // 确保显示名称正确更新
displayNames.value.intent = name // Ensure display name updates correctly
break
case 'memory':
formData.value.memModelId = value
formData.value.chatHistoryConf = value === 'Memory_nomem' ? 0 : 2
displayNames.value.memory = name // 确保显示名称正确更新
displayNames.value.memory = name // Ensure display name updates correctly
displayNames.value.report = reportOptions[1].name
isVisibleReport.value = value !== 'Memory_nomem'
if (value === 'Memory_nomem' || value === 'Memory_mem_report_only') {
@ -856,7 +856,7 @@ async function onPickerConfirm(type: string, value: any, name: string) {
formData.value.ttsLanguage = selectedTtsLanguage.value
ttsLanguageTouched.value = true
}
displayNames.value.voiceprint = name // 确保显示名称正确更新
displayNames.value.voiceprint = name // Ensure display name updates correctly
break
case 'report':
formData.value.chatHistoryConf = value
@ -866,30 +866,30 @@ async function onPickerConfirm(type: string, value: any, name: string) {
pickerShow.value[type] = false
}
// 选择器取消
// Selector canceled
function onPickerCancel(type: string) {
pickerShow.value[type] = false
// 关闭时停止播放
// Stop playback on close
if (type === 'voiceprint') {
stopAudio()
}
}
// 播放音频
// Play audio
async function playAudio(voice: VoiceOption, event: Event) {
event.stopPropagation() // 阻止事件冒泡,防止关闭下拉框
event.stopPropagation() // Prevent event bubbling to avoid closing the dropdown
if (!hasVoicePreview(voice)) {
return
}
// 如果正在播放同一个音频,则停止
// If playing the same audio, stop playback
if (playingVoiceId.value === voice.value) {
stopAudio()
return
}
// 停止之前的音频
// Stop previous audio
stopAudio()
const requestId = voicePreviewRequestGate.begin()
playingVoiceId.value = voice.value
@ -901,7 +901,7 @@ async function playAudio(voice: VoiceOption, event: Event) {
voiceDemo: voice.voiceDemo || voice.voice_demo,
}, getVoiceCloneAudioId, getEnvBaseUrl())
// 用户可能在等待克隆音色临时地址时取消或切换了音色。
// User may have cancelled or switched voices while waiting for the cloned voice temporary URL.
if (!voicePreviewRequestGate.isCurrent(requestId) || playingVoiceId.value !== voice.value) {
return
}
@ -911,12 +911,12 @@ async function playAudio(voice: VoiceOption, event: Event) {
return
}
// 创建新的音频实例
// Create new audio instance
const audio = uni.createInnerAudioContext()
audioRef.value = audio
audio.src = audioUrl
// 监听播放结束
// Listen for playback end
audio.onEnded(() => {
if (
voicePreviewRequestGate.isCurrent(requestId)
@ -927,7 +927,7 @@ async function playAudio(voice: VoiceOption, event: Event) {
}
})
// 监听播放错误
// Listen for playback error
audio.onError(() => {
if (
voicePreviewRequestGate.isCurrent(requestId)
@ -939,29 +939,29 @@ async function playAudio(voice: VoiceOption, event: Event) {
}
})
// 播放音频
// Play audio
audio.play()
}
catch (error) {
if (!voicePreviewRequestGate.isCurrent(requestId) || playingVoiceId.value !== voice.value) {
return
}
console.error('获取克隆音色试听地址失败:', error)
console.error('Failed to get cloned voice preview URL:', error)
toast.error(t('voiceprint.getAudioFailed'))
playingVoiceId.value = ''
})
// 监听播放错误
// Listen for playback error
audioRef.value.onError(() => {
toast.error(t('chatHistory.audioPlayFailed'))
playingVoiceId.value = ''
})
// 播放音频
// Play audio
audioRef.value.play()
}
// 停止音频
// Stop audio
function stopAudio() {
voicePreviewRequestGate.invalidate()
if (audioRef.value) {
@ -972,12 +972,12 @@ function stopAudio() {
playingVoiceId.value = ''
}
// 获取模型显示名称
// Get model display name
function getModelDisplayName(modelType: string, modelId: string) {
if (!modelId)
return t('agent.pleaseSelect')
// 直接从API配置数据中查找匹配的ID
// Look up matching ID directly from API config data
const options = modelOptions.value[modelType]
if (!options || options.length === 0) {
@ -991,7 +991,7 @@ function getModelDisplayName(modelType: string, modelId: string) {
return modelId
}
// 保存智能体
// Save Agent
async function saveAgent() {
if (saving.value) {
return
@ -1029,7 +1029,7 @@ async function saveAgent() {
saving.value = true
const tagNames = dynamicTags.value.map(tag => tag.tagName)
const tagsChanged = !isSameStringList(tagNames, originalTagNames.value)
// 构建保存数据,包含上下文配置和语音设置
// Build save data including context config and voice settings
const saveData: Record<string, any> = {
...formData.value,
contextProviders: providerStore.providers,
@ -1069,7 +1069,7 @@ async function saveAgent() {
toast.success(t('agent.saveSuccess'))
}
catch (error) {
console.error('保存失败:', error)
console.error('Save failed:', error)
toast.error(t('agent.saveFail'))
}
finally {
@ -1089,15 +1089,15 @@ function loadPluginFunctions() {
}) || []
allFunctions.value = processedFunctions
// 同时更新到store
// Also update to store
pluginStore.setAllFunctions(processedFunctions)
})
}
function handleTools() {
console.log('当前插件配置:', formData.value.functions)
console.log('Current plugin config:', formData.value.functions)
// 确保store中有最新数据
// Ensure store contains latest data
pluginStore.setCurrentAgentId(agentId.value)
pluginStore.setCurrentFunctions(normalizeAgentFunctions(formData.value.functions || []))
pluginStore.setAllFunctions(allFunctions.value)
@ -1107,7 +1107,7 @@ function handleTools() {
})
}
// 获取智能体标签
// Get agent tags
async function loadAgentTags(targetAgentId = agentId.value) {
if (!targetAgentId) {
return false
@ -1124,7 +1124,7 @@ async function loadAgentTags(targetAgentId = agentId.value) {
}
catch (error) {
if (isActiveAgentTagRequest(targetAgentId, requestId)) {
console.error('加载智能体标签失败:', error)
console.error('Failed to load Agent tags:', error)
}
return false
}
@ -1180,7 +1180,7 @@ async function reloadAgentAfterSnapshotRestore(targetAgentId = agentId.value) {
}
catch (error) {
if (isActiveSnapshotReload(targetAgentId, reloadId, detailRequestId, tagRequestId)) {
console.error('恢复后重新加载智能体失败:', error)
console.error('Failed to reload Agent after recovery:', error)
snapshotReloadFailed.value = true
toast.error(t('agentSnapshot.reloadAfterRestoreFailed'))
}
@ -1227,7 +1227,7 @@ function isSameStringList(left: string[], right: string[]) {
return left.every((value, index) => value === right[index])
}
// 监听store中的插件配置变化
// Listen for plugin config changes in the store.
watch(() => pluginStore.currentFunctions, (newFunctions) => {
formData.value.functions = normalizeAgentFunctions(newFunctions || [])
}, { deep: true })
@ -1253,14 +1253,14 @@ watch(agentId, (currentAgentId, previousAgentId) => {
onMounted(async () => {
loadAgentTags()
// 先加载模型选项和角色模板
// Load model options and character templates first
await Promise.all([
loadRoleTemplates(),
loadModelOptions(),
loadPluginFunctions(),
])
// 然后加载智能体详情,这样可以正确映射显示名称
// Then load agent details to ensure correct display name mapping
if (agentId.value && !snapshotReloadBlocked.value) {
await loadAgentDetail()
}
@ -1289,14 +1289,14 @@ onMounted(async () => {
</wd-button>
</view>
<!-- 基础信息标题
<!-- Basic info title
<view class="pb-[20rpx] first:pt-[20rpx]">
<text class="text-[32rpx] text-[#232338] font-bold">
{{ t('agent.basicInfo') }}
</text>
</view -->
<!-- 基础信息卡片 -->
<!-- Basic info card -->
<view class="mb-[24rpx] border border-[#eeeeee] rounded-[20rpx] bg-[#fbfbfb] p-[24rpx]" style="box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);">
<view class="mb-[24rpx] last:mb-0">
<text class="mb-[12rpx] block text-[28rpx] text-[#232338] font-medium">
@ -1386,14 +1386,14 @@ onMounted(async () => {
</view>
</view>
<!-- 模型配置标题 -->
<!-- Model config title -->
<view class="pb-[20rpx]">
<text class="text-[32rpx] text-[#232338] font-bold">
{{ t('agent.modelConfig') }}
</text>
</view>
<!-- 模型配置卡片 -->
<!-- Model config card -->
<view class="mb-[24rpx] border border-[#eeeeee] rounded-[20rpx] bg-[#fbfbfb] p-[24rpx]" style="box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);">
<view class="flex flex-col gap-[16rpx]">
<view class="flex cursor-pointer items-center justify-between border border-[#eeeeee] rounded-[12rpx] bg-[#f5f7fb] p-[20rpx] transition-all duration-300 active:bg-[#eef3ff]" @click="openPicker('vad')">
@ -1478,14 +1478,14 @@ onMounted(async () => {
</view>
</view>
<!-- 语音设置标题 -->
<!-- Voice Settings Title -->
<view class="pb-[20rpx]">
<text class="text-[32rpx] text-[#232338] font-bold">
{{ t('agent.voiceSettings') }}
</text>
</view>
<!-- 语音设置卡片 -->
<!-- Voice Settings Card -->
<view class="mb-[24rpx] border border-[#eeeeee] rounded-[20rpx] bg-[#fbfbfb] p-[24rpx]" style="box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);">
<view class="flex flex-col gap-[16rpx]">
<view class="flex cursor-pointer items-center justify-between border border-[#eeeeee] rounded-[12rpx] bg-[#f5f7fb] p-[20rpx] transition-all duration-300 active:bg-[#eef3ff]" @click="openPicker('tts')">
@ -1538,14 +1538,14 @@ onMounted(async () => {
</view>
</view>
<!-- 记忆历史标题 -->
<!-- Memory history title -->
<view class="pb-[20rpx]">
<text class="text-[32rpx] text-[#232338] font-bold">
{{ t('agent.historyMemory') }}
</text>
</view>
<!-- 记忆历史卡片 -->
<!-- Memory history card -->
<view class="mb-[24rpx] border border-[#eeeeee] rounded-[20rpx] bg-[#fbfbfb] p-[24rpx]" style="box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);">
<view class="mb-[24rpx] last:mb-0">
<textarea
@ -1558,7 +1558,7 @@ onMounted(async () => {
</view>
</view>
<!-- 保存按钮 -->
<!-- Save button -->
<view class="mt-[40rpx] p-0">
<view
v-if="snapshotReloadBlocked"
@ -1587,7 +1587,7 @@ onMounted(async () => {
{{ saving ? t('agent.saving') : t('agent.save') }}
</wd-button>
</view>
<!-- 模型选择器 -->
<!-- Model selector -->
<wd-action-sheet
v-model="pickerShow.vad"
:actions="modelOptions.VAD && modelOptions.VAD.map(item => ({ name: item.modelName, value: item.id }))"
@ -1645,7 +1645,7 @@ onMounted(async () => {
@select="({ item }) => onPickerConfirm('tts', item.value, item.name)"
/>
<!-- 自定义语音选择弹出层 -->
<!-- Custom voice selection popup -->
<wd-popup v-model="pickerShow.voiceprint" class="custom-popup" position="bottom" @close="onPickerCancel('voiceprint')">
<view class="overflow-hidden rounded-[20rpx] bg-white pb-[20rpx] pt-[20rpx]">
<view class="max-h-[600rpx] overflow-y-auto">

View file

@ -86,7 +86,7 @@ onMounted(() => {
<template>
<view class="h-screen flex flex-col bg-[#f5f7fb]">
<!-- 头部导航 -->
<!-- Header navigation -->
<wd-navbar
:title="t('contextProviderDialog.title')"
safe-area-inset-top

View file

@ -21,7 +21,7 @@ defineOptions({
name: 'ChatDetail',
})
// 获取屏幕边界到安全区域距离
// Get distance from screen bounds to safe area
let safeAreaInsets: any
let systemInfo: any
@ -42,11 +42,11 @@ systemInfo = uni.getSystemInfoSync()
safeAreaInsets = systemInfo.safeAreaInsets
// #endif
// 页面参数
// Page Parameters
const sessionId = ref('')
const agentId = ref('')
// 智能体信息(简化)
// Agent info (simplified)
const currentAgent = computed(() => {
return {
id: agentId.value,
@ -54,24 +54,24 @@ const currentAgent = computed(() => {
}
})
// 聊天数据
// Chat data
const messageList = ref<ChatMessage[]>([])
const loading = ref(false)
// 音频播放相关
// Audio playback related
const audioContext = ref<UniApp.InnerAudioContext | null>(null)
const playingAudioId = ref<string | null>(null)
const expandedToolResults = ref({})
// 返回上一页
// Go back
function goBack() {
uni.navigateBack()
}
// 加载聊天记录
// Load chat history
async function loadChatHistory() {
if (!sessionId.value || !agentId.value) {
console.error('缺少必要参数')
console.error('Missing required parameters')
return
}
@ -81,7 +81,7 @@ async function loadChatHistory() {
messageList.value = response
}
catch (error) {
console.error('获取聊天记录失败:', error)
console.error('Failed to fetch chat history:', error)
toast.error(t('chatHistory.loadFailed'))
}
finally {
@ -89,7 +89,7 @@ async function loadChatHistory() {
}
}
// 解析用户消息内容
// Parse user message content
function parseUserMessage(content: string): UserMessageContent | null {
try {
return JSON.parse(content)
@ -99,20 +99,20 @@ function parseUserMessage(content: string): UserMessageContent | null {
}
}
// 获取消息显示内容
// Get message display content
function getMessageContent(message: ChatMessage): string {
if (message.chatType === 1) {
// 用户消息,需要解析JSON
// User message, requires JSON parsing
const parsed = parseUserMessage(message.content)
return parsed ? parsed.content : message.content
}
else {
// AI消息,直接显示
// AI message, display directly
return message.content
}
}
// 获取说话人名称
// Get speaker name
function getSpeakerName(message: ChatMessage): string {
if (message.chatType === 1) {
const parsed = parseUserMessage(message.content)
@ -123,47 +123,47 @@ function getSpeakerName(message: ChatMessage): string {
}
}
// 格式化时间
// Format time
function formatTime(timeStr: string) {
if (!timeStr)
return t('chatHistory.unknownTime')
// 处理时间字符串,确保格式正确
const date = new Date(timeStr.replace(' ', 'T')) // 转换为ISO格式
// Process time string to ensure correct format
const date = new Date(timeStr.replace(' ', 'T')) // Convert to ISO format
const now = new Date()
// 检查日期是否有效
// Check if date is valid
if (Number.isNaN(date.getTime())) {
return timeStr // 如果解析失败,直接返回原字符串
return timeStr // If parsing fails, return original string directly
}
const diff = now.getTime() - date.getTime()
// 小于1分钟
// Less than 1 minute
if (diff < 60000)
return t('chatHistory.justNow')
// 小于1小时
// Less than 1 hour
if (diff < 3600000)
return t('chatHistory.minutesAgo', { minutes: Math.floor(diff / 60000) })
// 小于1天(24小时)
// Less than 1 day (24 hours)
if (diff < 86400000)
return t('chatHistory.hoursAgo', { hours: Math.floor(diff / 3600000) })
// 小于7天
// Less than 7 days
if (diff < 604800000) {
const days = Math.floor(diff / 86400000)
return t('chatHistory.daysAgo', { days })
}
// 超过7天,显示具体日期
// Over 7 days, show specific date
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const currentYear = now.getFullYear()
// 如果是当前年份,不显示年份
// If current year, do not display year
if (year === currentYear) {
return `${month}-${day}`
}
@ -171,7 +171,7 @@ function formatTime(timeStr: string) {
return `${year}-${month}-${day}`
}
// 播放音频
// Play audio
const playAudio = debounce(async (audioId: string) => {
if (!audioId) {
toast.error(t('chatHistory.invalidAudioId'))
@ -179,33 +179,33 @@ const playAudio = debounce(async (audioId: string) => {
}
try {
// 如果正在播放其他音频,先停止
// Stop other audio playback if active
if (audioContext.value) {
audioContext.value.stop()
}
// 如果当前音频ID与请求ID相同暂停播放
// Pause playback if the current audio ID matches the request ID
if (playingAudioId.value === audioId) {
playingAudioId.value = null
return
}
// 获取音频下载ID
// Get audio download ID
const downloadId = await getAudioId(audioId)
// 构造音频播放地址
// Construct audio playback URL
const baseUrl = getEnvBaseUrl()
const audioUrl = `${baseUrl}/agent/play/${downloadId}`
// 创建音频上下文
// Create audio context
if (!audioContext.value) {
audioContext.value = uni.createInnerAudioContext()
}
audioContext.value.src = audioUrl
// 设置播放状态
// Set Playback State
playingAudioId.value = audioId
// 监听播放完成
// Listen for playback completion
audioContext.value.onEnded(() => {
playingAudioId.value = null
if (audioContext.value) {
@ -214,9 +214,9 @@ const playAudio = debounce(async (audioId: string) => {
}
})
// 监听播放错误
// Listen for playback error
audioContext.value.onError((error) => {
console.error('音频播放失败:', error)
console.error('Audio playback failed:', error)
toast.error(t('chatHistory.audioPlayFailed'))
playingAudioId.value = null
if (audioContext.value) {
@ -225,11 +225,11 @@ const playAudio = debounce(async (audioId: string) => {
}
})
// 开始播放
// Start playback
audioContext.value.play()
}
catch (error) {
console.error('播放音频失败:', error)
console.error('Failed to play audio:', error)
toast.error(t('chatHistory.playAudioFailed'))
playingAudioId.value = null
}
@ -240,25 +240,25 @@ function extractContentFromString(content: string) {
return content
}
// 尝试解析为 JSON
// Attempt to parse as JSON
try {
const jsonObj = JSON.parse(content)
// 如果是数组格式(包含 text 和 tool)
// If in array format (containing text and tool)
if (Array.isArray(jsonObj)) {
return jsonObj
}
// 如果是对象且有 content 字段
// If it is an object with a content field
if (jsonObj && typeof jsonObj === 'object' && jsonObj.content) {
return jsonObj.content
}
}
catch (e) {
// 如果不是有效的 JSON,直接返回原内容
// If not valid JSON, return original content directly
}
// 如果不是 JSON 格式或没有 content 字段,直接返回原内容
// If not JSON format or missing content field, return original content directly
return content
}
@ -269,7 +269,7 @@ function toggleToolResult(messageIndex, itemIndex) {
function isToolResultCollapsed(messageIndex, itemIndex) {
const key = `${messageIndex}-${itemIndex}`
// 默认折叠(true表示折叠)
// Collapsed by default (true means collapsed)
return !expandedToolResults.value[key]
}
@ -287,7 +287,7 @@ onLoad((options) => {
agentId.value = options.agentId
}
else {
console.error('缺少必要参数')
console.error('Missing required parameters')
toast.error(t('chatHistory.parameterError'))
}
})
@ -296,7 +296,7 @@ onShow(() => {
loadChatHistory()
})
// 页面销毁时清理音频资源
// Clean up audio resources on page destroy
onUnload(() => {
if (audioContext.value) {
audioContext.value.stop()
@ -308,17 +308,17 @@ onUnload(() => {
<template>
<view class="h-screen flex flex-col bg-[#f5f7fb]">
<!-- 状态栏背景 -->
<!-- Status bar background -->
<view class="w-full bg-white" :style="{ height: `${safeAreaInsets?.top}px` }" />
<!-- 导航栏 -->
<!-- Navigation bar -->
<wd-navbar :title="t('chatHistory.pageTitle')">
<template #left>
<wd-icon name="arrow-left" size="18" @click="goBack" />
</template>
</wd-navbar>
<!-- 聊天消息列表 -->
<!-- Chat message list -->
<scroll-view
scroll-y
:style="{ height: `calc(100vh - ${safeAreaInsets?.top || 0}px - 120rpx)` }"
@ -351,7 +351,7 @@ onUnload(() => {
'tool-message': message.chatType === 3,
}"
>
<!-- 消息气泡 -->
<!-- Message bubble -->
<view
class="shadow-message break-words rounded-[20rpx] p-[24rpx] leading-[1.4]"
:class="{
@ -387,9 +387,9 @@ onUnload(() => {
</div>
</div>
</template>
<!-- 内容区域 - 使用flex布局让图标和文本对齐 -->
<!-- Content area - Use flex layout to align icons and text -->
<view v-else class="flex items-center gap-[12rpx]">
<!-- 音频播放图标 -->
<!-- Audio playback icon -->
<view
v-if="message.audioId"
class="flex-shrink-0 cursor-pointer transition-transform duration-200 active:scale-90"
@ -409,9 +409,9 @@ onUnload(() => {
/>
</view>
<!-- 消息内容容器 -->
<!-- Message content container -->
<view class="min-w-0 flex-1">
<!-- 消息内容 -->
<!-- Message content -->
<text class="block text-[28rpx]">
{{ getMessageContent(message) }}
</text>
@ -419,7 +419,7 @@ onUnload(() => {
</view>
</view>
<!-- 说话人信息 -->
<!-- Speaker info -->
<text
class="mx-[12rpx] text-[22rpx] text-[#9d9ea3]"
:class="{
@ -437,7 +437,7 @@ onUnload(() => {
</template>
<style>
/* 自定义阴影和动画效果,无法用UnoCSS表示的样式 */
/* Custom shadow and animation effects; styles not expressible with UnoCSS */
.shadow-message {
box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

View file

@ -23,7 +23,7 @@ defineOptions({
const toast = useToast()
// 缓存信息
// Cache info
const cacheInfo = reactive({
storageSize: '0MB',
imageCache: '0MB',
@ -32,23 +32,23 @@ const cacheInfo = reactive({
const configStore = useConfigStore()
// 服务端地址设置
// Server address settings
const baseUrlInput = ref('')
const urlError = ref('')
// 系统信息(保留)
// System info (reserved)
const systemInfo = computed(() => {
const info = uni.getSystemInfoSync()
return `${info.platform} ${info.system}`
})
// 读取本地覆盖地址
// Read local override address
function loadServerBaseUrl() {
const override = getServerBaseUrlOverride()
baseUrlInput.value = override || getEnvBaseUrl()
}
// 获取缓存信息
// Get cache info
function getCacheInfo() {
try {
const info = uni.getStorageInfoSync()
@ -56,11 +56,11 @@ function getCacheInfo() {
cacheInfo.storageSize = `${totalSize.toFixed(2)}MB`
}
catch (error) {
console.error('获取缓存信息失败:', error)
console.error('Failed to fetch cache info:', error)
}
}
// 验证URL格式
// Validate URL format
function validateUrl() {
urlError.value = ''
@ -73,9 +73,9 @@ function validateUrl() {
}
}
// 测试服务端地址
// Test server address
async function testServerBaseUrl() {
// 先清除错误信息
// Clear error messages first
urlError.value = ''
if (!baseUrlInput.value || !/^https?:\/\/.+\/xiaozhi$/.test(baseUrlInput.value)) {
@ -101,7 +101,7 @@ async function testServerBaseUrl() {
}
}
catch (error) {
console.error('测试服务端地址失败:', error)
console.error('Failed to test server address:', error)
toast.error({
msg: t('message.invalidAddress'),
duration: 3000,
@ -110,20 +110,20 @@ async function testServerBaseUrl() {
}
}
// 保存服务端地址
// Save server address
async function saveServerBaseUrl() {
if (!baseUrlInput.value || !/^https?:\/\/.+\/xiaozhi$/.test(baseUrlInput.value)) {
toast.warning(t('settings.validServerUrl'))
return
}
// 测试地址有效性
// Test address validity
const isServerValid = await testServerBaseUrl()
if (!isServerValid) {
return
}
setServerBaseUrlOverride(baseUrlInput.value)
// 处理config缓存无法更新的问题
// Handle issue where config cache cannot be updated
uni.request({
url: `${getEnvBaseUrl()}/user/pub-config`,
method: 'GET',
@ -134,11 +134,11 @@ async function saveServerBaseUrl() {
}
},
fail: (err) => {
console.error('获取SM2公钥失败:', err)
console.error('Failed to get SM2 public key:', err)
},
})
// 切换请求地址后清空所有缓存
// Clear all caches after switching request address
clearAllCacheAfterUrlChange()
uni.showModal({
@ -157,7 +157,7 @@ async function saveServerBaseUrl() {
})
}
// 语言切换
// Language Switch
const supportedLanguages = getSupportedLanguages()
const currentLanguage = ref<Language>(getCurrentLanguage())
const showLanguageSheet = ref(false)
@ -169,12 +169,12 @@ function handleLanguageChange(lang: Language) {
toast.success(t('settings.languageChanged'))
}
// 重置为 env 默认
// Reset to env default
function resetServerBaseUrl() {
clearServerBaseUrlOverride()
baseUrlInput.value = getEnvBaseUrl()
// 切换请求地址后清空所有缓存
// Clear all caches after switching request address
clearAllCacheAfterUrlChange()
uni.showModal({
@ -193,7 +193,7 @@ function resetServerBaseUrl() {
})
}
// 重启应用(App 原生重启;其他端回到首页)
// Restart app (native restart for App; return to home for other clients)
function restartApp() {
// #ifdef APP-PLUS
plus.runtime.restart()
@ -203,36 +203,36 @@ function restartApp() {
// #endif
}
// 切换地址后自动清空所有缓存
// Automatically clear all caches after switching address
function clearAllCacheAfterUrlChange() {
try {
// 备份运行时覆盖地址,确保清理后恢复
// Backup runtime override address to ensure restoration after cleanup
const preservedOverride = getServerBaseUrlOverride()
// 完全清空所有缓存,包括token
// Clear all caches, including tokens
uni.clearStorageSync()
// 清空localStorage(H5环境)
// Clear localStorage (H5 environment)
// #ifdef H5
if (typeof localStorage !== 'undefined') {
localStorage.clear()
}
// #endif
// 恢复运行时覆盖地址(如有),需要在清理完成后再写入
// Restore runtime override address (if any) after cleanup is complete
if (preservedOverride) {
setServerBaseUrlOverride(preservedOverride)
}
// 重新获取缓存信息
// Refresh cached information
getCacheInfo()
}
catch (error) {
console.error('清除缓存失败:', error)
console.error('Failed to clear cache:', error)
}
}
// 清除缓存
// Clear cache
async function clearCache() {
try {
uni.showModal({
@ -245,7 +245,7 @@ async function clearCache() {
clearAllCacheAfterUrlChange()
toast.success(t('settings.cacheCleared'))
// 延迟跳转到登录页
// Delayed redirect to login page
setTimeout(() => {
uni.reLaunch({ url: '/pages/login/index' })
}, 1500)
@ -254,12 +254,12 @@ async function clearCache() {
})
}
catch (error) {
console.error('清除缓存失败:', error)
console.error('Failed to clear cache:', error)
toast.error(t('settings.clearCacheFailed'))
}
}
// 关于我们
// About Us
function showAbout() {
uni.showModal({
title: t('settings.aboutApp', { appName: import.meta.env.VITE_APP_TITLE }),
@ -273,13 +273,13 @@ function showAbout() {
}
onMounted(async () => {
// 仅在非小程序环境加载服务端地址设置
// Load server address settings only in non-mini-program environments
if (!isMp) {
loadServerBaseUrl()
}
getCacheInfo()
// 动态设置导航栏标题为国际化文本
// Dynamically set navbar title to localized text
uni.setNavigationBarTitle({
title: t('settings.title'),
})
@ -291,7 +291,7 @@ onMounted(async () => {
<wd-navbar :title="t('settings.title')" placeholder safe-area-inset-top fixed />
<view class="p-[24rpx]">
<!-- 网络设置 - 仅在非小程序环境显示 -->
<!-- Network settings - Display only in non-mini-program environments -->
<view v-if="!isMp" class="mb-[32rpx]">
<view class="mb-[24rpx] flex items-center">
<text class="text-[32rpx] text-[#232338] font-bold">
@ -345,7 +345,7 @@ onMounted(async () => {
</view>
</view>
<!-- 缓存管理 -->
<!-- Cache management -->
<view class="mb-[32rpx]">
<view class="mb-[24rpx] flex items-center">
<text class="text-[32rpx] text-[#232338] font-bold">
@ -358,7 +358,7 @@ onMounted(async () => {
style="box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);"
>
<view class="space-y-[16rpx]">
<!-- 缓存信息展示,参考插件样式 -->
<!-- Display cache info, refer to plugin style -->
<view
class="flex items-center justify-between border border-[#eeeeee] rounded-[16rpx] bg-[#f5f7fb] p-[24rpx] transition-all active:bg-[#eef3ff]"
>
@ -375,7 +375,7 @@ onMounted(async () => {
</text>
</view>
<!-- 清除缓存按钮,参考插件编辑按钮样式 -->
<!-- Clear cache button, styled like the plugin edit button -->
<view
class="flex items-center justify-between border border-[#eeeeee] rounded-[16rpx] bg-[#f5f7fb] p-[24rpx]"
>
@ -398,7 +398,7 @@ onMounted(async () => {
</view>
</view>
<!-- 应用信息 -->
<!-- App info -->
<view class="mb-[32rpx]">
<view class="mb-[24rpx] flex items-center">
<text class="text-[32rpx] text-[#232338] font-bold">
@ -427,7 +427,7 @@ onMounted(async () => {
</view>
</view>
<!-- 语言设置 -->
<!-- Language Settings -->
<view class="mb-[32rpx]">
<view class="mb-[24rpx] flex items-center">
<text class="text-[32rpx] text-[#232338] font-bold">
@ -461,7 +461,7 @@ onMounted(async () => {
</view>
</view>
<!-- 语言选择弹窗 -->
<!-- Language Selection Modal -->
<wd-action-sheet v-model="showLanguageSheet" :title="t('settings.selectLanguage')" :close-on-click-modal="true">
<view class="language-sheet">
<scroll-view scroll-y class="language-list">
@ -477,17 +477,17 @@ onMounted(async () => {
</view>
</wd-action-sheet>
<!-- 底部安全距离 -->
<!-- 底部安全距离 -->
<!-- Bottom safe area inset -->
<!-- Bottom safe area inset -->
<view style="height: env(safe-area-inset-bottom);" />
</view>
</view>
</template>
<style lang="scss" scoped>
// 保持与 edit.vue 一致的风格,样式主要通过类名控制
// Maintain style consistent with edit.vue; styles are primarily controlled via class names
// 语言选择弹窗样式
// Language selection modal styles
.language-sheet {
.language-list {
max-height: 50vh;

View file

@ -1,5 +1,5 @@
import { createPinia } from 'pinia'
import { createPersistedState } from 'pinia-plugin-persistedstate' // 数据持久化
import { createPersistedState } from 'pinia-plugin-persistedstate' // Data persistence
const store = createPinia()
store.use(
@ -17,5 +17,5 @@ export * from './config'
export * from './plugin'
export * from './provider'
export * from './speedPitch'
// 模块统一导出
// Unified module exports
export * from './user'

View file

@ -1,4 +1,4 @@
// 引入各个模块的请求
// Import requests for each module
import admin from './module/admin.js'
import agent from './module/agent.js'
import device from './module/device.js'
@ -16,21 +16,21 @@ import addressBook from './module/addressBook.js'
/**
* 接口地址
* 开发时自动读取使用.env.development文件
* 编译时自动读取使用.env.production文件
* API endpoint
* Automatically load .env.development during development
* Automatically read .env.production file during compilation
*/
const DEV_API_SERVICE = process.env.VUE_APP_API_BASE_URL
/**
* 根据开发环境返回接口url
* Return API URL based on development environment
* @returns {string}
*/
export function getServiceUrl() {
return DEV_API_SERVICE
}
/** request服务封装 */
/** Request service wrapper */
export default {
getServiceUrl,
user,

View file

@ -3,7 +3,7 @@ import RequestService from '../httpRequest';
export default {
/**
* 获取设备通讯录列表
* Get device contacts list
*/
getAddressBookList(macAddress, callback) {
RequestService.sendRequest()
@ -21,7 +21,7 @@ export default {
},
/**
* 更新设备通讯录别名
* Update device contact alias
*/
updateAlias(data, callback) {
RequestService.sendRequest()
@ -40,7 +40,7 @@ export default {
},
/**
* 更新设备通讯录权限
* Update device contact permissions
*/
updatePermission(data, callback) {
RequestService.sendRequest()

View file

@ -21,7 +21,7 @@ test("snapshot restore sends the preview token once without an automatic replay"
const source = sourceBetween(
agentApiSource,
"restoreAgentSnapshot(agentId",
"// 删除智能体配置快照"
"// Delete Agent config snapshot"
);
assert.match(source, /restoreAgentSnapshot\(agentId, snapshotId, currentStateToken, callback, onTerminalFailure\)/);
@ -35,7 +35,7 @@ test("snapshot deletion terminates on network failure without an automatic repla
const source = sourceBetween(
agentApiSource,
"deleteAgentSnapshot(agentId",
"// 新增方法:获取智能体模板"
"// New method: Get Agent template"
);
assert.match(source, /deleteAgentSnapshot\(agentId, snapshotId, callback, onTerminalFailure\)/);

View file

@ -23,7 +23,7 @@ function retryCallbackRequest(retry, retryCount, onTerminalFailure, error, retry
export default {
// 获取替换词文件列表
// Get replacement word file list
getFileList(params, callback) {
const queryParams = new URLSearchParams({
page: params.page,
@ -38,14 +38,14 @@ export default {
callback(res)
})
.networkFail((err) => {
console.error('获取替换词文件列表失败:', err)
console.error('Failed to fetch replacement word file list:', err)
RequestService.reAjaxFun(() => {
this.getFileList(params, callback)
})
}).send()
},
// 获取所有替换词文件(不分页)
// Get all replacement-word files (no pagination)
selectAll(callback, onTerminalFailure, retryCount = 0, retryStartedAt = 0) {
const retryWindowStartedAt = retryStartedAt || Date.now()
const request = RequestService.sendRequest()
@ -56,7 +56,7 @@ export default {
callback(res)
})
.networkFail((err) => {
console.error('获取所有替换词文件失败:', err)
console.error('Failed to get all replacement word files:', err)
retryCallbackRequest(
(nextRetryCount, nextRetryStartedAt) => this.selectAll(
callback,
@ -79,7 +79,7 @@ export default {
request.send()
},
// 下载替换词文件
// Download replacement word file
downloadFile(id, callback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/correct-word/file/download/${id}`)
@ -94,7 +94,7 @@ export default {
}).send()
},
// 新增替换词文件
// Add replacement word file
addFile(data, callback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/correct-word/file`)
@ -110,7 +110,7 @@ export default {
}).send()
},
// 更新替换词文件
// Update replacement word file
updateFile(data, callback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/correct-word/file/${data.id}`)
@ -129,7 +129,7 @@ export default {
}).send()
},
// 删除替换词文件
// Delete replacement word file
deleteFile(id, callback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/correct-word/file/${id}`)
@ -139,14 +139,14 @@ export default {
callback(res)
})
.networkFail((err) => {
console.error('删除替换词文件失败:', err)
console.error('Failed to delete replacement word file:', err)
RequestService.reAjaxFun(() => {
this.deleteFile(id, callback)
})
}).send()
},
// 批量删除替换词文件
// Batch delete replacement word files
batchDeleteFile(ids, callback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/correct-word/file/batch-delete`)
@ -157,7 +157,7 @@ export default {
callback(res)
})
.networkFail((err) => {
console.error('批量删除替换词文件失败:', err)
console.error('Failed to batch delete replacement word files:', err)
RequestService.reAjaxFun(() => {
this.batchDeleteFile(ids, callback)
})

View file

@ -64,7 +64,7 @@ export default {
trigger: "blur"
},
{
pattern: /^[一-龥a-zA-Z0-9\s-_]+$/,
pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s-_]+$/,
message: this.$t("addressBookDialog.namePattern"),
trigger: "blur"
}

View file

@ -1433,7 +1433,7 @@ export default {
}
resolve();
}, () => {
// 权限不足或元数据服务不可用时保留原始 ID,不扩大文件列表的访问边界。
// Retain original ID when permissions are insufficient or metadata service is unavailable; do not expand file list access boundaries
this.correctWordMetadataLoaded = true;
resolve();
});

View file

@ -236,7 +236,7 @@ export default {
if (this.messages.length > 0 && this.messages[0].macAddress) {
this.currentMacAddress = this.messages[0].macAddress;
}
// 更新会话列表中的聊天记录数量
// Update chat history count in session list
this.sessions = this.sessions.map(item => {
if (item.sessionId === session.sessionId) {
item.chatCount = this.messages.length;
@ -599,7 +599,7 @@ export default {
transform: translate(-50%, -50%);
height: 90vh;
max-width: 85vw;
/* 兜底,防止 size="large" 那个 height 没有生效时弹框缩成内容高度 */
/* Fallback to prevent the dialog from collapsing to content height when height for size="large" is not applied */
height: calc(100vh - 20px) !important;
}

View file

@ -146,7 +146,7 @@ export default {
</script>
<style lang="scss" scoped>
/* 大档与小档通过 .custom-dialog--large 区分 */
/* Distinguish large and small dialogs using .custom-dialog--large */
::v-deep .el-dialog.custom-dialog {
border-radius: 10px;
overflow: hidden;
@ -163,7 +163,7 @@ export default {
padding: 20px;
}
/* .v-modal 样式由 global.scss 全局定义 */
/* .v-modal styles are defined globally in global.scss */
::v-deep .el-dialog__header {
padding: 16px 20px 12px;
background: linear-gradient(135deg, #e2eeff, #edeafe);
@ -259,7 +259,7 @@ export default {
}
}
/* 大档:上下各留 10px 让边框和圆角可见 */
/* Large size: add 10px padding top and bottom to show border and rounded corners */
::v-deep .el-dialog.custom-dialog.custom-dialog--large {
margin: 10px auto !important;
height: calc(100vh - 20px);

View file

@ -15,12 +15,12 @@
@selection-change="handleSelectionChange"
@row-click="handleRowClick"
>
<!-- 选择列 -->
<!-- Select column -->
<el-table-column
v-if="showSelection"
width="55"
align="center"
label="选择"
label="Select"
>
<template slot-scope="scope">
<slot
@ -37,7 +37,7 @@
</template>
</el-table-column>
<!-- 动态列 -->
<!-- Dynamic column -->
<el-table-column
v-for="column in columns"
:key="column.prop"
@ -49,7 +49,7 @@
:show-overflow-tooltip="column.showOverflowTooltip !== false"
>
<template slot-scope="scope">
<!-- 自定义插槽:优先使用 column.slot 指定的插槽名,否则用 column.prop 作为插槽名 -->
<!-- Custom slots: Prioritize the slot name specified by column.slot, otherwise use column.prop as the slot name -->
<slot
v-if="$scopedSlots[column.slot] || $scopedSlots[column.prop]"
:name="column.slot || column.prop"
@ -57,14 +57,14 @@
:$index="scope.$index"
:column="column"
/>
<!-- 默认显示 -->
<!-- Visible by Default -->
<template v-else>
{{ scope.row[column.prop] }}
</template>
</template>
</el-table-column>
<!-- 操作列 -->
<!-- Action column -->
<el-table-column
v-if="showOperations"
:label="operationsLabel"
@ -78,7 +78,7 @@
</el-table>
</div>
<!-- 分页 -->
<!-- Pagination -->
<div class="table-footer">
<slot name="footer-btns"></slot>
<CustomPagination
@ -103,35 +103,35 @@ export default {
CustomPagination
},
props: {
// 表格数据
// Table data
data: {
type: Array,
default: () => []
},
// 列配置
// Column config
columns: {
type: Array,
default: () => []
},
// 是否显示选择框
// Show selection box
showSelection: {
type: Boolean,
default: false
},
// 是否显示操作列
// Show action column
showOperations: {
type: Boolean,
default: false
},
operationsLabel: {
type: String,
default: '操作'
default: 'Action'
},
operationsWidth: {
type: [String, Number],
default: 180
},
// 分页相关
// Pagination Related
showPagination: {
type: Boolean,
default: true
@ -152,7 +152,7 @@ export default {
type: Array,
default: () => [10, 20, 50, 100]
},
// 加载状态
// Loading status
loading: {
type: Boolean,
default: false
@ -169,7 +169,7 @@ export default {
type: String,
default: 'rgba(255, 255, 255, 0.7)'
},
// 自定义类名
// Custom class name
tableClass: {
type: String,
default: ''
@ -189,30 +189,30 @@ export default {
}
},
methods: {
// 复选框变化
// Checkbox change
handleCheckboxChange(row) {
this.$set(row, 'selected', !row.selected);
},
// 分页事件
// Pagination Events
handleSizeChange(val) {
this.$emit('size-change', val);
},
handlePageChange(page) {
this.$emit('page-change', page);
},
// 选择事件
// Select Event
handleSelectionChange(selection) {
this.$emit('selection-change', selection);
},
// 行点击事件
// Row click event
handleRowClick(row, column, event) {
this.$emit('row-click', row, column, event);
},
// 清除选择
// Clear selection
clearSelection() {
this.$refs.tableRef && this.$refs.tableRef.clearSelection();
},
// 切换选择
// Toggle Selection
toggleRowSelection(row, selected) {
this.$refs.tableRef && this.$refs.tableRef.toggleRowSelection(row, selected);
}

View file

@ -120,7 +120,7 @@ export default {
}
// After successful submission, let parent component handle dialog closing logic
this.$emit('submit', this.form)
// 兜底:父组件若未在回调内重置 saving,3 秒后强制释放加载状态
// Fallback: If parent component does not reset saving in callback, force release loading state after 3 seconds
setTimeout(() => {
this.saving = false
}, 3000)
@ -131,7 +131,7 @@ export default {
this.saving = false
this.$emit('cancel')
},
// 提供给父组件调用以重置saving状态
// Expose to parent component to reset saving state
resetSaving() {
this.saving = false
},

View file

@ -1,6 +1,6 @@
<template>
<el-drawer :visible.sync="dialogVisible" direction="rtl" size="80%" :wrapperClosable="false" :withHeader="false">
<!-- 自定义标题区域 -->
<!-- Custom title area -->
<div class="custom-header">
<div class="header-left">
<h3 class="bold-title">{{ $t('functionDialog.title') }}</h3>
@ -9,7 +9,7 @@
</div>
<div class="function-manager">
<!-- 左侧:未选功能 -->
<!-- Left: No feature selected -->
<div class="function-column">
<div class="column-header">
<h4 class="column-title">{{ $t('functionDialog.unselectedFunctions') }}</h4>
@ -34,7 +34,7 @@
</div>
</div>
<!-- 中间:已选功能 -->
<!-- Middle: Selected features -->
<div class="function-column">
<div class="column-header">
<h4 class="column-title">{{ $t('functionDialog.selectedFunctions') }}</h4>
@ -59,14 +59,14 @@
</div>
</div>
<!-- 右侧:参数配置 -->
<!-- Right side: Parameter config -->
<div class="params-column">
<h4 v-if="currentFunction" class="column-title">
{{ $t('functionDialog.paramConfig') }} - {{ currentFunction.name }}
</h4>
<div v-if="currentFunction" class="params-container">
<el-form :model="currentFunction" class="param-form">
<!-- 遍历 fieldsMeta,而不是 params 的 keys -->
<!-- Iterate over fieldsMeta instead of params keys -->
<div v-if="currentFunction.fieldsMeta.length == 0">
<el-empty :description="currentFunction.name + $t('functionDialog.noNeedToConfig')" />
</div>
@ -105,10 +105,10 @@
</div>
</div>
<!-- MCP区域 -->
<!-- MCP Region -->
<div class="mcp-access-point" v-if="featureStatus.mcpAccessPoint">
<div class="mcp-container">
<!-- 左侧区域 -->
<!-- Left area -->
<div class="mcp-left">
<div class="mcp-header">
<h3 class="bold-title">{{ $t('functionDialog.mcpAccessPoint') }}</h3>
@ -131,7 +131,7 @@
</el-input>
</div>
<!-- 右侧区域 -->
<!-- Right-side area -->
<div class="mcp-right">
<div class="mcp-header">
<h3 class="bold-title">{{ $t('functionDialog.accessPointStatus') }}</h3>
@ -199,7 +199,7 @@ export default {
currentFunction: null,
modifiedFunctions: {},
tempFunctions: {},
// 添加一个标志位来跟踪是否已经保存
// Add a flag to track whether the state has been saved
hasSaved: false,
loading: false,
@ -207,7 +207,7 @@ export default {
mcpStatus: "disconnected",
mcpTools: [],
// 功能状态
// Feature status
featureStatus: {
mcpAccessPoint: false,
addressBook: false
@ -217,7 +217,7 @@ export default {
computed: {
selectedList() {
const list = this.allFunctions.filter(f => this.selectedNames.includes(f.name));
// 如果通讯录功能未启用,过滤掉设备呼叫设备插件
// If the contacts feature is disabled, filter out the device-to-device call plugin
if (!this.featureStatus.addressBook) {
return list.filter(f => f.providerCode !== 'call_device');
}
@ -225,7 +225,7 @@ export default {
},
unselected() {
const list = this.allFunctions.filter(f => !this.selectedNames.includes(f.name));
// 如果通讯录功能未启用,过滤掉设备呼叫设备插件
// If the contacts feature is disabled, filter out the device-to-device call plugin
if (!this.featureStatus.addressBook) {
return list.filter(f => f.providerCode !== 'call_device');
}
@ -235,7 +235,7 @@ export default {
watch: {
currentFunction(newFn) {
if (!newFn) return;
// 对每个字段,如果是 array 或 json,就在 textCache 里生成初始字符串
// For each field, if it is an array or JSON, generate an initial string in textCache
newFn.fieldsMeta.forEach(f => {
const v = newFn.params[f.key];
if (f.type === 'array') {
@ -253,13 +253,13 @@ export default {
async value(v) {
this.dialogVisible = v;
if (v) {
// 加载功能状态(需要在初始化选中态之前)
// Load feature status (must be done before initializing selection state)
await this.loadFeatureStatus();
// 对话框打开时,初始化选中态
// Initialize selection state when dialog opens
this.selectedNames = this.functions.map(f => f.name);
// 如果通讯录功能未启用,从已选列表中移除设备呼叫设备插件
// If the contacts feature is disabled, remove the device-to-device call plugin from the selected list
if (!this.featureStatus.addressBook) {
this.selectedNames = this.selectedNames.filter(name => {
const func = this.allFunctions.find(f => f.name === name);
@ -267,18 +267,18 @@ export default {
});
}
// 把后端传来的 this.functions(带 params)merge 到 allFunctions 上
// Merge backend-provided this.functions (with params) into allFunctions
this.functions.forEach(saved => {
const idx = this.allFunctions.findIndex(f => f.name === saved.name);
if (idx >= 0) {
// 保留用户之前在 saved.params 上的改动
// Preserve user changes to saved.params
this.allFunctions[idx].params = { ...saved.params };
}
});
// 右侧默认指向第一个
// Right side defaults to the first item
this.currentFunction = this.selectedList[0] || null;
// 加载MCP数据
// Load MCP data
this.loadMcpAddress();
this.loadMcpTools();
}
@ -289,10 +289,10 @@ export default {
},
methods: {
/**
* 加载功能状态
* Load feature status
*/
async loadFeatureStatus() {
// 确保featureManager已初始化完成
// Ensure featureManager is fully initialized
await featureManager.waitForInitialization();
const config = featureManager.getConfig();
@ -305,7 +305,7 @@ export default {
copyUrl() {
const textarea = document.createElement('textarea');
textarea.value = this.mcpUrl;
textarea.style.position = 'fixed'; // 防止页面滚动
textarea.style.position = 'fixed'; // Prevent page scrolling
document.body.appendChild(textarea);
textarea.select();
@ -318,7 +318,7 @@ export default {
}
} catch (err) {
this.$message.error(this.$t('functionDialog.copyFailed'));
console.error('复制失败:', err);
console.error('Copy failed:', err);
} finally {
document.body.removeChild(textarea);
}
@ -329,29 +329,29 @@ export default {
this.loadMcpTools();
},
// 加载MCP接入点地址
// Load MCP endpoint address
loadMcpAddress() {
Api.agent.getAgentMcpAccessAddress(this.agentId, (res) => {
if (res.data.code === 0) {
this.mcpUrl = res.data.data || "";
} else {
this.mcpUrl = res.data.msg;
console.error('获取MCP地址失败:', res.data.msg);
console.error('Failed to get MCP address:', res.data.msg);
}
});
},
// 加载MCP工具列表
// Load MCP tool list
loadMcpTools() {
Api.agent.getAgentMcpToolsList(this.agentId, (res) => {
if (res.data.code === 0) {
this.mcpTools = res.data.data || [];
// 根据工具列表更新状态
// Update status based on tool list
this.mcpStatus = this.mcpTools.length > 0 ? "connected" : "disconnected";
} else {
this.mcpTools = [];
this.mcpStatus = "disconnected";
console.error('获取MCP工具列表失败:', res.data.msg);
console.error('Failed to get MCP tool list:', res.data.msg);
}
});
},
@ -445,20 +445,20 @@ export default {
}
});
// 如果通讯录功能未启用,自动取消已选的设备呼叫设备插件
// If contacts feature is disabled, automatically deselect the device call plugin
if (!this.featureStatus.addressBook) {
selected = selected.filter(f => f.providerCode !== 'call_device');
}
this.$emit('update-functions', selected);
this.dialogVisible = false;
// 通知父组件对话框已关闭且已保存
// Notify parent component that dialog is closed and saved
this.$emit('dialog-closed', true);
},
fieldRemark(field) {
let description = (field && field.label) ? field.label : '';
if (field.default) {
description += `(${this.$t('functionDialog.defaultValue')}:${field.default})`;
description += `(${this.$t('functionDialog.defaultValue')}:${field.default})`;
}
return description;
},
@ -806,17 +806,17 @@ export default {
&.disconnected {
background-color: #909399;
/* 灰色 - 未连接 */
/* Gray - Not connected */
}
&.connected {
background-color: #67C23A;
/* 绿色 - 已连接 */
/* Green - Connected */
}
&.loading {
background-color: #E6A23C;
/* 橙色 - 加载中 */
/* Orange - Loading */
animation: pulse 1.5s infinite;
}
}

View file

@ -1,13 +1,13 @@
<template>
<el-header class="header">
<div class="header-container">
<!-- 左侧元素 -->
<!-- Left element -->
<div class="header-left" @click="handleRouter('home')">
<img loading="lazy" alt="" src="@/assets/xiaozhi-logo.png" class="logo-img" />
<img loading="lazy" alt="" :src="xiaozhiAiIcon" class="brand-img" />
</div>
<!-- 中间导航菜单 -->
<!-- Middle navigation menu -->
<div class="header-center">
<div class="equipment-management" :class="{
'active-tab':
@ -25,7 +25,7 @@
}" />
<span class="nav-text">{{ $t("header.smartManagement") }}</span>
</div>
<!-- 普通用户显示音色克隆 -->
<!-- Show voice cloning for regular users -->
<div v-if="!userInfo.superAdmin && featureStatus.voiceClone" class="equipment-management"
:class="{ 'active-tab': $route.path === '/voice-clone-management' }"
@click="handleRouter('voiceCloneManagement')">
@ -38,7 +38,7 @@
<span class="nav-text">{{ $t("header.voiceCloneManagement") }}</span>
</div>
<!-- 超级管理员显示音色克隆下拉菜单 -->
<!-- Show voice cloning dropdown menu for super admin -->
<el-dropdown v-if="userInfo.superAdmin && featureStatus.voiceClone" trigger="click"
class="equipment-management more-dropdown" :class="{
'active-tab':
@ -154,7 +154,7 @@
</el-dropdown>
</div>
<!-- 右侧元素 -->
<!-- Right-side element -->
<div class="header-right">
<img loading="lazy" alt="" src="@/assets/home/avatar.png" class="avatar-img" @click="handleAvatarClick" />
<span class="el-user-dropdown" @click="handleAvatarClick">
@ -171,7 +171,7 @@
</div>
</div>
<!-- 修改密码弹窗 -->
<!-- Change password dialog -->
<ChangePasswordDialog v-model="isChangePasswordDialogVisible" />
</el-header>
</template>
@ -179,32 +179,32 @@
<script>
import i18n, { changeLanguage, getLanguageLabelKey, supportedLanguages } from "@/i18n";
import userApi from "@/apis/module/user";
import featureManager from "@/utils/featureManager"; // 引入功能管理工具类
import featureManager from "@/utils/featureManager"; // Import feature management utility class
import { mapActions, mapState } from "vuex";
import ChangePasswordDialog from "./ChangePasswordDialog.vue"; // 引入修改密码弹窗组件
import ChangePasswordDialog from "./ChangePasswordDialog.vue"; // Import change password modal component
export default {
name: "HeaderBar",
components: {
ChangePasswordDialog,
},
props: ["devices"], // 接收父组件设备列表
props: ["devices"], // Receive device list from parent component
data() {
return {
search: "",
isChangePasswordDialogVisible: false, // 控制修改密码弹窗的显示
isChangePasswordDialogVisible: false, // Control visibility of change password dialog
paramDropdownVisible: false,
voiceCloneDropdownVisible: false,
userMenuVisible: false, // 添加用户菜单可见状态
menuVisibleTimer: null, // 菜单显示定时器,防止够快触发
// Cascader 配置
userMenuVisible: false, // Add user menu visibility status
menuVisibleTimer: null, // Menu display timer to prevent rapid triggering
// Cascader Config
cascaderProps: {
expandTrigger: "click",
value: "value",
label: "label",
children: "children",
},
// 跳转页面配置
// Page Navigation Config
routerPaths: {
home: "/home",
modelConfig: "/model-config",
@ -227,9 +227,9 @@ export default {
computed: {
...mapState({
featureStatus: (state) => ({
voiceClone: state.pubConfig.systemWebMenu?.features?.voiceClone?.enabled, // 音色克隆功能状态
knowledgeBase: state.pubConfig.systemWebMenu?.features?.knowledgeBase?.enabled, // 知识库功能状态
addressBook: state.pubConfig.systemWebMenu?.features?.addressBook?.enabled, // 通讯录功能状态
voiceClone: state.pubConfig.systemWebMenu?.features?.voiceClone?.enabled, // Voice cloning feature status
knowledgeBase: state.pubConfig.systemWebMenu?.features?.knowledgeBase?.enabled, // Knowledge base feature status
addressBook: state.pubConfig.systemWebMenu?.features?.addressBook?.enabled, // Contacts feature status
}),
userInfo: (state) => state.userInfo,
}),
@ -251,7 +251,7 @@ export default {
return require("@/assets/xiaozhi-ai_en.png");
}
},
// 用户菜单选项
// User menu options
userMenuOptions() {
return [
{
@ -277,9 +277,9 @@ export default {
this.fetchUserInfo();
this.checkScreenSize();
window.addEventListener("resize", this.checkScreenSize);
// 从localStorage加载搜索历史
// Load search history from localStorage
this.loadSearchHistory();
// 等待featureManager初始化完成后再加载功能状态
// Wait for featureManager initialization to complete before loading feature states
await this.loadFeatureStatus();
},
methods: {
@ -293,45 +293,45 @@ export default {
}
});
},
// 加载功能状态
// Load feature status
async loadFeatureStatus() {
// 等待featureManager初始化完成
// Wait for featureManager initialization to complete
await featureManager.waitForInitialization();
},
// 显示修改密码弹窗
// Show change password dialog
showChangePasswordDialog() {
this.isChangePasswordDialogVisible = true;
// 添加:显示修改密码弹窗后重置用户菜单可见状态
// Add: Reset user menu visibility after showing the change password dialog
this.userMenuVisible = false;
},
// 退出登录
// Log Out
async handleLogout() {
try {
// 调用 Vuex 的 logout action
// Call the Vuex logout action
await this.logout();
this.$message.success({
message: this.$t("message.success"),
showClose: true,
});
} catch (error) {
console.error("退出登录失败:", error);
console.error("Logout failed:", error);
this.$message.error({
message: this.$t("message.error"),
showClose: true,
});
}
},
// 监听参数字典下拉菜单的可见状态变化
// Monitor visibility changes of the parameter dictionary dropdown
handleParamDropdownVisibleChange(visible) {
this.paramDropdownVisible = visible;
},
// 监听音色克隆下拉菜单的可见状态变化
// Monitor visibility changes of the voice cloning dropdown
handleVoiceCloneDropdownVisibleChange(visible) {
this.voiceCloneDropdownVisible = visible;
},
// 在data中添加一个key用于强制重新渲染组件
// 处理 Cascader 选择变化
// Add a key in data to force component re-render
// Handle Cascader selection change
handleCascaderChange(value) {
if (!value || value.length === 0) {
return;
@ -339,11 +339,11 @@ export default {
const action = value[value.length - 1];
// 处理语言切换
// Handle language switch
if (value.length === 2 && value[0] === "language") {
this.changeLanguage(action);
} else {
// 处理其他操作
// Process other operations
switch (action) {
case "changePassword":
this.showChangePasswordDialog();
@ -354,34 +354,34 @@ export default {
}
}
// 操作完成后立即清空选择
// Clear selection immediately after operation
setTimeout(() => {
this.completeResetCascader();
}, 300);
},
// 切换语言
// Toggle Language
changeLanguage(lang) {
changeLanguage(lang);
this.$message.success({
message: this.$t("message.success"),
showClose: true,
});
// 添加:切换语言后重置用户菜单可见状态
// Added: Reset user menu visibility state after language switch
this.userMenuVisible = false;
},
// 完全重置级联选择器
// Fully reset cascader
completeResetCascader() {
if (this.$refs.userCascader) {
try {
// 尝试所有可能的方法来清空选择
// 1. 尝试使用组件提供的clearValue方法
// Attempt all possible methods to clear selection
// 1. Try using the clearValue method provided by the component
if (this.$refs.userCascader.clearValue) {
this.$refs.userCascader.clearValue();
}
// 2. 直接清空内部属性
// 2. Directly clear internal properties
if (this.$refs.userCascader.$data) {
this.$refs.userCascader.$data.selectedPaths = [];
this.$refs.userCascader.$data.displayLabels = [];
@ -390,7 +390,7 @@ export default {
this.$refs.userCascader.$data.showAllLevels = false;
}
// 3. 操作DOM清除选中状态
// 3. Manipulate DOM to clear selection state
const menuElement = this.$refs.userCascader.$refs.menu;
if (menuElement && menuElement.$el) {
const activeItems = menuElement.$el.querySelectorAll(
@ -406,28 +406,28 @@ export default {
console.log("Cascader values cleared");
} catch (error) {
console.error("清空选择值失败:", error);
console.error("Failed to clear selection values:", error);
}
}
},
// 点击头像触发cascader下拉菜单
// Click avatar to trigger cascader dropdown menu
handleAvatarClick() {
if (this.$refs.userCascader) {
// 切换菜单可见状态
// Toggle menu visibility
this.userMenuVisible = !this.userMenuVisible;
// 菜单收起时清空选择值
// Clear selection values when menu collapses
if (!this.userMenuVisible) {
this.completeResetCascader();
}
// 直接设置菜单的显隐状态
// Directly set menu visibility state
try {
// 尝试使用toggleDropDownVisible方法
// Attempt to use the toggleDropDownVisible method
this.$refs.userCascader.toggleDropDownVisible(this.userMenuVisible);
} catch (error) {
// 如果toggle方法失败,尝试直接设置属性
// If toggle method fails, try setting the property directly
if (this.$refs.userCascader.$refs.menu) {
this.$refs.userCascader.$refs.menu.showMenu(this.userMenuVisible);
} else {
@ -437,7 +437,7 @@ export default {
}
},
// 处理用户菜单可见性变化
// Handle user menu visibility changes
handleUserMenuVisibleChange(visible) {
if (this.menuVisibleTimer) return;
this.menuVisibleTimer = setTimeout(() => {
@ -446,13 +446,13 @@ export default {
this.menuVisibleTimer = null;
}, 100);
// 如果菜单关闭了,也要清空选择值
// If menu is closed, also clear selected values
if (!visible) {
this.completeResetCascader();
}
},
// 使用 mapActions 引入 Vuex 的 logout action
// Use mapActions to import the Vuex logout action
...mapActions(["logout"]),
},
};
@ -560,7 +560,7 @@ export default {
cursor: pointer;
}
/* 导航文本样式 - 支持中英文换行 */
/* Navigation text style - supports line breaks for Chinese and English */
.nav-text {
white-space: normal;
text-align: center;
@ -573,7 +573,7 @@ export default {
gap: 7px;
}
/* 响应式调整 */
/* Responsive adjustment */
@media (max-width: 1200px) {
.header-center {
gap: 14px;
@ -604,7 +604,7 @@ export default {
white-space: nowrap;
}
/* 添加倒三角旋转样式 */
/* Add inverted triangle rotation style */
.rotate-down {
transform: rotate(180deg);
transition: transform 0.3s ease;

View file

@ -181,7 +181,7 @@ export default {
},
handleClose() {
this.saving = false;
// 处理关闭弹窗闪动问题
// Fix flickering issue when closing modal
setTimeout(() => {
this.resetForm();
}, 200)

View file

@ -309,7 +309,7 @@ export default {
}
});
// 兜底:父组件若未在回调内清 saving,3 秒后强制释放加载状态
// Fallback: If the parent component does not clear saving in the callback, force release the loading state after 3 seconds
setTimeout(() => {
this.saving = false;
}, 3000);

View file

@ -15,7 +15,7 @@
<div class="drawer-content">
<el-form label-position="top">
<!-- 音量 -->
<!-- Volume -->
<el-form-item :label="$t('roleConfig.ttsVolume')">
<div class="slider-container">
<el-slider
@ -31,7 +31,7 @@
</div>
</el-form-item>
<!-- 语速 -->
<!-- Speech Rate -->
<el-form-item :label="$t('roleConfig.ttsRate')">
<div class="slider-container">
<el-slider
@ -47,7 +47,7 @@
</div>
</el-form-item>
<!-- 音调 -->
<!-- Pitch -->
<el-form-item :label="$t('roleConfig.ttsPitch')">
<div class="slider-container">
<el-slider
@ -64,7 +64,7 @@
</el-form-item>
</el-form>
<!-- 关联替换词 -->
<!-- Associated replacement words -->
<div>
<h4 class="replacement-label">
{{ $t('roleConfig.replacementWordLabel') }}
@ -149,7 +149,7 @@ export default {
watch: {
visible(newVal) {
if (newVal) {
// 当抽屉打开时,复制当前设置到本地
// Copy current settings to local storage when drawer opens
this.localSettings = { ...this.settings };
this.changedTtsFields = {
volume: false,
@ -166,11 +166,11 @@ export default {
this.$emit('update:visible', false);
},
handleCancel() {
// 取消时不保存,直接关闭
// Close without saving on cancel
this.handleClose();
},
handleSave() {
// 保存设置并关闭
// Save settings and close
const changedTtsFields = Object.keys(this.changedTtsFields)
.filter((field) => this.changedTtsFields[field]);
this.$emit('save', {

View file

@ -53,7 +53,7 @@ const routes = [
return import('../views/retrievePassword.vue')
}
},
// 设备管理页面路由
// Device management page route
{
path: '/device-management',
name: 'DeviceManagement',
@ -61,7 +61,7 @@ const routes = [
return import('../views/DeviceManagement.vue')
}
},
// 添加用户管理路由
// Add user management routes
{
path: '/user-management',
name: 'UserManagement',
@ -168,7 +168,7 @@ const routes = [
return import('../views/ProviderManagement.vue')
}
},
// 添加默认角色管理路由
// Add default role management route
{
path: '/agent-template-management',
name: 'AgentTemplateManagement',
@ -176,7 +176,7 @@ const routes = [
return import('../views/AgentTemplateManagement.vue')
}
},
// 添加模板快速配置路由
// Add template quick config route
{
path: '/template-quick-config',
name: 'TemplateQuickConfig',
@ -184,7 +184,7 @@ const routes = [
return import('../views/TemplateQuickConfig.vue')
}
},
// 功能配置页面路由
// Function config page route
{
path: '/feature-management',
name: 'FeatureManagement',
@ -196,7 +196,7 @@ const routes = [
title: 'Feature Configuration'
}
},
// 替换词管理
// Replacement word management
{
path: '/replacement-word-management',
name: 'ReplacementWordManagement',
@ -208,7 +208,7 @@ const routes = [
title: 'Replacement Word Management'
}
},
// 通讯录管理页面路由
// Contacts management page route
{
path: '/address-book-management',
name: 'AddressBookManagement',
@ -226,31 +226,31 @@ const router = new VueRouter({
routes
})
// 全局处理重复导航,改为刷新页面
// Globally handle duplicate navigation by refreshing the page
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => {
if (err.name === 'NavigationDuplicated') {
// 如果是重复导航,刷新页面
// If duplicate navigation, refresh page
window.location.reload()
} else {
// 其他错误正常抛出
// Throw other errors normally
throw err
}
})
}
// 需要登录才能访问的路由
// Routes requiring login
const protectedRoutes = ['home', 'RoleConfig', 'DeviceManagement', 'UserManagement', 'ModelConfig', 'KnowledgeBaseManagement', 'KnowledgeFileUpload', 'AddressBookManagement']
// 路由守卫
// Route Guard
router.beforeEach((to, from, next) => {
// 检查是否是需要保护的路由
// Check if the route requires protection
if (protectedRoutes.includes(to.name)) {
// 从localStorage获取token
// Get token from localStorage
const token = localStorage.getItem('token')
if (!token) {
// 未登录,跳转到登录页
// Not logged in, redirecting to login page
next({ name: 'login', query: { redirect: to.fullPath } })
return
}

View file

@ -3,7 +3,7 @@
<HeaderBar />
<div class="page-content">
<!-- 左侧设备列表 -->
<!-- Left device list -->
<div class="left-panel">
<div class="left-header">
<h1 class="main-title">{{ $t('addressBookManagement.mainTitle') }}</h1>
@ -20,7 +20,7 @@
/>
</div>
<!-- 智能体列表 -->
<!-- Agent list -->
<el-collapse accordion class="agent-collapse" v-model="expandedAgentId">
<el-collapse-item v-for="agent in filteredAgents" :key="agent.id" :name="agent.id">
<template slot="title">
@ -59,10 +59,10 @@
</el-collapse>
</div>
<!-- 右侧通讯录详情 -->
<!-- Right side contacts details -->
<div class="right-panel">
<div class="device-detail" v-if="selectedDevice">
<!-- 设备信息头部 -->
<!-- Device info header -->
<div class="device-header">
<div class="device-left">
<div class="device-avatar-large">
@ -85,11 +85,11 @@
<i v-if="!isEditingAlias" class="el-icon-edit" @click="handleStartEdit"></i>
</div>
<div class="device-mac">
{{ $t('addressBookManagement.macAddress') }}:
{{ $t('addressBookManagement.macAddress') }}:
<MacAddressMask :macAddress="selectedDevice.deviceId" />
</div>
<div class="device-status">
<span>{{ $t('addressBookManagement.status') }}:</span>
<span>{{ $t('addressBookManagement.status') }}:</span>
<span :class="selectedDevice.online ? 'online' : 'offline'">
<i class="status-dot"></i>
<span>{{ selectedDevice.online ? $t('addressBookManagement.online') : $t('addressBookManagement.offline') }}</span></span>
@ -133,7 +133,7 @@
</div>
</div>
<!-- 权限管理区域 -->
<!-- Permission management area -->
<div class="permission-section">
<div class="section-header">
<div class="section-title">
@ -250,13 +250,13 @@ export default {
this.filteredAgents = this.agentDeviceOptions;
return;
}
// 过滤:匹配智能体名称、设备名称或MAC地址
// Filter: Match agent name, device name, or MAC address
this.filteredAgents = this.agentDeviceOptions.filter(agent => {
// 匹配智能体名称
// Match agent name
if (agent.agentName.toLowerCase().includes(keyword)) {
return true;
}
// 匹配设备名称或MAC地址
// Match device name or MAC address
if (agent.devices && agent.devices.some(device => {
const name = (device.name || '').toLowerCase();
const mac = (device.deviceId || '').toLowerCase();
@ -279,7 +279,7 @@ export default {
id: device.id,
name: (device.alias && device.alias.trim()) ? device.alias : device.id,
alias: device.alias || '',
addressBookAlias: '', // 通讯录别名,初始为空
addressBookAlias: '', // Contact alias, initially empty
type: device.board,
deviceId: device.macAddress,
remarks: device.alias || '',
@ -297,9 +297,9 @@ export default {
const firstDevice = agentList[0] || {};
this.agentDeviceOptions = agentList;
this.filteredAgents = agentList;
// 默认选中第一项
// Select first item by default
this.handleDeviceClick(firstDevice.devices?.[0] || {}, firstDevice);
// 获取设备状态
// Get device status
this.fetchDeviceStatus();
});
} else {
@ -309,7 +309,7 @@ export default {
});
},
fetchDeviceStatus() {
// 为每个智能体获取设备状态
// Get device status for each agent
this.agentDeviceOptions.forEach(agent => {
if (!agent.id) return;
Api.device.getDeviceStatus(agent.id, (statusRes) => {
@ -358,11 +358,11 @@ export default {
this.expandedAgentId = agent.id;
this.selectedAgent = agent;
this.selectedDevice = device;
// 加载所有设备用于权限选择(排除当前设备)
// Load all devices for permission selection (excluding the current device)
this.allDevices = this.agentDeviceOptions
.flatMap(agent => agent.devices || [])
.filter(d => d.id !== device.id);
// 加载通讯录权限
// Load contacts permissions
this.loadAddressBookPermissions(device.deviceId);
},
loadAddressBookPermissions(macAddress) {
@ -391,7 +391,7 @@ export default {
permission
])
);
// 设置已选择的权限
// Set selected permissions
const permittedTargetMacs = new Set(
permissions
.filter(p => p.hasPermission)
@ -400,9 +400,9 @@ export default {
this.selectedPermissions = this.allDevices
.filter(device => permittedTargetMacs.has((device.deviceId || '').toLowerCase()))
.map(device => device.deviceId);
// 保存初始权限状态(用于对比变更)
// Save initial permission state (for change comparison)
this.originalPermissions = [...this.selectedPermissions];
// 更新设备的通讯录别名
// Update device contact alias
this.allDevices.forEach(device => {
const addrBook = permissionsByTargetMac.get((device.deviceId || '').toLowerCase());
if (addrBook) {
@ -547,7 +547,7 @@ export default {
Api.agent.updateAgentConfig(this.selectedAgent.id, { agentName: newName }, ({ data }) => {
if (data.code === 0) {
this.selectedAgent.agentName = newName;
// 更新列表中的智能体名称
// Update agent name in list
const agentInList = this.agentDeviceOptions.find(a => a.id === this.selectedAgent.id);
if (agentInList) {
agentInList.agentName = newName;
@ -586,7 +586,7 @@ export default {
return formatCreateDate(device.createDateTimestamp, device.createDate);
},
getDeviceAvatar(deviceId) {
// 根据 deviceId 计算 MD5,选择对应的头像
// Compute MD5 based on deviceId to select the corresponding avatar
const avatars = [
require('@/assets/device-avatars/xiaozhi-logo1.png'),
require('@/assets/device-avatars/xiaozhi-logo2.png'),
@ -605,7 +605,7 @@ export default {
require('@/assets/device-avatars/xiaozhi-logo15.png'),
require('@/assets/device-avatars/xiaozhi-logo16.png')
];
// 简单的哈希算法,根据 deviceId 分配头像
// Simple hash algorithm to assign avatars based on deviceId
let hash = 0;
for (let i = 0; i < deviceId.length; i++) {
hash = ((hash << 5) - hash) + deviceId.charCodeAt(i);

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