diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 000000000..135cfbd65 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,66 @@ +name: Tests + +on: + push: + branches: [main] + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + python: + name: Python (xiaozhi-server) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.10' + cache: 'pip' + cache-dependency-path: 'main/xiaozhi-server/requirements.txt' + - name: Install dependencies + working-directory: main/xiaozhi-server + run: | + pip install -r requirements.txt + pip install pytest pytest-asyncio freezegun + - name: Run smoke test + working-directory: main/xiaozhi-server + run: | + if [ -f tests/test_smoke.py ]; then + pytest tests/test_smoke.py -x -q + else + echo "::warning::Slice 2 not done yet — tests/test_smoke.py missing" + exit 0 + fi + + java: + name: Java (manager-api) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: '21' + cache: 'maven' + - name: Run tests + working-directory: main/manager-api + run: mvn -B -q test -DfailIfNoTests=false + + web: + name: Vue (manager-web) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + cache-dependency-path: main/manager-web/package-lock.json + - name: Run tests + working-directory: main/manager-web + run: | + npm ci --no-audit --no-fund + npm run test:unit diff --git a/.gitignore b/.gitignore index 8b393385c..1c0c024ba 100644 --- a/.gitignore +++ b/.gitignore @@ -110,12 +110,17 @@ celerybeat.pid # Environments .env .venv +/.venv-*/ env/ venv/ ENV/ env.bak/ venv.bak/ +# Repository-local runtimes and package-manager caches +/.runtime/ +/main/manager-web/.npm-cache/ + # Spyder project settings .spyderproject .spyproject diff --git a/Makefile b/Makefile new file mode 100644 index 000000000..3362dcb74 --- /dev/null +++ b/Makefile @@ -0,0 +1,21 @@ +.PHONY: test test-fast test-python test-java test-web help + +help: + @echo "make test-fast - run all fast unit tests (default)" + @echo "make test - alias for test-fast" + @echo "make test-python - pytest in main/xiaozhi-server" + @echo "make test-java - mvn test in main/manager-api" + @echo "make test-web - npm run test:unit in main/manager-web" + +test: test-fast + +test-fast: test-python test-java test-web + +test-python: + cd main/xiaozhi-server && python -m pytest -x -q + +test-java: + cd main/manager-api && mvn -B -q test -DfailIfNoTests=false + +test-web: + cd main/manager-web && npm ci --no-audit --no-fund && npm test diff --git a/docs/web-search-integration.md b/docs/web-search-integration.md index 25dd546a1..cb694e912 100644 --- a/docs/web-search-integration.md +++ b/docs/web-search-integration.md @@ -2,13 +2,14 @@ ## 功能简介 -联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持两个搜索源:秘塔(Metaso)和Tavily,用户可根据需要选择其中一个。 +联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持三个搜索源:秘塔(Metaso)、Tavily和Serply,用户可根据需要选择其中一个。 ## API Key申请指南 -目前我们适配了`秘塔搜索`和`Tavily搜索`。 +目前我们适配了`秘塔搜索`、`Tavily搜索`和`Serply搜索`。 - Tavily搜索:每个月1000次免费额度。 - 秘塔搜索:拥有较为优质的国内数据源。 +- Serply搜索:返回谷歌搜索结果,注册赠送2500次免费额度,额度用完后需要付费。 ## API Key申请指南 @@ -24,6 +25,13 @@ - 在控制台中创建API Key - 复制生成的API Key(以 `tvly-` 为前缀),这是配置所需的关键信息 +### 方式三:使用Serply搜索 + +- 访问 [Serply](https://serply.io),注册并登录账号 +- 在控制台中创建API Key +- 复制生成的API Key,这是配置所需的关键信息 +- 接口说明见 [Serply文档](https://serply.io/docs) + ## 配置方式 ### 方式1. 使用智控台部署(推荐) @@ -32,14 +40,14 @@ - 进入"配置角色"页面,选择要配置的智能体 - 点击"编辑功能"按钮,在右侧参数配置区域找到"联网搜索"插件 - 勾选"联网搜索" -- 填入搜索源(`metaso`或`tavily`),并将对应的`API Key`填入配置项 +- 填入搜索源(`metaso`、`tavily`或`serply`),并将对应的`API Key`填入配置项 - 保存配置,再保存智能体配置 ### 方式2. 单模块xiaozhi-server部署 在 `data/.config.yaml` 中配置: -- 将搜索源填入 `provider`,可选值为 `metaso` 或 `tavily` +- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily` 或 `serply` - 将申请到的API Key填入 `api_key` ```yaml diff --git a/main/manager-api/pom.xml b/main/manager-api/pom.xml index 7bb9016ca..0b0e90a9e 100644 --- a/main/manager-api/pom.xml +++ b/main/manager-api/pom.xml @@ -20,15 +20,15 @@ 21 5.10.1 1.2.20 - 3.5.5 - 5.8.24 - 1.19.1 + 3.5.17 + 5.8.46 + 1.22.2 4.6.0 2.8.8 - 3.18.0 + 3.20.0 2.0.2 1.6.2 - 33.0.0-jre + 33.6.0-jre 4.20.0 8.31.1 @@ -174,13 +174,13 @@ com.baomidou - mybatis-plus-boot-starter + mybatis-plus-spring-boot3-starter ${mybatisplus.version} - org.mybatis - mybatis-spring - 3.0.3 + com.baomidou + mybatis-plus-jsqlparser-4.9 + ${mybatisplus.version} cn.hutool @@ -295,6 +295,16 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + full + + -Xlint:deprecation,unchecked + + + org.apache.maven.plugins maven-surefire-plugin diff --git a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java index 55965e476..664cb9b48 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java +++ b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java @@ -324,7 +324,7 @@ public interface Constant { /** * 版本号 */ - public static final String VERSION = "0.9.4"; + public static final String VERSION = "0.9.7"; /** * 无效固件URL diff --git a/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataFilterInterceptor.java b/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataFilterInterceptor.java index b1bae90e5..7a34fa80f 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataFilterInterceptor.java +++ b/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataFilterInterceptor.java @@ -67,7 +67,7 @@ public class DataFilterInterceptor implements InnerInterceptor { private String getSelect(String buildSql, DataScope scope) { try { Select select = (Select) CCJSqlParserUtil.parse(buildSql); - PlainSelect plainSelect = (PlainSelect) select.getSelectBody(); + PlainSelect plainSelect = select.getPlainSelect(); Expression expression = plainSelect.getWhere(); if (expression == null) { @@ -82,4 +82,4 @@ public class DataFilterInterceptor implements InnerInterceptor { return buildSql; } } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/service/impl/BaseServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/common/service/impl/BaseServiceImpl.java index 33d0f5d35..4dec94356 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/service/impl/BaseServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/common/service/impl/BaseServiceImpl.java @@ -5,7 +5,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; -import java.util.function.BiConsumer; +import java.util.function.BiFunction; import org.apache.ibatis.binding.MapperMethod; import org.apache.ibatis.logging.Log; @@ -81,8 +81,8 @@ public abstract class BaseServiceImpl, T> implements Bas // Process sort fields if (orderField instanceof String) { orderFields.add((String) orderField); - } else if (orderField instanceof List) { - orderFields.addAll((List) orderField); + } else if (orderField instanceof List fields) { + fields.forEach(field -> orderFields.add(String.class.cast(field))); } // Sort if there are sort fields @@ -142,11 +142,12 @@ public abstract class BaseServiceImpl, T> implements Bas return SqlHelper.retBool(result); } - protected Class currentMapperClass() { - return (Class) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 0); + protected Class currentMapperClass() { + return ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 0); } @Override + @SuppressWarnings("unchecked") public Class currentModelClass() { return (Class) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 1); } @@ -181,8 +182,9 @@ public abstract class BaseServiceImpl, T> implements Bas * Execute batch operations */ @SuppressWarnings("deprecation") - protected boolean executeBatch(Collection list, int batchSize, BiConsumer consumer) { - return SqlHelper.executeBatch(this.currentModelClass(), this.log, list, batchSize, consumer); + protected boolean executeBatch(Collection list, int batchSize, BiFunction operation) { + return SqlHelper.executeBatch(SqlHelper.sqlSessionFactory(this.currentModelClass()), this.log, list, batchSize, + operation); } @Override @@ -209,7 +211,7 @@ public abstract class BaseServiceImpl, T> implements Bas return executeBatch(entityList, batchSize, (sqlSession, entity) -> { MapperMethod.ParamMap param = new MapperMethod.ParamMap<>(); param.put(Constants.ENTITY, entity); - sqlSession.update(sqlStatement, param); + return sqlSession.update(sqlStatement, param); }); } @@ -225,6 +227,6 @@ public abstract class BaseServiceImpl, T> implements Bas @Override public boolean deleteBatchIds(Collection idList) { - return SqlHelper.retBool(baseDao.deleteBatchIds(idList)); + return SqlHelper.retBool(baseDao.deleteByIds(idList)); } } diff --git a/main/manager-api/src/main/java/xiaozhi/common/service/impl/CrudServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/common/service/impl/CrudServiceImpl.java index 3b9d0fe97..d6e37d13d 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/service/impl/CrudServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/common/service/impl/CrudServiceImpl.java @@ -24,6 +24,7 @@ import xiaozhi.common.utils.ConvertUtils; public abstract class CrudServiceImpl, T, D> extends BaseServiceImpl implements CrudService { + @SuppressWarnings("unchecked") protected Class currentDtoClass() { return (Class) ReflectionKit.getSuperClassGenericType(getClass(), CrudServiceImpl.class, 2); } @@ -70,6 +71,6 @@ public abstract class CrudServiceImpl, T, D> extends Bas @Override public void delete(Serializable[] ids) { - baseDao.deleteBatchIds(Arrays.asList(ids)); + baseDao.deleteByIds(Arrays.asList(ids)); } } diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/HashEncryptionUtil.java b/main/manager-api/src/main/java/xiaozhi/common/utils/HashEncryptionUtil.java deleted file mode 100644 index dd0c26305..000000000 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/HashEncryptionUtil.java +++ /dev/null @@ -1,52 +0,0 @@ -package xiaozhi.common.utils; - -import lombok.extern.slf4j.Slf4j; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -/** - * Hash encryption algorithm utility class - * @author zjy - */ -@Slf4j -public class HashEncryptionUtil { - /** - * Encrypt using md5 - * @param context Content to be encrypted - * @return Hash value - */ - public static String Md5hexDigest(String context){ - return hexDigest(context,"MD5"); - } - - /** - * Encrypt using specified hash algorithm - * @param context Content to be encrypted - * @param algorithm Hash algorithm - * @return Hash value - */ - public static String hexDigest(String context,String algorithm ){ - // Get MD5 algorithm instance - MessageDigest md = null; - try { - md = MessageDigest.getInstance(algorithm); - } catch (NoSuchAlgorithmException e) { - log.error("Encryption failed algorithm: {}",algorithm); - throw new RuntimeException("Encryption failed, system does not support "+ algorithm +" hash algorithm"); - } - // Calculate MD5 value of agent id - byte[] messageDigest = md.digest(context.getBytes()); - // Convert byte array to hexadecimal string - StringBuilder hexString = new StringBuilder(); - for (byte b : messageDigest) { - String hex = Integer.toHexString(0xFF & b); - if (hex.length() == 1) { - hexString.append('0'); - } - hexString.append(hex); - } - return hexString.toString(); - } - -} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java index 21d1bf211..cf0ef663b 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java @@ -1,7 +1,9 @@ package xiaozhi.common.utils; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -16,6 +18,10 @@ import cn.hutool.core.util.StrUtil; */ public class JsonUtils { private static final ObjectMapper objectMapper = new ObjectMapper(); + private static final TypeReference> STRING_OBJECT_MAP = new TypeReference<>() { + }; + private static final TypeReference>> STRING_OBJECT_MAP_LIST = new TypeReference<>() { + }; public static String toJsonString(Object object) { try { @@ -67,4 +73,59 @@ public class JsonUtils { } } + public static Map parseMap(String text) { + if (StrUtil.isEmpty(text)) { + return null; + } + return parseObject(text, STRING_OBJECT_MAP); + } + + public static List> parseMapList(String text) { + if (StrUtil.isEmpty(text)) { + return null; + } + return parseObject(text, STRING_OBJECT_MAP_LIST); + } + + public static Map toStringObjectMap(Object value) { + if (value == null) { + return null; + } + if (!(value instanceof Map map)) { + throw new ClassCastException("Expected Map but got " + value.getClass().getName()); + } + + Map result = new LinkedHashMap<>(map.size()); + for (Map.Entry entry : map.entrySet()) { + result.put(String.class.cast(entry.getKey()), entry.getValue()); + } + return result; + } + + public static List> toStringObjectMapList(Object value) { + if (value == null) { + return null; + } + + List list = List.class.cast(value); + List> result = new ArrayList<>(list.size()); + for (Object item : list) { + result.add(toStringObjectMap(item)); + } + return result; + } + + public static List toList(Object value, Class elementType) { + if (value == null) { + return null; + } + + List list = List.class.cast(value); + List result = new ArrayList<>(list.size()); + for (Object item : list) { + result.add(elementType.cast(item)); + } + return result; + } + } diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/SensitiveDataUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/SensitiveDataUtils.java index 5b5f6c60e..bfcb08135 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/SensitiveDataUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/SensitiveDataUtils.java @@ -75,11 +75,11 @@ public class SensitiveDataUtils { Object value = jsonObject.get(key); if (SENSITIVE_FIELDS.contains(key.toLowerCase()) && value instanceof String) { - result.put(key, maskMiddle((String) value)); + result.set(key, maskMiddle((String) value)); } else if (value instanceof JSONObject) { - result.put(key, maskSensitiveFields((JSONObject) value)); + result.set(key, maskSensitiveFields((JSONObject) value)); } else { - result.put(key, value); + result.set(key, value); } } diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/ToolUtil.java b/main/manager-api/src/main/java/xiaozhi/common/utils/ToolUtil.java deleted file mode 100644 index c0e278662..000000000 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/ToolUtil.java +++ /dev/null @@ -1,89 +0,0 @@ -package xiaozhi.common.utils; - -import cn.hutool.core.util.ReUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * General utility helpers. - */ -public class ToolUtil { - private static final Logger logger = LoggerFactory.getLogger(ToolUtil.class); - - /** - * Whether an object is not empty. - */ - public static boolean isNotEmpty(Object o) { - return !isEmpty(o); - } - - /** - * Whether an object is empty. - */ - public static boolean isEmpty(Object o) { - if (o == null) { - return true; - } - if (o instanceof String) { - if (o.toString().trim().equals("")) { - return true; - } - } else if (o instanceof List) { - if (((List) o).size() == 0) { - return true; - } - } else if (o instanceof Map) { - if (((Map) o).size() == 0) { - return true; - } - } else if (o instanceof Set) { - if (((Set) o).size() == 0) { - return true; - } - } else if (o instanceof Object[]) { - if (((Object[]) o).length == 0) { - return true; - } - } else if (o instanceof int[]) { - if (((int[]) o).length == 0) { - return true; - } - } else if (o instanceof long[]) { - if (((long[]) o).length == 0) { - return true; - } - } - return false; - } - - /** - * Whether any object in the group is empty. - */ - public static boolean isOneEmpty(Object... os) { - for (Object o : os) { - if (isEmpty(o)) { - return true; - } - } - return false; - } - - /** - * Whether all objects in the group are empty. - */ - public static boolean isAllEmpty(Object... os) { - for (Object o : os) { - if (!isEmpty(o)) { - return false; - } - } - return true; - } -} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/AgentSnapshotField.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/AgentSnapshotField.java new file mode 100644 index 000000000..166b76fee --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/AgentSnapshotField.java @@ -0,0 +1,103 @@ +package xiaozhi.modules.agent.Enums; + +import java.util.Arrays; +import java.util.List; +import java.util.function.BiConsumer; +import java.util.function.Function; + +import lombok.Getter; +import xiaozhi.modules.agent.dto.AgentSnapshotDataDTO; +import xiaozhi.modules.agent.dto.AgentUpdateDTO; +import xiaozhi.modules.agent.entity.AgentEntity; + +@Getter +public enum AgentSnapshotField { + AGENT_CODE("agentCode", AgentSnapshotDataDTO::getAgentCode, AgentUpdateDTO::getAgentCode, + (agent, data) -> agent.setAgentCode(data.getAgentCode())), + AGENT_NAME("agentName", AgentSnapshotDataDTO::getAgentName, AgentUpdateDTO::getAgentName, + (agent, data) -> agent.setAgentName(data.getAgentName())), + ASR_MODEL_ID("asrModelId", AgentSnapshotDataDTO::getAsrModelId, AgentUpdateDTO::getAsrModelId, + (agent, data) -> agent.setAsrModelId(data.getAsrModelId())), + VAD_MODEL_ID("vadModelId", AgentSnapshotDataDTO::getVadModelId, AgentUpdateDTO::getVadModelId, + (agent, data) -> agent.setVadModelId(data.getVadModelId())), + LLM_MODEL_ID("llmModelId", AgentSnapshotDataDTO::getLlmModelId, AgentUpdateDTO::getLlmModelId, + (agent, data) -> agent.setLlmModelId(data.getLlmModelId())), + SLM_MODEL_ID("slmModelId", AgentSnapshotDataDTO::getSlmModelId, AgentUpdateDTO::getSlmModelId, + (agent, data) -> agent.setSlmModelId(data.getSlmModelId())), + VLLM_MODEL_ID("vllmModelId", AgentSnapshotDataDTO::getVllmModelId, AgentUpdateDTO::getVllmModelId, + (agent, data) -> agent.setVllmModelId(data.getVllmModelId())), + TTS_MODEL_ID("ttsModelId", AgentSnapshotDataDTO::getTtsModelId, AgentUpdateDTO::getTtsModelId, + (agent, data) -> agent.setTtsModelId(data.getTtsModelId())), + TTS_VOICE_ID("ttsVoiceId", AgentSnapshotDataDTO::getTtsVoiceId, AgentUpdateDTO::getTtsVoiceId, + (agent, data) -> agent.setTtsVoiceId(data.getTtsVoiceId())), + TTS_LANGUAGE("ttsLanguage", AgentSnapshotDataDTO::getTtsLanguage, AgentUpdateDTO::getTtsLanguage, + (agent, data) -> agent.setTtsLanguage(data.getTtsLanguage())), + TTS_VOLUME("ttsVolume", AgentSnapshotDataDTO::getTtsVolume, AgentUpdateDTO::getTtsVolume, + (agent, data) -> agent.setTtsVolume(data.getTtsVolume())), + TTS_RATE("ttsRate", AgentSnapshotDataDTO::getTtsRate, AgentUpdateDTO::getTtsRate, + (agent, data) -> agent.setTtsRate(data.getTtsRate())), + TTS_PITCH("ttsPitch", AgentSnapshotDataDTO::getTtsPitch, AgentUpdateDTO::getTtsPitch, + (agent, data) -> agent.setTtsPitch(data.getTtsPitch())), + MEM_MODEL_ID("memModelId", AgentSnapshotDataDTO::getMemModelId, AgentUpdateDTO::getMemModelId, + (agent, data) -> agent.setMemModelId(data.getMemModelId())), + INTENT_MODEL_ID("intentModelId", AgentSnapshotDataDTO::getIntentModelId, AgentUpdateDTO::getIntentModelId, + (agent, data) -> agent.setIntentModelId(data.getIntentModelId())), + CHAT_HISTORY_CONF("chatHistoryConf", AgentSnapshotDataDTO::getChatHistoryConf, AgentUpdateDTO::getChatHistoryConf, + (agent, data) -> agent.setChatHistoryConf(data.getChatHistoryConf())), + SYSTEM_PROMPT("systemPrompt", AgentSnapshotDataDTO::getSystemPrompt, AgentUpdateDTO::getSystemPrompt, + (agent, data) -> agent.setSystemPrompt(data.getSystemPrompt())), + SUMMARY_MEMORY("summaryMemory", AgentSnapshotDataDTO::getSummaryMemory, AgentUpdateDTO::getSummaryMemory, + (agent, data) -> agent.setSummaryMemory(data.getSummaryMemory())), + LANG_CODE("langCode", AgentSnapshotDataDTO::getLangCode, AgentUpdateDTO::getLangCode, + (agent, data) -> agent.setLangCode(data.getLangCode())), + LANGUAGE("language", AgentSnapshotDataDTO::getLanguage, AgentUpdateDTO::getLanguage, + (agent, data) -> agent.setLanguage(data.getLanguage())), + SORT("sort", AgentSnapshotDataDTO::getSort, AgentUpdateDTO::getSort, + (agent, data) -> agent.setSort(data.getSort())), + FUNCTIONS("functions", AgentSnapshotDataDTO::getFunctions, AgentUpdateDTO::getFunctions, null), + CONTEXT_PROVIDERS("contextProviders", AgentSnapshotDataDTO::getContextProviders, + AgentUpdateDTO::getContextProviders, null), + CORRECT_WORD_FILE_IDS("correctWordFileIds", AgentSnapshotDataDTO::getCorrectWordFileIds, + AgentUpdateDTO::getCorrectWordFileIds, null), + TAG_NAMES("tagNames", AgentSnapshotDataDTO::getTagNames, AgentUpdateDTO::getTagNames, null); + + private final String fieldName; + private final Function snapshotGetter; + private final Function updateGetter; + private final BiConsumer restoreApplier; + + AgentSnapshotField(String fieldName, Function snapshotGetter, + Function updateGetter, + BiConsumer restoreApplier) { + this.fieldName = fieldName; + this.snapshotGetter = snapshotGetter; + this.updateGetter = updateGetter; + this.restoreApplier = restoreApplier; + } + + public static List names() { + return Arrays.stream(values()).map(AgentSnapshotField::getFieldName).toList(); + } + + public static String canonicalName(String fieldName) { + return "tags".equals(fieldName) ? TAG_NAMES.getFieldName() : fieldName; + } + + public Object snapshotValue(AgentSnapshotDataDTO data) { + return data == null ? null : snapshotGetter.apply(data); + } + + public Object updateValue(AgentUpdateDTO data) { + return data == null ? null : updateGetter.apply(data); + } + + public boolean isRestorableAgentField() { + return restoreApplier != null; + } + + public void applyTo(AgentEntity agent, AgentSnapshotDataDTO data) { + if (restoreApplier != null) { + restoreApplier.accept(agent, data); + } + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java index 5e2435e9e..0961fe7b7 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java @@ -28,10 +28,13 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.AllArgsConstructor; import xiaozhi.common.constant.Constant; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; import xiaozhi.common.page.PageData; import xiaozhi.common.redis.RedisKeys; import xiaozhi.common.redis.RedisUtils; import xiaozhi.common.user.UserDetail; +import xiaozhi.common.utils.JsonUtils; import xiaozhi.common.utils.Result; import xiaozhi.common.utils.ResultUtils; import xiaozhi.modules.agent.dto.AgentChatHistoryDTO; @@ -48,15 +51,10 @@ import xiaozhi.modules.agent.service.AgentTagService; import xiaozhi.modules.agent.service.AgentChatAudioService; import xiaozhi.modules.agent.service.AgentChatHistoryService; import xiaozhi.modules.agent.service.AgentChatSummaryService; -import xiaozhi.modules.agent.service.AgentContextProviderService; -import xiaozhi.modules.agent.service.AgentPluginMappingService; import xiaozhi.modules.agent.service.AgentService; import xiaozhi.modules.agent.service.AgentTemplateService; -import xiaozhi.modules.correctword.service.CorrectWordFileService; import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO; import xiaozhi.modules.agent.vo.AgentInfoVO; -import xiaozhi.modules.device.entity.DeviceEntity; -import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.security.user.SecurityUser; @Tag(name = "智能体管理") @@ -64,17 +62,39 @@ import xiaozhi.modules.security.user.SecurityUser; @RestController @RequestMapping("/agent") public class AgentController { + private static final long AUDIO_PLAY_TOKEN_EXPIRE_SECONDS = 300L; + private final AgentService agentService; private final AgentTemplateService agentTemplateService; - private final DeviceService deviceService; private final AgentChatHistoryService agentChatHistoryService; private final AgentChatAudioService agentChatAudioService; - private final AgentPluginMappingService agentPluginMappingService; - private final AgentContextProviderService agentContextProviderService; private final AgentChatSummaryService agentChatSummaryService; private final RedisUtils redisUtils; private final AgentTagService agentTagService; - private final CorrectWordFileService correctWordFileService; + + private void requireAgentPermission(String agentId) { + if (!agentService.checkAgentPermission(agentId, SecurityUser.getUserId())) { + throw new RenException(ErrorCode.NO_PERMISSION); + } + } + + private String requireSessionAgent(String sessionId) { + String agentId = agentChatHistoryService.getAgentIdBySessionId(sessionId); + if (StringUtils.isBlank(agentId)) { + throw new RenException(ErrorCode.AGENT_NOT_FOUND); + } + agentService.getAgentById(agentId); + return agentId; + } + + private String requireAudioPermission(String audioId) { + String agentId = agentChatHistoryService.getAgentIdByAudioId(audioId); + if (StringUtils.isBlank(agentId)) { + throw new RenException(ErrorCode.NO_PERMISSION); + } + requireAgentPermission(agentId); + return agentId; + } @GetMapping("/list") @Operation(summary = "获取用户智能体列表") @@ -106,7 +126,7 @@ public class AgentController { @Operation(summary = "获取智能体详情") @RequiresPermissions("sys:role:normal") public Result getAgentById(@PathVariable("id") String id) { - AgentInfoVO agent = agentService.getAgentById(id); + AgentInfoVO agent = agentService.getAgentById(id, SecurityUser.getUserId()); return ResultUtils.success(agent); } @@ -120,20 +140,16 @@ public class AgentController { @PutMapping("/saveMemory/{macAddress}") @Operation(summary = "根据设备id更新智能体") + @RequiresPermissions("sys:role:normal") public Result updateByDeviceId(@PathVariable String macAddress, @RequestBody @Valid AgentMemoryDTO dto) { - DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress); - if (device == null) { - return new Result<>(); - } - AgentUpdateDTO agentUpdateDTO = new AgentUpdateDTO(); - agentUpdateDTO.setSummaryMemory(dto.getSummaryMemory()); - agentService.updateAgentById(device.getAgentId(), agentUpdateDTO); - return new Result<>(); + agentService.updateAgentMemoryByDeviceMacAddress(macAddress, dto, SecurityUser.getUserId()); + return new Result().ok(null); } @PostMapping("/chat-summary/{sessionId}/save") @Operation(summary = "根据会话ID生成聊天记录总结并保存(异步执行)") public Result generateAndSaveChatSummary(@PathVariable String sessionId) { + requireSessionAgent(sessionId); try { // 异步执行总结生成任务,立即返回成功响应 new Thread(() -> { @@ -155,6 +171,7 @@ public class AgentController { @PostMapping("/chat-title/{sessionId}/generate") @Operation(summary = "根据会话ID生成聊天标题") public Result generateAndSaveChatTitle(@PathVariable String sessionId) { + requireSessionAgent(sessionId); agentChatSummaryService.generateAndSaveChatTitle(sessionId); return new Result().ok(null); } @@ -163,7 +180,7 @@ public class AgentController { @Operation(summary = "更新智能体") @RequiresPermissions("sys:role:normal") public Result update(@PathVariable String id, @RequestBody @Valid AgentUpdateDTO dto) { - agentService.updateAgentById(id, dto); + agentService.updateAgentById(id, dto, SecurityUser.getUserId()); return new Result<>(); } @@ -171,18 +188,7 @@ public class AgentController { @Operation(summary = "删除智能体") @RequiresPermissions("sys:role:normal") public Result delete(@PathVariable String id) { - // 先删除关联的设备 - deviceService.deleteByAgentId(id); - // 删除关联的聊天记录 - agentChatHistoryService.deleteByAgentId(id, true, true); - // 删除关联的插件 - agentPluginMappingService.deleteByAgentId(id); - // 删除关联的上下文源配置 - agentContextProviderService.deleteByAgentId(id); - // 删除关联的替换词文件关联记录 - correctWordFileService.deleteMappingsByAgentId(id); - // 再删除智能体 - agentService.deleteById(id); + agentService.deleteAgentById(id, SecurityUser.getUserId()); return new Result<>(); } @@ -205,6 +211,7 @@ public class AgentController { public Result> getAgentSessions( @PathVariable("id") String id, @Parameter(hidden = true) @RequestParam Map params) { + requireAgentPermission(id); params.put("agentId", id); PageData page = agentChatHistoryService.getSessionListByAgentId(params); return new Result>().ok(page); @@ -252,6 +259,7 @@ public class AgentController { @RequiresPermissions("sys:role:normal") public Result getContentByAudioId( @PathVariable("id") String id) { + requireAudioPermission(id); // 查询聊天记录 String data = agentChatHistoryService.getContentByAudioId(id); return new Result().ok(data); @@ -261,12 +269,13 @@ public class AgentController { @Operation(summary = "获取音频下载ID") @RequiresPermissions("sys:role:normal") public Result getAudioId(@PathVariable("audioId") String audioId) { + requireAudioPermission(audioId); byte[] audioData = agentChatAudioService.getAudio(audioId); if (audioData == null) { return new Result().error("音频不存在"); } String uuid = UUID.randomUUID().toString(); - redisUtils.set(RedisKeys.getAgentAudioIdKey(uuid), audioId); + redisUtils.set(RedisKeys.getAgentAudioIdKey(uuid), audioId, AUDIO_PLAY_TOKEN_EXPIRE_SECONDS); return new Result().ok(uuid); } @@ -322,6 +331,7 @@ public class AgentController { @Operation(summary = "获取智能体的标签") @RequiresPermissions("sys:role:normal") public Result> getAgentTags(@PathVariable String id) { + requireAgentPermission(id); List tags = agentTagService.getTagsByAgentId(id); return new Result>().ok(tags); } @@ -330,10 +340,14 @@ public class AgentController { @Operation(summary = "保存智能体的标签") @RequiresPermissions("sys:role:normal") public Result saveAgentTags(@PathVariable String id, @RequestBody Map params) { - List tagIds = (List) params.get("tagIds"); - List tagNames = (List) params.get("tagNames"); - agentTagService.saveAgentTags(id, tagIds, tagNames); + requireAgentPermission(id); + List tagIds = JsonUtils.toList(params.get("tagIds"), String.class); + List tagNames = JsonUtils.toList(params.get("tagNames"), String.class); + AgentUpdateDTO dto = new AgentUpdateDTO(); + dto.setTagIds(tagIds); + dto.setTagNames(tagNames); + agentService.updateAgentById(id, dto); return new Result().ok(null); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentSnapshotController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentSnapshotController.java new file mode 100644 index 000000000..de4b57b29 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentSnapshotController.java @@ -0,0 +1,79 @@ +package xiaozhi.modules.agent.controller; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springdoc.core.annotations.ParameterObject; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.AllArgsConstructor; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.page.PageData; +import xiaozhi.common.user.UserDetail; +import xiaozhi.common.utils.Result; +import xiaozhi.modules.agent.dto.AgentSnapshotPageDTO; +import xiaozhi.modules.agent.dto.AgentSnapshotRestoreDTO; +import xiaozhi.modules.agent.service.AgentService; +import xiaozhi.modules.agent.service.AgentSnapshotService; +import xiaozhi.modules.agent.vo.AgentSnapshotVO; +import xiaozhi.modules.security.user.SecurityUser; + +@Tag(name = "智能体快照") +@AllArgsConstructor +@RestController +@RequestMapping("/agent/{agentId}/snapshots") +public class AgentSnapshotController { + private final AgentSnapshotService agentSnapshotService; + private final AgentService agentService; + + @GetMapping + @Operation(summary = "获取智能体快照列表") + @RequiresPermissions("sys:role:normal") + public Result> page( + @PathVariable String agentId, + @ParameterObject AgentSnapshotPageDTO params) { + checkPermission(agentId); + return new Result>().ok(agentSnapshotService.page(agentId, params)); + } + + @GetMapping("/{snapshotId}") + @Operation(summary = "获取智能体快照详情") + @RequiresPermissions("sys:role:normal") + public Result getSnapshot(@PathVariable String agentId, @PathVariable String snapshotId) { + checkPermission(agentId); + return new Result().ok(agentSnapshotService.getSnapshot(agentId, snapshotId)); + } + + @PostMapping("/{snapshotId}/restore") + @Operation(summary = "恢复智能体快照") + @RequiresPermissions("sys:role:normal") + public Result restore(@PathVariable String agentId, @PathVariable String snapshotId, + @RequestBody @Valid AgentSnapshotRestoreDTO request) { + checkPermission(agentId); + agentSnapshotService.restoreSnapshot(agentId, snapshotId, request.getCurrentStateToken()); + return new Result<>(); + } + + @DeleteMapping("/{snapshotId}") + @Operation(summary = "删除智能体历史快照") + @RequiresPermissions("sys:role:normal") + public Result deleteSnapshot(@PathVariable String agentId, @PathVariable String snapshotId) { + checkPermission(agentId); + agentSnapshotService.deleteSnapshot(agentId, snapshotId); + return new Result<>(); + } + + private void checkPermission(String agentId) { + UserDetail user = SecurityUser.getUser(); + if (user == null || !agentService.checkAgentPermission(agentId, user.getId())) { + throw new RenException("没有权限访问该智能体快照"); + } + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java index 98a80b761..82d7ef29a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java @@ -36,4 +36,20 @@ public interface AgentDao extends BaseDao { * @param agentId Agent ID */ AgentInfoVO selectAgentInfoById(@Param("agentId") String agentId); + + /** + * 锁定智能体主记录,用于串行化同一智能体的配置写入 + * + * @param agentId 智能体ID + */ + AgentEntity selectByIdForUpdate(@Param("agentId") String agentId); + + /** + * 精确写入快照覆盖的智能体字段,包括目标快照中的 null 值。 + * 不更新所属用户、创建信息等不属于快照的字段。 + * + * @param agent 已应用目标快照的智能体 + * @return 受影响行数 + */ + int updateSnapshotFields(@Param("agent") AgentEntity agent); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentSnapshotDao.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentSnapshotDao.java new file mode 100644 index 000000000..ec8f39e8f --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentSnapshotDao.java @@ -0,0 +1,29 @@ +package xiaozhi.modules.agent.dao; + +import java.util.List; + +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import xiaozhi.common.dao.BaseDao; +import xiaozhi.modules.agent.entity.AgentSnapshotEntity; + +@Mapper +public interface AgentSnapshotDao extends BaseDao { + Integer selectMaxVersionNo(@Param("agentId") String agentId); + + AgentSnapshotEntity selectLatestSnapshot(@Param("agentId") String agentId); + + AgentSnapshotEntity selectNextSnapshot(@Param("agentId") String agentId, @Param("versionNo") Integer versionNo); + + int insertWithNextVersion(@Param("snapshot") AgentSnapshotEntity snapshot); + + int deleteOlderThanKeepLimit(@Param("agentId") String agentId, @Param("keepLimit") int keepLimit); + + List selectLegacyRedactionBatch(@Param("afterId") String afterId, + @Param("limit") int limit, + @Param("targetRedactionVersion") int targetRedactionVersion); + + int updateRedactedSnapshots(@Param("snapshots") List snapshots, + @Param("redactionVersion") int redactionVersion); +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentMemoryDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentMemoryDTO.java index 556b4437e..641631781 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentMemoryDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentMemoryDTO.java @@ -16,4 +16,4 @@ public class AgentMemoryDTO implements Serializable { @Schema(description = "Summary memory", example = "Build a growing dynamic memory network that retains key information in limited space while intelligently maintaining information evolution trajectory\n" + "Summarize important user information based on conversation records to provide more personalized service in future conversations", required = false) private String summaryMemory; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotDataDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotDataDTO.java new file mode 100644 index 000000000..328c73cf3 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotDataDTO.java @@ -0,0 +1,40 @@ +package xiaozhi.modules.agent.dto; + +import java.io.Serializable; +import java.util.List; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "智能体快照数据") +public class AgentSnapshotDataDTO implements Serializable { + private static final long serialVersionUID = 1L; + + private String agentCode; + private String agentName; + private String asrModelId; + private String vadModelId; + private String llmModelId; + private String slmModelId; + private String vllmModelId; + private String ttsModelId; + private String ttsVoiceId; + private String ttsLanguage; + private Integer ttsVolume; + private Integer ttsRate; + private Integer ttsPitch; + private String memModelId; + private String intentModelId; + private Integer chatHistoryConf; + private String systemPrompt; + private String summaryMemory; + private String langCode; + private String language; + private Integer sort; + private List functions; + private List contextProviders; + private List correctWordFileIds; + private List tagNames; + private List tags; +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotPageDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotPageDTO.java new file mode 100644 index 000000000..3f3f5d655 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotPageDTO.java @@ -0,0 +1,28 @@ +package xiaozhi.modules.agent.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "智能体快照分页查询参数") +public class AgentSnapshotPageDTO { + @Schema(description = "当前页码,从1开始", example = "1") + private Integer page = 1; + + @Schema(description = "每页数量", example = "10") + private Integer limit = 10; + + @Schema(description = "版本锚点,只查询小于等于该版本号的历史快照", example = "20") + private Integer maxVersionNo; + + public int pageOrDefault() { + return page == null || page < 1 ? 1 : page; + } + + public int limitOrDefault() { + if (limit == null || limit < 1) { + return 10; + } + return limit; + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotRestoreDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotRestoreDTO.java new file mode 100644 index 000000000..aa003fa4e --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotRestoreDTO.java @@ -0,0 +1,13 @@ +package xiaozhi.modules.agent.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +@Data +@Schema(description = "智能体快照恢复请求") +public class AgentSnapshotRestoreDTO { + @NotBlank + @Schema(description = "预览时由服务端生成的当前配置状态指纹") + private String currentStateToken; +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotTagDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotTagDTO.java new file mode 100644 index 000000000..6e93dd0e5 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotTagDTO.java @@ -0,0 +1,16 @@ +package xiaozhi.modules.agent.dto; + +import java.io.Serializable; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "智能体快照标签") +public class AgentSnapshotTagDTO implements Serializable { + private static final long serialVersionUID = 1L; + + private String id; + private String tagName; + private Integer sort; +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentUpdateDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentUpdateDTO.java index 247b2c2c5..d61b4c08a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentUpdateDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentUpdateDTO.java @@ -4,9 +4,12 @@ import java.io.Serializable; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; +import java.util.Map; +import com.fasterxml.jackson.core.type.TypeReference; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; +import xiaozhi.common.utils.JsonUtils; /** * Agent update DTO. @@ -91,6 +94,12 @@ public class AgentUpdateDTO implements Serializable { @Schema(description = "替换词文件ID列表", nullable = true) private List correctWordFileIds; + @Schema(description = "标签名称列表", nullable = true) + private List tagNames; + + @Schema(description = "标签ID列表", nullable = true) + private List tagIds; + @Data @Schema(description = "Plugin function information") public static class FunctionInfo implements Serializable { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentContextProviderEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentContextProviderEntity.java index d01fb7881..51d715dfa 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentContextProviderEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentContextProviderEntity.java @@ -7,11 +7,11 @@ import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; -import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import xiaozhi.modules.agent.dto.ContextProviderDTO; +import xiaozhi.modules.agent.typehandler.ContextProviderListTypeHandler; @Data @TableName(value = "ai_agent_context_provider", autoResultMap = true) diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentSnapshotEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentSnapshotEntity.java new file mode 100644 index 000000000..c4ad695df --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentSnapshotEntity.java @@ -0,0 +1,53 @@ +package xiaozhi.modules.agent.entity; + +import java.util.Date; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@TableName("ai_agent_snapshot") +@Schema(description = "智能体配置快照") +public class AgentSnapshotEntity { + + @TableId(type = IdType.ASSIGN_UUID) + @Schema(description = "快照ID") + private String id; + + @Schema(description = "智能体ID") + private String agentId; + + @Schema(description = "所属用户ID") + private Long userId; + + @Schema(description = "版本号") + private Integer versionNo; + + @Schema(description = "快照数据JSON") + private String snapshotData; + + @Schema(description = "变更字段JSON") + private String changedFields; + + @Schema(description = "快照来源") + private String source; + + @Schema(description = "恢复来源快照ID") + private String restoreFromSnapshotId; + + @Schema(description = "恢复来源版本号") + private Integer restoreFromVersionNo; + + @Schema(description = "创建者") + private Long creator; + + @Schema(description = "创建时间") + private Date createdAt; + + @Schema(description = "快照数据脱敏规则版本") + private Integer redactionVersion; +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatAudioService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatAudioService.java index 805c13ba1..9e53a8d0b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatAudioService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatAudioService.java @@ -1,6 +1,6 @@ package xiaozhi.modules.agent.service; -import com.baomidou.mybatisplus.extension.service.IService; +import com.baomidou.mybatisplus.extension.repository.IRepository; import xiaozhi.modules.agent.entity.AgentChatAudioEntity; @@ -11,7 +11,7 @@ import xiaozhi.modules.agent.entity.AgentChatAudioEntity; * @version 1.0, 2025/5/8 * @since 1.0.0 */ -public interface AgentChatAudioService extends IService { +public interface AgentChatAudioService extends IRepository { /** * Save audio data * diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatHistoryService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatHistoryService.java index 9b1d01924..a5adb43c8 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatHistoryService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentChatHistoryService.java @@ -3,9 +3,9 @@ package xiaozhi.modules.agent.service; import java.util.List; import java.util.Map; -import com.baomidou.mybatisplus.extension.service.IService; - -import xiaozhi.common.page.PageData; +import com.baomidou.mybatisplus.extension.repository.IRepository; + +import xiaozhi.common.page.PageData; import xiaozhi.modules.agent.dto.AgentChatHistoryDTO; import xiaozhi.modules.agent.dto.AgentChatSessionDTO; import xiaozhi.modules.agent.entity.AgentChatHistoryEntity; @@ -18,7 +18,7 @@ import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO; * @version 1.0, 2025/4/30 * @since 1.0.0 */ -public interface AgentChatHistoryService extends IService { +public interface AgentChatHistoryService extends IRepository { /** * Get session list by agent ID @@ -37,6 +37,14 @@ public interface AgentChatHistoryService extends IService getChatHistoryBySessionId(String agentId, String sessionId); + /** + * 根据会话ID获取智能体ID + * + * @param sessionId 会话ID + * @return 智能体ID + */ + String getAgentIdBySessionId(String sessionId); + /** * Delete chat records by agent ID * @@ -70,6 +78,14 @@ public interface AgentChatHistoryService extends IService { +public interface AgentPluginMappingService extends IRepository { /** * 根据智能体id获取插件参数 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java index c235c23a2..13121454a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java @@ -7,6 +7,7 @@ import xiaozhi.common.page.PageData; import xiaozhi.common.service.BaseService; import xiaozhi.modules.agent.dto.AgentCreateDTO; import xiaozhi.modules.agent.dto.AgentDTO; +import xiaozhi.modules.agent.dto.AgentMemoryDTO; import xiaozhi.modules.agent.dto.AgentUpdateDTO; import xiaozhi.modules.agent.entity.AgentEntity; import xiaozhi.modules.agent.vo.AgentInfoVO; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentSnapshotService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentSnapshotService.java new file mode 100644 index 000000000..57e03ebfb --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentSnapshotService.java @@ -0,0 +1,25 @@ +package xiaozhi.modules.agent.service; + +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.BaseService; +import xiaozhi.modules.agent.dto.AgentSnapshotPageDTO; +import xiaozhi.modules.agent.entity.AgentSnapshotEntity; +import xiaozhi.modules.agent.vo.AgentSnapshotVO; + +public interface AgentSnapshotService extends BaseService { + void createSnapshot(String agentId, String source); + + PageData page(String agentId, AgentSnapshotPageDTO params); + + AgentSnapshotVO getSnapshot(String agentId, String snapshotId); + + void restoreSnapshot(String agentId, String snapshotId, String currentStateToken); + + void deleteSnapshot(String agentId, String snapshotId); + + Integer getCurrentVersionNo(String agentId); + + void deleteByAgentId(String agentId); + + long redactLegacySnapshots(); +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java index 092f02b89..b699d4603 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java @@ -1,7 +1,7 @@ package xiaozhi.modules.agent.service; -import com.baomidou.mybatisplus.extension.service.IService; - +import com.baomidou.mybatisplus.extension.repository.IRepository; + import xiaozhi.modules.agent.entity.AgentTemplateEntity; /** @@ -9,7 +9,7 @@ import xiaozhi.modules.agent.entity.AgentTemplateEntity; * @description Database operation Service for table [ai_agent_template(agent configuration template table)] * @createDate 2025-03-22 11:48:18 */ -public interface AgentTemplateService extends IService { +public interface AgentTemplateService extends IRepository { /** * Get default template diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatAudioServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatAudioServiceImpl.java index 457faab85..81e31b983 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatAudioServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatAudioServiceImpl.java @@ -2,7 +2,7 @@ package xiaozhi.modules.agent.service.impl; import org.springframework.stereotype.Service; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.baomidou.mybatisplus.spring.repository.CrudRepository; import xiaozhi.modules.agent.dao.AiAgentChatAudioDao; import xiaozhi.modules.agent.entity.AgentChatAudioEntity; @@ -16,7 +16,7 @@ import xiaozhi.modules.agent.service.AgentChatAudioService; * @since 1.0.0 */ @Service -public class AgentChatAudioServiceImpl extends ServiceImpl +public class AgentChatAudioServiceImpl extends CrudRepository implements AgentChatAudioService { @Override public String saveAudio(byte[] audioData) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatHistoryServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatHistoryServiceImpl.java index e839f4a99..c2ed0705e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatHistoryServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatHistoryServiceImpl.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.ListUtil; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -14,13 +15,12 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.baomidou.mybatisplus.spring.repository.CrudRepository; import xiaozhi.common.constant.Constant; import xiaozhi.common.page.PageData; import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.JsonUtils; -import xiaozhi.common.utils.ToolUtil; import xiaozhi.modules.agent.Enums.AgentChatHistoryType; import xiaozhi.modules.agent.dao.AiAgentChatHistoryDao; import xiaozhi.modules.agent.dto.AgentChatHistoryDTO; @@ -39,7 +39,7 @@ import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO; */ @Service @RequiredArgsConstructor -public class AgentChatHistoryServiceImpl extends ServiceImpl +public class AgentChatHistoryServiceImpl extends CrudRepository implements AgentChatHistoryService { private final AgentChatTitleService agentChatTitleService; @@ -88,6 +88,19 @@ public class AgentChatHistoryServiceImpl extends ServiceImpl() + .select(AgentChatHistoryEntity::getAgentId) + .eq(AgentChatHistoryEntity::getSessionId, sessionId) + .last("LIMIT 1")); + return entity == null ? null : entity.getAgentId(); + } + @Override @Transactional(rollbackFor = Exception.class) public void deleteByAgentId(String agentId, Boolean deleteAudio, Boolean deleteText) { @@ -159,7 +172,7 @@ public class AgentChatHistoryServiceImpl extends ServiceImpl jsonMap = JsonUtils.parseObject(content, Map.class); + Map jsonMap = JsonUtils.parseMap(content); if (jsonMap != null && jsonMap.containsKey("content")) { Object contentObj = jsonMap.get("content"); return contentObj != null ? contentObj.toString() : content; @@ -181,6 +194,19 @@ public class AgentChatHistoryServiceImpl extends ServiceImpl() + .select(AgentChatHistoryEntity::getAgentId) + .eq(AgentChatHistoryEntity::getAudioId, audioId) + .last("LIMIT 1")); + return entity == null ? null : entity.getAgentId(); + } + @Override public boolean isAudioOwnedByAgent(String audioId, String agentId) { // Check whether exactly one record exists for the given audio ID and agent ID. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentMcpAccessPointServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentMcpAccessPointServiceImpl.java index 31ace32d9..2d4f9f5dd 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentMcpAccessPointServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentMcpAccessPointServiceImpl.java @@ -12,11 +12,11 @@ import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; +import cn.hutool.crypto.digest.DigestUtil; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import xiaozhi.common.constant.Constant; import xiaozhi.common.utils.AESUtils; -import xiaozhi.common.utils.HashEncryptionUtil; import xiaozhi.common.utils.JsonUtils; import xiaozhi.modules.agent.Enums.XiaoZhiMcpJsonRpcJson; import xiaozhi.modules.agent.service.AgentMcpAccessPointService; @@ -76,7 +76,7 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic // Wait for initialization response (id=1) - Remove fixed delay, change to response-driven List initResponses = client.listenerWithoutClose(response -> { try { - Map jsonMap = JsonUtils.parseObject(response, Map.class); + Map jsonMap = JsonUtils.parseMap(response); if (jsonMap != null && Integer.valueOf(1).equals(jsonMap.get("id"))) { // Check if there is a result field, indicating successful initialization return jsonMap.containsKey("result") && !jsonMap.containsKey("error"); @@ -92,7 +92,7 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic boolean initSucceeded = false; for (String response : initResponses) { try { - Map jsonMap = JsonUtils.parseObject(response, Map.class); + Map jsonMap = JsonUtils.parseMap(response); if (jsonMap != null && Integer.valueOf(1).equals(jsonMap.get("id"))) { if (jsonMap.containsKey("result")) { log.info("MCP initialization successful, Agent ID: {}", id); @@ -123,7 +123,7 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic // Wait for tools list response (id=2) List toolsResponses = client.listener(response -> { try { - Map jsonMap = JsonUtils.parseObject(response, Map.class); + Map jsonMap = JsonUtils.parseMap(response); return jsonMap != null && Integer.valueOf(2).equals(jsonMap.get("id")); } catch (Exception e) { log.warn("Failed to parse tools list response: {}", response, e); @@ -134,18 +134,18 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic // Process tools list response for (String response : toolsResponses) { try { - Map jsonMap = JsonUtils.parseObject(response, Map.class); + Map jsonMap = JsonUtils.parseMap(response); if (jsonMap != null && Integer.valueOf(2).equals(jsonMap.get("id"))) { // Check if there is a result field Object resultObj = jsonMap.get("result"); - if (resultObj instanceof Map) { - Map resultMap = (Map) resultObj; + if (resultObj instanceof Map) { + Map resultMap = JsonUtils.toStringObjectMap(resultObj); Object toolsObj = resultMap.get("tools"); if (toolsObj instanceof List) { List> toolsList = (List>) toolsObj; // Extract tool name list List result = toolsList.stream() - .map(tool -> (String) tool.get("name")) + .map(tool -> String.class.cast(tool.get("name"))) .filter(name -> name != null) .sorted() .collect(Collectors.toList()); @@ -232,4 +232,4 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic // Encrypt to token value return AESUtils.encrypt(key, json); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java index 63158ab74..c979cc9cf 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java @@ -9,7 +9,7 @@ import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.baomidou.mybatisplus.spring.repository.CrudRepository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -29,7 +29,7 @@ import xiaozhi.modules.model.service.ModelConfigService; @Service @RequiredArgsConstructor @Slf4j -public class AgentPluginMappingServiceImpl extends ServiceImpl +public class AgentPluginMappingServiceImpl extends CrudRepository implements AgentPluginMappingService { private final AgentPluginMappingMapper agentPluginMappingMapper; private final KnowledgeBaseService knowledgeBaseService; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java index 981a2bcf4..8001c205f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java @@ -15,9 +15,10 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.repository.IRepository; +import cn.hutool.core.collection.CollUtil; import lombok.AllArgsConstructor; import xiaozhi.common.constant.Constant; import xiaozhi.common.exception.ErrorCode; @@ -29,11 +30,11 @@ import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.user.UserDetail; import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.JsonUtils; -import xiaozhi.common.utils.ToolUtil; import xiaozhi.modules.agent.dao.AgentDao; import xiaozhi.modules.agent.dao.AgentTagDao; import xiaozhi.modules.agent.dto.AgentCreateDTO; import xiaozhi.modules.agent.dto.AgentDTO; +import xiaozhi.modules.agent.dto.AgentMemoryDTO; import xiaozhi.modules.agent.dto.AgentTagDTO; import xiaozhi.modules.agent.dto.AgentUpdateDTO; import xiaozhi.modules.agent.entity.AgentContextProviderEntity; @@ -43,9 +44,10 @@ import xiaozhi.modules.agent.entity.AgentTagEntity; import xiaozhi.modules.agent.entity.AgentTemplateEntity; import xiaozhi.modules.agent.service.AgentChatHistoryService; import xiaozhi.modules.agent.service.AgentContextProviderService; -import xiaozhi.modules.agent.service.AgentPluginMappingService; -import xiaozhi.modules.agent.service.AgentService; -import xiaozhi.modules.agent.service.AgentTagService; +import xiaozhi.modules.agent.service.AgentPluginMappingService; +import xiaozhi.modules.agent.service.AgentService; +import xiaozhi.modules.agent.service.AgentSnapshotService; +import xiaozhi.modules.agent.service.AgentTagService; import xiaozhi.modules.agent.service.AgentTemplateService; import xiaozhi.modules.agent.vo.AgentInfoVO; import xiaozhi.modules.correctword.service.CorrectWordFileService; @@ -56,9 +58,9 @@ import xiaozhi.modules.model.dto.VoiceDTO; import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.model.service.ModelProviderService; -import xiaozhi.modules.security.user.SecurityUser; -import xiaozhi.modules.sys.enums.SuperAdminEnum; -import xiaozhi.modules.timbre.service.TimbreService; +import xiaozhi.modules.security.user.SecurityUser; +import xiaozhi.modules.sys.enums.SuperAdminEnum; +import xiaozhi.modules.timbre.service.TimbreService; @Service @AllArgsConstructor @@ -73,9 +75,10 @@ public class AgentServiceImpl extends BaseServiceImpl imp private final AgentChatHistoryService agentChatHistoryService; private final AgentTemplateService agentTemplateService; private final ModelProviderService modelProviderService; - private final AgentContextProviderService agentContextProviderService; - private final AgentTagService agentTagService; - private final CorrectWordFileService correctWordFileService; + private final AgentContextProviderService agentContextProviderService; + private final AgentTagService agentTagService; + private final CorrectWordFileService correctWordFileService; + private final AgentSnapshotService agentSnapshotService; @Override public PageData adminAgentList(Map params) { @@ -92,6 +95,7 @@ public class AgentServiceImpl extends BaseServiceImpl imp if (agent == null) { throw new RenException(ErrorCode.AGENT_NOT_FOUND); } + requireCurrentUserPermissionIfPresent(agent); if (agent.getMemModelId() != null && agent.getMemModelId().equals(Constant.MEMORY_NO_MEM)) { agent.setChatHistoryConf(Constant.ChatHistoryConfEnum.IGNORE.getCode()); @@ -106,14 +110,74 @@ public class AgentServiceImpl extends BaseServiceImpl imp agent.setContextProviders(contextProviderEntity.getContextProviders()); } - // 查询替换词文件ID列表 - List correctWordFileIds = correctWordFileService.getAgentCorrectWordFileIds(id); - agent.setCorrectWordFileIds(correctWordFileIds); - - // 无需额外查询插件列表,已通过SQL查询出来 - return agent; + // 查询替换词文件ID列表 + List correctWordFileIds = correctWordFileService.getAgentCorrectWordFileIds(id); + agent.setCorrectWordFileIds(correctWordFileIds); + agent.setCurrentVersionNo(agentSnapshotService.getCurrentVersionNo(id)); + + // 无需额外查询插件列表,已通过SQL查询出来 + return agent; } + @Override + public AgentInfoVO getAgentById(String id, Long userId) { + AgentInfoVO agent = getAgentById(id); + requireAgentPermission(agent, userId); + return agent; + } + + private AgentEntity getAgentEntityOrThrow(String agentId) { + AgentEntity agent = agentDao.selectById(agentId); + if (agent == null) { + throw new RenException(ErrorCode.AGENT_NOT_FOUND); + } + return agent; + } + + private boolean isCurrentUserSuperAdmin() { + UserDetail user = SecurityUser.getUser(); + return user != null && Integer.valueOf(SuperAdminEnum.YES.value()).equals(user.getSuperAdmin()); + } + + private void requireCurrentUserPermissionIfPresent(AgentEntity agent) { + Long userId = SecurityUser.getUserId(); + if (userId != null) { + requireAgentPermission(agent, userId); + } + } + + private boolean hasAgentPermission(AgentEntity agent, Long userId) { + if (agent == null) { + return false; + } + if (isCurrentUserSuperAdmin()) { + return true; + } + return userId != null && userId.equals(agent.getUserId()); + } + + private void requireAgentPermission(AgentEntity agent, Long userId) { + if (!hasAgentPermission(agent, userId)) { + throw new RenException(ErrorCode.NO_PERMISSION); + } + } + + private boolean hasDevicePermission(DeviceEntity device, Long userId) { + if (device == null) { + return false; + } + if (isCurrentUserSuperAdmin()) { + return true; + } + return userId != null && userId.equals(device.getUserId()); + } + + private void requireDevicePermission(DeviceEntity device, Long userId) { + if (!hasDevicePermission(device, userId)) { + throw new RenException(ErrorCode.NO_PERMISSION); + } + } + @Override public boolean insert(AgentEntity entity) { // 如果ID为空,自动生成一个UUID作为ID @@ -134,15 +198,35 @@ public class AgentServiceImpl extends BaseServiceImpl imp return super.insert(entity); } - @Override - public void deleteAgentByUserId(Long userId) { - UpdateWrapper wrapper = new UpdateWrapper<>(); - wrapper.eq("user_id", userId); - baseDao.delete(wrapper); - } - - @Override - public List getUserAgents(Long userId, String keyword, String searchType) { + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteAgentByUserId(Long userId) { + List agents = baseDao.selectList(new QueryWrapper() + .select("id") + .eq("user_id", userId)); + for (AgentEntity agent : agents) { + deleteAgent(agent.getId()); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteAgent(String agentId) { + if (agentDao.selectByIdForUpdate(agentId) == null) { + return; + } + deviceService.deleteByAgentId(agentId); + agentChatHistoryService.deleteByAgentId(agentId, true, true); + agentPluginMappingService.deleteByAgentId(agentId); + agentContextProviderService.deleteByAgentId(agentId); + correctWordFileService.deleteMappingsByAgentId(agentId); + agentTagService.deleteAgentTags(agentId); + agentSnapshotService.deleteByAgentId(agentId); + deleteById(agentId); + } + + @Override + public List getUserAgents(Long userId, String keyword, String searchType) { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("user_id", userId).orderByDesc("created_at"); @@ -159,13 +243,13 @@ public class AgentServiceImpl extends BaseServiceImpl imp .map(DeviceEntity::getAgentId) .distinct() .collect(Collectors.toList()); - if (ToolUtil.isNotEmpty(agentIds)) { + if (CollUtil.isNotEmpty(agentIds)) { w.or().in("id", agentIds); } // 按标签名搜索 List tagAgentIds = agentTagService.getAgentIdsByTagName(keyword); - if (ToolUtil.isNotEmpty(tagAgentIds)) { + if (CollUtil.isNotEmpty(tagAgentIds)) { w.or().in("id", tagAgentIds); } }); @@ -207,7 +291,7 @@ public class AgentServiceImpl extends BaseServiceImpl imp // 获取标签列表 List tags = agentTagDao.selectByAgentId(agent.getId()); - if (ToolUtil.isNotEmpty(tags)) { + if (CollUtil.isNotEmpty(tags)) { dto.setTags(tags.stream().map(this::convertTagToDTO).collect(Collectors.toList())); } @@ -253,42 +337,56 @@ public class AgentServiceImpl extends BaseServiceImpl imp } @Override - public boolean checkAgentPermission(String agentId, Long userId) { - if (SecurityUser.getUser() == null || SecurityUser.getUser().getId() == null) { - return false; - } - // 获取智能体信息 - AgentEntity agent = getAgentById(agentId); - if (agent == null) { - return false; - } - - // 如果是超级管理员,直接返回true - if (SecurityUser.getUser().getSuperAdmin() == SuperAdminEnum.YES.value()) { - return true; - } - - // 检查是否是智能体的所有者 - return userId.equals(agent.getUserId()); - } - - // 根据id更新智能体信息 - @Override - @Transactional(rollbackFor = Exception.class) - public void updateAgentById(String agentId, AgentUpdateDTO dto) { - // 先查询现有实体 - AgentEntity existingEntity = this.getAgentById(agentId); - if (existingEntity == null) { - throw new RenException(ErrorCode.AGENT_NOT_FOUND); - } - - // 只更新提供的非空字段 - if (dto.getAgentName() != null) { - existingEntity.setAgentName(dto.getAgentName()); - } - if (dto.getAgentCode() != null) { - existingEntity.setAgentCode(dto.getAgentCode()); - } + public boolean checkAgentPermission(String agentId, Long userId) { + AgentEntity agent = agentDao.selectById(agentId); + return hasAgentPermission(agent, userId); + } + + // 根据id更新智能体信息 + @Override + @Transactional(rollbackFor = Exception.class) + public void updateAgentById(String agentId, AgentUpdateDTO dto) { + updateAgentById(agentId, dto, true); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void updateAgentById(String agentId, AgentUpdateDTO dto, Long userId) { + updateAgentById(agentId, dto, userId, true); + } + + // 根据id更新智能体信息 + @Override + @Transactional(rollbackFor = Exception.class) + public void updateAgentById(String agentId, AgentUpdateDTO dto, boolean createSnapshot) { + updateAgentById(agentId, dto, null, createSnapshot); + } + + private void updateAgentById(String agentId, AgentUpdateDTO dto, Long userId, boolean createSnapshot) { + AgentEntity lockedAgent = agentDao.selectByIdForUpdate(agentId); + if (lockedAgent == null) { + throw new RenException(ErrorCode.AGENT_NOT_FOUND); + } + if (userId == null) { + requireCurrentUserPermissionIfPresent(lockedAgent); + } else { + requireAgentPermission(lockedAgent, userId); + } + + // 锁定后查询现有实体和关联配置 + AgentEntity existingEntity = this.getAgentById(agentId); + if (createSnapshot) { + int currentVersionNo = agentSnapshotService.getCurrentVersionNo(agentId); + agentSnapshotService.createSnapshot(agentId, currentVersionNo == 0 ? "initial" : "current"); + } + + // 只更新提供的非空字段 + if (dto.getAgentName() != null) { + existingEntity.setAgentName(dto.getAgentName()); + } + if (dto.getAgentCode() != null) { + existingEntity.setAgentCode(dto.getAgentCode()); + } if (dto.getAsrModelId() != null) { existingEntity.setAsrModelId(dto.getAsrModelId()); } @@ -385,10 +483,10 @@ public class AgentServiceImpl extends BaseServiceImpl imp .toList(); if (!toUpdate.isEmpty()) { - agentPluginMappingService.updateBatchById(toUpdate); + agentPluginMappingService.updateBatchById(toUpdate, IRepository.DEFAULT_BATCH_SIZE); } if (!toInsert.isEmpty()) { - agentPluginMappingService.saveBatch(toInsert); + agentPluginMappingService.saveBatch(toInsert, IRepository.DEFAULT_BATCH_SIZE); } // 5. 删除本次不在提交列表里的插件映射 @@ -397,7 +495,7 @@ public class AgentServiceImpl extends BaseServiceImpl imp .map(AgentPluginMapping::getId) .toList(); if (!toDelete.isEmpty()) { - agentPluginMappingService.removeBatchByIds(toDelete); + agentPluginMappingService.removeByIds(toDelete); } } @@ -426,17 +524,48 @@ public class AgentServiceImpl extends BaseServiceImpl imp } // 更新替换词文件关联 - if (dto.getCorrectWordFileIds() != null) { - correctWordFileService.saveAgentCorrectWords(agentId, dto.getCorrectWordFileIds()); - } - - boolean b = validateLLMIntentParams(dto.getLlmModelId(), dto.getIntentModelId()); - if (!b) { - throw new RenException(ErrorCode.LLM_INTENT_PARAMS_MISMATCH); - } - this.updateById(existingEntity); - } + if (dto.getCorrectWordFileIds() != null) { + correctWordFileService.saveAgentCorrectWords(agentId, dto.getCorrectWordFileIds()); + } + + // 更新智能体标签 + if (dto.getTagNames() != null || dto.getTagIds() != null) { + agentTagService.saveAgentTags(agentId, dto.getTagIds(), dto.getTagNames()); + } + + boolean b = validateLLMIntentParams(existingEntity.getLlmModelId(), existingEntity.getIntentModelId()); + if (!b) { + throw new RenException(ErrorCode.LLM_INTENT_PARAMS_MISMATCH); + } + this.updateById(existingEntity); + if (createSnapshot) { + agentSnapshotService.createSnapshot(agentId, "config"); + } + } + @Override + @Transactional(rollbackFor = Exception.class) + public void updateAgentMemoryByDeviceMacAddress(String macAddress, AgentMemoryDTO dto, Long userId) { + DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress); + if (device == null || StringUtils.isBlank(device.getAgentId()) || dto == null) { + return; + } + + requireDevicePermission(device, userId); + + AgentUpdateDTO agentUpdateDTO = new AgentUpdateDTO(); + agentUpdateDTO.setSummaryMemory(dto.getSummaryMemory()); + updateAgentById(device.getAgentId(), agentUpdateDTO, userId, false); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteAgentById(String agentId, Long userId) { + AgentEntity agent = getAgentEntityOrThrow(agentId); + requireAgentPermission(agent, userId); + deleteAgent(agentId); + } + /** * 验证大语言模型和意图识别的参数是否符合匹配 * @@ -487,16 +616,22 @@ public class AgentServiceImpl extends BaseServiceImpl imp template.setTtsVoiceId(timbre.getId()); } } - } - - entity.setTtsVoiceId(template.getTtsVoiceId()); - entity.setMemModelId(template.getMemModelId()); - entity.setIntentModelId(template.getIntentModelId()); - entity.setSystemPrompt(template.getSystemPrompt()); - entity.setSummaryMemory(template.getSummaryMemory()); - - // 根据记忆模型类型设置默认的chatHistoryConf值 - if (template.getMemModelId() != null) { + } + + entity.setTtsVoiceId(template.getTtsVoiceId()); + entity.setTtsLanguage(defaultIfBlank(template.getTtsLanguage(), + timbreModelService.getDefaultLanguageById(entity.getTtsVoiceId()))); + entity.setMemModelId(template.getMemModelId()); + entity.setIntentModelId(template.getIntentModelId()); + entity.setSystemPrompt(template.getSystemPrompt()); + entity.setSummaryMemory(template.getSummaryMemory()); + if (Constant.MEMORY_NO_MEM.equals(entity.getMemModelId()) + || Constant.MEMORY_MEM_REPORT_ONLY.equals(entity.getMemModelId())) { + entity.setSummaryMemory(""); + } + + // 根据记忆模型类型设置默认的chatHistoryConf值 + if (template.getMemModelId() != null) { if (template.getMemModelId().equals("Memory_nomem")) { // 无记忆功能的模型,默认不记录聊天记录 entity.setChatHistoryConf(0); @@ -542,7 +677,7 @@ public class AgentServiceImpl extends BaseServiceImpl imp mapping.setPluginId(pluginId); Map paramInfo = new HashMap<>(); - List> fields = JsonUtils.parseObject(provider.getFields(), List.class); + List> fields = JsonUtils.parseMapList(provider.getFields()); if (fields != null) { for (Map field : fields) { paramInfo.put((String) field.get("key"), field.get("default")); @@ -551,13 +686,18 @@ public class AgentServiceImpl extends BaseServiceImpl imp mapping.setParamInfo(JsonUtils.toJsonString(paramInfo)); mapping.setAgentId(entity.getId()); toInsert.add(mapping); - } - // 保存默认插件 - agentPluginMappingService.saveBatch(toInsert); - return entity.getId(); - } - - private String getDefaultLLMModelId() { + } + // 保存默认插件 + agentPluginMappingService.saveBatch(toInsert, IRepository.DEFAULT_BATCH_SIZE); + agentSnapshotService.createSnapshot(entity.getId(), "initial"); + return entity.getId(); + } + + private String defaultIfBlank(String value, String defaultValue) { + return StringUtils.isBlank(value) ? defaultValue : value; + } + + private String getDefaultLLMModelId() { try { List llmConfigs = modelConfigService.getEnabledModelsByType("LLM"); if (llmConfigs == null || llmConfigs.isEmpty()) { @@ -576,4 +716,4 @@ public class AgentServiceImpl extends BaseServiceImpl imp } } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentSnapshotRedactionRunner.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentSnapshotRedactionRunner.java new file mode 100644 index 000000000..33ff67f64 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentSnapshotRedactionRunner.java @@ -0,0 +1,59 @@ +package xiaozhi.modules.agent.service.impl; + +import java.util.concurrent.TimeUnit; + +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import xiaozhi.modules.agent.service.AgentSnapshotService; + +@Slf4j +@Component +@RequiredArgsConstructor +public class AgentSnapshotRedactionRunner implements SmartInitializingSingleton { + static final long ROLLING_DEPLOYMENT_INITIAL_DELAY_MILLIS = 5_000; + static final long ROLLING_DEPLOYMENT_FIXED_DELAY_MILLIS = 15_000; + + private final AgentSnapshotService agentSnapshotService; + + @Override + public void afterSingletonsInstantiated() { + redactAndReport("startup"); + } + + @Scheduled(initialDelay = ROLLING_DEPLOYMENT_INITIAL_DELAY_MILLIS, + fixedDelay = ROLLING_DEPLOYMENT_FIXED_DELAY_MILLIS) + public void redactLateRollingDeploymentWrites() { + redactAndReport("rolling-deployment"); + } + + private void redactAndReport(String trigger) { + long startedAt = System.nanoTime(); + try { + long migrated = agentSnapshotService.redactLegacySnapshots(); + long durationMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt); + if (migrated > 0) { + log.warn("Agent snapshot legacy redaction trigger={} migrated={} durationMs={}. Rotate credentials " + + "that may have appeared in historical snapshot URLs, cookies, sessions, or structured " + + "headers.", trigger, migrated, durationMillis); + } else if ("startup".equals(trigger)) { + log.info("Agent snapshot legacy redaction startup pass completed: migrated=0 durationMs={}; " + + "rolling-deployment compensation starts after {} ms and repeats every {} ms.", + durationMillis, ROLLING_DEPLOYMENT_INITIAL_DELAY_MILLIS, + ROLLING_DEPLOYMENT_FIXED_DELAY_MILLIS); + } + } catch (RuntimeException exception) { + if ("startup".equals(trigger)) { + log.error("Agent snapshot legacy redaction failed during startup; blocking application startup " + + "before it can accept traffic.", exception); + } else { + log.error("Agent snapshot legacy redaction failed during rolling-deployment compensation; the " + + "scheduler will retry on its next run.", exception); + } + throw exception; + } + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentSnapshotServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentSnapshotServiceImpl.java new file mode 100644 index 000000000..0cab47fb2 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentSnapshotServiceImpl.java @@ -0,0 +1,1772 @@ +package xiaozhi.modules.agent.service.impl; + +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.metadata.OrderItem; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.repository.IRepository; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +import lombok.AllArgsConstructor; +import xiaozhi.common.constant.Constant; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.impl.BaseServiceImpl; +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.modules.agent.dao.AgentDao; +import xiaozhi.modules.agent.dao.AgentSnapshotDao; +import xiaozhi.modules.agent.dao.AgentTagDao; +import xiaozhi.modules.agent.dao.AgentTagRelationDao; +import xiaozhi.modules.agent.dto.AgentSnapshotDataDTO; +import xiaozhi.modules.agent.dto.AgentSnapshotPageDTO; +import xiaozhi.modules.agent.dto.AgentSnapshotTagDTO; +import xiaozhi.modules.agent.dto.AgentUpdateDTO; +import xiaozhi.modules.agent.dto.ContextProviderDTO; +import xiaozhi.modules.agent.entity.AgentContextProviderEntity; +import xiaozhi.modules.agent.entity.AgentEntity; +import xiaozhi.modules.agent.entity.AgentPluginMapping; +import xiaozhi.modules.agent.entity.AgentSnapshotEntity; +import xiaozhi.modules.agent.entity.AgentTagEntity; +import xiaozhi.modules.agent.entity.AgentTagRelationEntity; +import xiaozhi.modules.agent.Enums.AgentSnapshotField; +import xiaozhi.modules.agent.service.AgentChatHistoryService; +import xiaozhi.modules.agent.service.AgentContextProviderService; +import xiaozhi.modules.agent.service.AgentPluginMappingService; +import xiaozhi.modules.agent.service.AgentSnapshotService; +import xiaozhi.modules.agent.service.AgentTagService; +import xiaozhi.modules.agent.vo.AgentInfoVO; +import xiaozhi.modules.agent.vo.AgentSnapshotVO; +import xiaozhi.modules.correctword.service.CorrectWordFileService; +import xiaozhi.modules.model.entity.ModelConfigEntity; +import xiaozhi.modules.model.service.ModelConfigService; +import xiaozhi.modules.security.user.SecurityUser; + +@Service +@AllArgsConstructor +public class AgentSnapshotServiceImpl extends BaseServiceImpl + implements AgentSnapshotService { + private static final int MAX_SNAPSHOTS_PER_AGENT = 100; + private static final int LEGACY_REDACTION_BATCH_SIZE = 100; + private static final int CURRENT_REDACTION_VERSION = 2; + private static final TypeReference> STRING_LIST_TYPE = new TypeReference<>() { + }; + private static final TypeReference> PARAM_INFO_TYPE = new TypeReference<>() { + }; + private static final TypeReference> OBJECT_MAP_TYPE = new TypeReference<>() { + }; + private static final ObjectMapper SNAPSHOT_OBJECT_MAPPER = new ObjectMapper() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + private static final String SECRET_PLACEHOLDER = "__SNAPSHOT_SECRET_REDACTED__"; + private static final String SOURCE_CONFIG = "config"; + private static final String SOURCE_CURRENT_BACKUP = "current"; + private static final String SOURCE_RESTORE_RESULT = "restore"; + + private final AgentSnapshotDao agentSnapshotDao; + private final AgentDao agentDao; + private final AgentTagDao agentTagDao; + private final AgentTagRelationDao agentTagRelationDao; + private final AgentPluginMappingService agentPluginMappingService; + private final AgentContextProviderService agentContextProviderService; + private final AgentTagService agentTagService; + private final AgentChatHistoryService agentChatHistoryService; + private final ModelConfigService modelConfigService; + private final CorrectWordFileService correctWordFileService; + + @Override + @Transactional(rollbackFor = Exception.class) + public void createSnapshot(String agentId, String source) { + lockAgent(agentId); + AgentInfoVO agent = getAgentInfo(agentId); + AgentSnapshotDataDTO snapshotData = buildSnapshotData(agent); + AgentSnapshotEntity previousSnapshot = agentSnapshotDao.selectLatestSnapshot(agentId); + List changedFields; + if (previousSnapshot == null) { + changedFields = List.of("initial"); + } else { + AgentSnapshotDataDTO previousData = parseSnapshotData(previousSnapshot.getSnapshotData()); + changedFields = getChangedFields(previousData, snapshotData); + } + if (changedFields.isEmpty()) { + return; + } + + insertSnapshot(agentId, agent.getUserId(), source, snapshotData, changedFields); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public PageData page(String agentId, AgentSnapshotPageDTO params) { + AgentSnapshotPageDTO pageParams = params == null ? new AgentSnapshotPageDTO() : params; + Page page = new Page<>(pageParams.pageOrDefault(), pageParams.limitOrDefault()); + page.addOrder(OrderItem.desc("version_no")); + IPage result = agentSnapshotDao.selectPage(page, + new QueryWrapper() + .eq("agent_id", agentId) + .le(pageParams.getMaxVersionNo() != null, "version_no", pageParams.getMaxVersionNo())); + List list = result.getRecords().stream() + .map(entity -> toVO(entity, false)) + .toList(); + return new PageData<>(list, result.getTotal()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public AgentSnapshotVO getSnapshot(String agentId, String snapshotId) { + lockAgent(agentId); + AgentSnapshotEntity entity = getSnapshotEntity(agentId, snapshotId); + AgentSnapshotVO detail = toVO(entity, true); + AgentSnapshotDataDTO currentData = buildSnapshotData(agentId); + detail.setCurrentSnapshotData(redactSnapshotData(currentData)); + detail.setCurrentStateToken(buildCurrentStateToken(currentData)); + return detail; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void restoreSnapshot(String agentId, String snapshotId, String currentStateToken) { + AgentEntity agent = agentDao.selectByIdForUpdate(agentId); + if (agent == null) { + throw new RenException(ErrorCode.AGENT_NOT_FOUND); + } + + AgentSnapshotEntity snapshot = getSnapshotEntity(agentId, snapshotId); + AgentSnapshotDataDTO data = parseSnapshotData(snapshot.getSnapshotData()); + if (data == null) { + throw new RenException("快照数据为空,无法恢复"); + } + + AgentInfoVO currentAgent = getAgentInfo(agentId); + AgentSnapshotDataDTO currentData = buildSnapshotData(currentAgent); + if (!Objects.equals(buildCurrentStateToken(currentData), currentStateToken)) { + throw new RenException("当前配置已变化,请重新打开恢复预览后再试"); + } + AgentSnapshotDataDTO restoreData = preserveCurrentSensitiveValues(data, currentData); + validateSensitiveRestoreIsReversible(currentData, restoreData); + List requestedChangedFields = getChangedFields(currentData, restoreData); + if (requestedChangedFields.isEmpty()) { + return; + } + + AgentSnapshotEntity latestSnapshot = agentSnapshotDao.selectLatestSnapshot(agentId); + AgentSnapshotDataDTO latestData = latestSnapshot == null + ? null + : parseSnapshotData(latestSnapshot.getSnapshotData()); + List backupChangedFields = getChangedFields(latestData, currentData); + boolean backupCreated = !backupChangedFields.isEmpty(); + if (backupCreated) { + insertSnapshot(agentId, currentAgent.getUserId(), SOURCE_CURRENT_BACKUP, currentData, + backupChangedFields, null, null, false); + } + + applyAgentFields(agent, restoreData); + validateRestoreParams(agent); + applyMemoryPolicy(agent); + agent.setUpdater(SecurityUser.getUserId()); + agent.setUpdatedAt(new Date()); + int updatedRows = agentDao.updateSnapshotFields(agent); + // 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("智能体快照恢复失败"); + } + + restoreFunctions(agentId, restoreData.getFunctions()); + restoreContextProviders(agentId, restoreData.getContextProviders()); + correctWordFileService.saveAgentCorrectWords(agentId, nullToEmpty(restoreData.getCorrectWordFileIds())); + restoreTags(agentId, restoreData); + + AgentSnapshotDataDTO restoredData = buildSnapshotData(agentId); + List restoredChangedFields = getChangedFields(currentData, restoredData); + if (!restoredChangedFields.isEmpty()) { + insertSnapshot(agentId, currentAgent.getUserId(), SOURCE_RESTORE_RESULT, restoredData, + restoredChangedFields, snapshot.getId(), snapshot.getVersionNo(), false); + } + if (backupCreated || !restoredChangedFields.isEmpty()) { + pruneSnapshots(agentId); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteSnapshot(String agentId, String snapshotId) { + lockAgent(agentId); + AgentSnapshotEntity entity = getSnapshotEntity(agentId, snapshotId); + Integer maxVersionNo = agentSnapshotDao.selectMaxVersionNo(agentId); + if (Objects.equals(entity.getVersionNo(), maxVersionNo)) { + throw new RenException("最新历史版本不能删除"); + } + deleteById(snapshotId); + } + + @Override + public Integer getCurrentVersionNo(String agentId) { + Integer maxVersionNo = agentSnapshotDao.selectMaxVersionNo(agentId); + return maxVersionNo == null ? 0 : maxVersionNo; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteByAgentId(String agentId) { + agentSnapshotDao.delete(new QueryWrapper().eq("agent_id", agentId)); + } + + @Override + public long redactLegacySnapshots() { + String afterId = null; + long migrated = 0; + while (true) { + List batch = agentSnapshotDao.selectLegacyRedactionBatch(afterId, + LEGACY_REDACTION_BATCH_SIZE, CURRENT_REDACTION_VERSION); + if (batch == null || batch.isEmpty()) { + return migrated; + } + for (AgentSnapshotEntity snapshot : batch) { + Map rawData = JsonUtils.parseObject(snapshot.getSnapshotData(), OBJECT_MAP_TYPE); + if (rawData == null) { + throw new RenException("历史快照数据无法解析,已中止脱敏迁移: " + 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("历史快照批量脱敏迁移失败"); + } + migrated += affected; + afterId = batch.get(batch.size() - 1).getId(); + } + } + + private void insertSnapshot(String agentId, Long userId, String source, AgentSnapshotDataDTO snapshotData, + List changedFields) { + insertSnapshot(agentId, userId, source, snapshotData, changedFields, null, null); + } + + private void insertSnapshot(String agentId, Long userId, String source, AgentSnapshotDataDTO snapshotData, + List changedFields, String restoreFromSnapshotId, Integer restoreFromVersionNo) { + insertSnapshot(agentId, userId, source, snapshotData, changedFields, restoreFromSnapshotId, + restoreFromVersionNo, true); + } + + private void insertSnapshot(String agentId, Long userId, String source, AgentSnapshotDataDTO snapshotData, + List changedFields, String restoreFromSnapshotId, Integer restoreFromVersionNo, + boolean pruneAfterInsert) { + AgentSnapshotEntity entity = new AgentSnapshotEntity(); + entity.setId(UUID.randomUUID().toString().replace("-", "")); + entity.setAgentId(agentId); + entity.setUserId(userId); + entity.setSnapshotData(JsonUtils.toJsonString(redactSnapshotData(snapshotData))); + entity.setChangedFields(JsonUtils.toJsonString(changedFields)); + entity.setSource(StringUtils.defaultIfBlank(source, SOURCE_CONFIG)); + entity.setRestoreFromSnapshotId(restoreFromSnapshotId); + entity.setRestoreFromVersionNo(restoreFromVersionNo); + entity.setCreator(SecurityUser.getUserId()); + entity.setCreatedAt(new Date()); + entity.setRedactionVersion(CURRENT_REDACTION_VERSION); + int inserted = agentSnapshotDao.insertWithNextVersion(entity); + if (inserted != 1) { + throw new RenException("快照版本号生成失败"); + } + if (pruneAfterInsert) { + pruneSnapshots(agentId); + } + } + + private void lockAgent(String agentId) { + if (agentDao.selectByIdForUpdate(agentId) == null) { + throw new RenException(ErrorCode.AGENT_NOT_FOUND); + } + } + + private void pruneSnapshots(String agentId) { + agentSnapshotDao.deleteOlderThanKeepLimit(agentId, MAX_SNAPSHOTS_PER_AGENT); + } + + private AgentSnapshotEntity getSnapshotEntity(String agentId, String snapshotId) { + AgentSnapshotEntity entity = selectById(snapshotId); + if (entity == null || !Objects.equals(agentId, entity.getAgentId())) { + throw new RenException("快照不存在"); + } + return entity; + } + + private AgentInfoVO getAgentInfo(String agentId) { + AgentInfoVO agent = agentDao.selectAgentInfoById(agentId); + if (agent == null) { + throw new RenException(ErrorCode.AGENT_NOT_FOUND); + } + return agent; + } + + private AgentSnapshotDataDTO buildSnapshotData(String agentId) { + return buildSnapshotData(getAgentInfo(agentId)); + } + + private AgentSnapshotDataDTO buildSnapshotData(AgentInfoVO agent) { + AgentSnapshotDataDTO data = new AgentSnapshotDataDTO(); + data.setAgentCode(agent.getAgentCode()); + data.setAgentName(agent.getAgentName()); + data.setAsrModelId(agent.getAsrModelId()); + data.setVadModelId(agent.getVadModelId()); + data.setLlmModelId(agent.getLlmModelId()); + data.setSlmModelId(agent.getSlmModelId()); + data.setVllmModelId(agent.getVllmModelId()); + data.setTtsModelId(agent.getTtsModelId()); + data.setTtsVoiceId(agent.getTtsVoiceId()); + data.setTtsLanguage(agent.getTtsLanguage()); + data.setTtsVolume(agent.getTtsVolume()); + data.setTtsRate(agent.getTtsRate()); + data.setTtsPitch(agent.getTtsPitch()); + data.setMemModelId(agent.getMemModelId()); + data.setIntentModelId(agent.getIntentModelId()); + data.setChatHistoryConf(agent.getChatHistoryConf()); + data.setSystemPrompt(agent.getSystemPrompt()); + data.setSummaryMemory(agent.getSummaryMemory()); + data.setLangCode(agent.getLangCode()); + data.setLanguage(agent.getLanguage()); + data.setSort(agent.getSort()); + data.setFunctions(toFunctionInfo(agent.getFunctions())); + data.setContextProviders(getContextProviders(agent.getId())); + data.setCorrectWordFileIds(nullToEmpty(correctWordFileService.getAgentCorrectWordFileIds(agent.getId()))); + List tags = getSnapshotTags(agent.getId()); + data.setTags(tags); + data.setTagNames(tags.stream().map(AgentSnapshotTagDTO::getTagName).toList()); + return data; + } + + private List getSnapshotTags(String agentId) { + List tags = agentTagDao.selectByAgentId(agentId); + if (tags == null || tags.isEmpty()) { + return Collections.emptyList(); + } + List snapshotTags = new ArrayList<>(); + for (int i = 0; i < tags.size(); i++) { + AgentTagEntity tag = tags.get(i); + AgentSnapshotTagDTO snapshotTag = new AgentSnapshotTagDTO(); + snapshotTag.setId(tag.getId()); + snapshotTag.setTagName(tag.getTagName()); + snapshotTag.setSort(i); + snapshotTags.add(snapshotTag); + } + return snapshotTags; + } + + private List toFunctionInfo(List mappings) { + if (mappings == null || mappings.isEmpty()) { + return Collections.emptyList(); + } + return mappings.stream().map(mapping -> { + AgentUpdateDTO.FunctionInfo info = new AgentUpdateDTO.FunctionInfo(); + info.setPluginId(mapping.getPluginId()); + info.setParamInfo(parseParamInfo(mapping.getParamInfo())); + return info; + }).toList(); + } + + private HashMap parseParamInfo(String paramInfo) { + if (StringUtils.isBlank(paramInfo)) { + return new HashMap<>(); + } + return JsonUtils.parseObject(paramInfo, PARAM_INFO_TYPE); + } + + private List getContextProviders(String agentId) { + AgentContextProviderEntity contextEntity = agentContextProviderService.getByAgentId(agentId); + if (contextEntity == null || contextEntity.getContextProviders() == null) { + return Collections.emptyList(); + } + return contextEntity.getContextProviders(); + } + + private List getChangedFields(AgentSnapshotDataDTO current, AgentUpdateDTO pendingUpdate) { + if (pendingUpdate == null) { + return List.of("restore"); + } + + List fields = new ArrayList<>(); + for (AgentSnapshotField field : AgentSnapshotField.values()) { + Object nextValue = field.updateValue(pendingUpdate); + if (nextValue != null && isChanged(field, field.snapshotValue(current), nextValue)) { + fields.add(field.getFieldName()); + } + } + return fields; + } + + private List getChangedFields(AgentSnapshotDataDTO current, AgentSnapshotDataDTO next) { + if (next == null) { + return List.of("restore"); + } + if (current == null) { + current = new AgentSnapshotDataDTO(); + } + + List fields = new ArrayList<>(); + for (AgentSnapshotField field : AgentSnapshotField.values()) { + if (isChanged(field, field.snapshotValue(current), field.snapshotValue(next))) { + fields.add(field.getFieldName()); + } + } + return fields; + } + + private String buildCurrentStateToken(AgentSnapshotDataDTO data) { + Map normalized = new TreeMap<>(); + for (AgentSnapshotField field : AgentSnapshotField.values()) { + normalized.put(field.getFieldName(), normalizeForCompare(field, field.snapshotValue(data))); + } + byte[] payload = JsonUtils.toJsonString(normalized).getBytes(StandardCharsets.UTF_8); + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private boolean isChanged(AgentSnapshotField field, Object current, Object next) { + return !Objects.equals(normalizeForCompare(field, current), normalizeForCompare(field, next)); + } + + @SuppressWarnings("unchecked") + private Object normalizeForCompare(AgentSnapshotField field, Object value) { + return switch (field) { + case FUNCTIONS -> normalizeFunctions((List) value); + case CONTEXT_PROVIDERS -> normalizeJsonList((List) value); + case CORRECT_WORD_FILE_IDS -> normalizeStringList((List) value); + case TAG_NAMES -> normalizeStringList((List) value); + case SUMMARY_MEMORY -> normalizeBlankText(value); + default -> value; + }; + } + + private String normalizeBlankText(Object value) { + if (value == null) { + return ""; + } + String text = String.valueOf(value); + return StringUtils.isBlank(text) ? "" : text; + } + + private Map normalizeFunctions(List functions) { + Map result = new TreeMap<>(); + if (functions == null) { + return result; + } + for (AgentUpdateDTO.FunctionInfo function : functions) { + if (function == null || StringUtils.isBlank(function.getPluginId())) { + continue; + } + result.put(function.getPluginId(), normalizeMap(function.getParamInfo())); + } + return result; + } + + private List normalizeStringList(List values) { + if (values == null) { + return Collections.emptyList(); + } + return values.stream() + .filter(StringUtils::isNotBlank) + .sorted() + .toList(); + } + + private List normalizeJsonList(List values) { + if (values == null) { + return Collections.emptyList(); + } + return values.stream() + .filter(Objects::nonNull) + .map(value -> JsonUtils.toJsonString(normalizeValue(value))) + .toList(); + } + + private Object normalizeValue(Object value) { + return normalizeValue(value, null); + } + + private Object normalizeValue(Object value, String parentKey) { + if (value == null) { + return null; + } + if (value instanceof CharSequence text && shouldTreatAsUrl(parentKey, text.toString())) { + return normalizeUrlForCompare(text.toString(), parentKey); + } + if (value instanceof Map map) { + return normalizeMap(map, parentKey); + } + if (value instanceof List list) { + return list.stream().map(item -> normalizeValue(item, parentKey)).toList(); + } + if (isScalarValue(value)) { + return value; + } + return normalizeMap(JsonUtils.parseObject(JsonUtils.toJsonString(value), OBJECT_MAP_TYPE), parentKey); + } + + private boolean isScalarValue(Object value) { + return value instanceof CharSequence + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date; + } + + private Map normalizeMap(Map map) { + return normalizeMap(map, null); + } + + private Map normalizeMap(Map map, String parentSemanticKey) { + Map result = new TreeMap<>(); + if (map == null) { + return result; + } + String structuredSensitiveKey = getStructuredSensitiveKey(map); + map.forEach((key, value) -> { + if (key != null) { + String keyText = String.valueOf(key); + String semanticKey = resolveUrlSemanticKey(parentSemanticKey, keyText); + if (isSensitiveKey(keyText) + || (structuredSensitiveKey != null && "value".equalsIgnoreCase(keyText))) { + result.put(keyText, SECRET_PLACEHOLDER); + } else if (value instanceof CharSequence text && shouldTreatAsUrl(semanticKey, text.toString())) { + result.put(keyText, normalizeUrlForCompare(text.toString(), semanticKey)); + } else { + result.put(keyText, normalizeValue(value, semanticKey)); + } + } + }); + return result; + } + + private void applyAgentFields(AgentEntity agent, AgentSnapshotDataDTO data) { + for (AgentSnapshotField field : AgentSnapshotField.values()) { + field.applyTo(agent, data); + } + } + + private void validateRestoreParams(AgentEntity agent) { + if (agent == null || StringUtils.isBlank(agent.getLlmModelId())) { + return; + } + + ModelConfigEntity llmModelData = modelConfigService.selectById(agent.getLlmModelId()); + if (llmModelData == null || llmModelData.getConfigJson() == null) { + throw new RenException(ErrorCode.LLM_INTENT_PARAMS_MISMATCH); + } + Object typeValue = llmModelData.getConfigJson().get("type"); + String type = typeValue == null ? "" : typeValue.toString(); + if ("openai".equals(type) || "ollama".equals(type)) { + return; + } + if ("Intent_function_call".equals(agent.getIntentModelId())) { + throw new RenException(ErrorCode.LLM_INTENT_PARAMS_MISMATCH); + } + } + + private void applyMemoryPolicy(AgentEntity agent) { + if (agent == null || StringUtils.isBlank(agent.getMemModelId())) { + return; + } + if (Constant.MEMORY_NO_MEM.equals(agent.getMemModelId())) { + agentChatHistoryService.deleteByAgentId(agent.getId(), true, true); + agent.setSummaryMemory(""); + } else if (Constant.MEMORY_MEM_REPORT_ONLY.equals(agent.getMemModelId())) { + agent.setSummaryMemory(""); + } + } + + private void restoreFunctions(String agentId, List functions) { + agentPluginMappingService.deleteByAgentId(agentId); + if (functions == null || functions.isEmpty()) { + return; + } + List mappings = functions.stream().map(info -> { + AgentPluginMapping mapping = new AgentPluginMapping(); + mapping.setAgentId(agentId); + mapping.setPluginId(info.getPluginId()); + mapping.setParamInfo(JsonUtils.toJsonString(info.getParamInfo())); + return mapping; + }).toList(); + agentPluginMappingService.saveBatch(mappings, IRepository.DEFAULT_BATCH_SIZE); + } + + private void restoreContextProviders(String agentId, + List contextProviders) { + AgentContextProviderEntity entity = new AgentContextProviderEntity(); + entity.setAgentId(agentId); + entity.setContextProviders(nullToEmpty(contextProviders)); + entity.setUpdater(SecurityUser.getUserId()); + entity.setUpdatedAt(new Date()); + agentContextProviderService.saveOrUpdateByAgentId(entity); + } + + private void restoreTags(String agentId, AgentSnapshotDataDTO data) { + List tags = data.getTags(); + if (tags == null || tags.isEmpty()) { + agentTagService.saveAgentTags(agentId, null, nullToEmpty(data.getTagNames())); + return; + } + + agentTagRelationDao.deleteByAgentId(agentId); + List relations = new ArrayList<>(); + Date now = new Date(); + for (int i = 0; i < tags.size(); i++) { + AgentSnapshotTagDTO snapshotTag = tags.get(i); + String tagId = restoreTag(snapshotTag, now); + if (StringUtils.isBlank(tagId)) { + continue; + } + AgentTagRelationEntity relation = new AgentTagRelationEntity(); + relation.setId(UUID.randomUUID().toString().replace("-", "")); + relation.setAgentId(agentId); + relation.setTagId(tagId); + relation.setSort(i); + relation.setCreator(SecurityUser.getUserId()); + relation.setCreatedAt(now); + relation.setUpdater(SecurityUser.getUserId()); + relation.setUpdatedAt(now); + relations.add(relation); + } + if (!relations.isEmpty()) { + agentTagRelationDao.batchInsertRelation(relations); + } + } + + private String restoreTag(AgentSnapshotTagDTO snapshotTag, Date now) { + if (snapshotTag == null || StringUtils.isBlank(snapshotTag.getTagName())) { + return null; + } + + AgentTagEntity tag = null; + if (StringUtils.isNotBlank(snapshotTag.getId())) { + tag = agentTagDao.selectById(snapshotTag.getId()); + } + if (tag == null) { + tag = agentTagDao.selectOne(new QueryWrapper() + .eq("tag_name", snapshotTag.getTagName()) + .last("LIMIT 1")); + } + if (tag != null) { + if (Objects.equals(tag.getDeleted(), 1)) { + // 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("快照引用的标签已被删除,无法恢复,请先重新创建或选择标签"); + } + return tag.getId(); + } + + AgentTagEntity newTag = new AgentTagEntity(); + newTag.setId(UUID.randomUUID().toString().replace("-", "")); + newTag.setTagName(snapshotTag.getTagName()); + newTag.setSort(snapshotTag.getSort() == null ? 0 : snapshotTag.getSort()); + newTag.setDeleted(0); + newTag.setCreator(SecurityUser.getUserId()); + newTag.setCreatedAt(now); + newTag.setUpdater(SecurityUser.getUserId()); + newTag.setUpdatedAt(now); + agentTagDao.insert(newTag); + return newTag.getId(); + } + + private AgentSnapshotVO toVO(AgentSnapshotEntity entity, boolean includeData) { + AgentSnapshotVO vo = new AgentSnapshotVO(); + vo.setId(entity.getId()); + vo.setAgentId(entity.getAgentId()); + vo.setUserId(entity.getUserId()); + vo.setVersionNo(entity.getVersionNo()); + vo.setChangedFields(parseChangedFields(entity.getChangedFields())); + vo.setFieldOrder(AgentSnapshotField.names()); + vo.setSource(entity.getSource()); + vo.setRestoreFromSnapshotId(entity.getRestoreFromSnapshotId()); + vo.setRestoreFromVersionNo(entity.getRestoreFromVersionNo()); + vo.setCreator(entity.getCreator()); + vo.setCreatedAt(entity.getCreatedAt()); + if (includeData) { + vo.setSnapshotData(redactSnapshotData(parseSnapshotData(entity.getSnapshotData()))); + vo.setAfterSnapshotData(redactSnapshotData(getAfterSnapshotData(entity))); + } + return vo; + } + + private AgentSnapshotDataDTO getAfterSnapshotData(AgentSnapshotEntity entity) { + AgentSnapshotEntity nextSnapshot = agentSnapshotDao.selectNextSnapshot(entity.getAgentId(), entity.getVersionNo()); + if (nextSnapshot != null) { + return parseSnapshotData(nextSnapshot.getSnapshotData()); + } + return null; + } + + private List parseChangedFields(String changedFields) { + if (StringUtils.isBlank(changedFields)) { + return Collections.emptyList(); + } + return JsonUtils.parseObject(changedFields, STRING_LIST_TYPE); + } + + /** + * Snapshot payloads outlive the application version that wrote them. Keep + * forward-compatible deserialization local to this persistence boundary so + * unrelated API DTOs retain the project's normal unknown-field validation. + * Unknown fields are intentionally ignored here; they are not restored by + * this older application version. + */ + private AgentSnapshotDataDTO parseSnapshotData(String value) { + if (StringUtils.isBlank(value)) { + return null; + } + try { + return SNAPSHOT_OBJECT_MAPPER.readValue(value, AgentSnapshotDataDTO.class); + } catch (Exception exception) { + throw new RenException("快照数据无法解析"); + } + } + + private AgentSnapshotDataDTO redactSnapshotData(AgentSnapshotDataDTO data) { + if (data == null) { + return null; + } + AgentSnapshotDataDTO copy = parseSnapshotData(JsonUtils.toJsonString(data)); + if (copy.getFunctions() != null) { + copy.getFunctions().forEach(function -> { + if (function != null) { + function.setParamInfo(redactSensitiveMap(function.getParamInfo())); + } + }); + } + if (copy.getContextProviders() != null) { + copy.getContextProviders().forEach(provider -> { + if (provider != null) { + provider.setUrl(redactSensitiveUrl(provider.getUrl(), "url")); + provider.setHeaders(redactSensitiveMap(provider.getHeaders())); + } + }); + } + return copy; + } + + private AgentSnapshotDataDTO preserveCurrentSensitiveValues(AgentSnapshotDataDTO target, AgentSnapshotDataDTO current) { + if (target == null) { + return null; + } + AgentSnapshotDataDTO copy = parseSnapshotData(JsonUtils.toJsonString(target)); + Map currentFunctions = nullToEmpty(current == null ? null : current.getFunctions()) + .stream() + .filter(function -> function != null && StringUtils.isNotBlank(function.getPluginId())) + .collect(Collectors.toMap(AgentUpdateDTO.FunctionInfo::getPluginId, Function.identity(), + (left, right) -> left)); + if (copy.getFunctions() != null) { + copy.getFunctions().forEach(function -> { + if (function == null) { + return; + } + AgentUpdateDTO.FunctionInfo currentFunction = currentFunctions.get(function.getPluginId()); + function.setParamInfo(preserveCurrentSensitiveMap(function.getParamInfo(), + currentFunction == null ? null : currentFunction.getParamInfo())); + }); + } + + copy.setContextProviders(preserveCurrentContextProviders(copy.getContextProviders(), + current == null ? null : current.getContextProviders())); + return copy; + } + + private void validateSensitiveRestoreIsReversible(AgentSnapshotDataDTO current, + AgentSnapshotDataDTO restored) { + try { + // Simulate restoring the automatic pre-restore backup from the proposed + // result. If a current secret-bearing slot disappears, the reverse + // preservation fails because snapshots intentionally never store secrets. + preserveCurrentSensitiveValues(current, restored); + } catch (RenException exception) { + throw new RenException("目标版本会移除无法写入历史的敏感配置,请先手动处理相关密钥后再恢复"); + } + } + + private HashMap redactSensitiveMap(Map map) { + return redactSensitiveMap(map, null); + } + + private HashMap redactSensitiveMap(Map map, String parentSemanticKey) { + HashMap result = new HashMap<>(); + if (map == null) { + return result; + } + String structuredSensitiveKey = getStructuredSensitiveKey(map); + map.forEach((key, value) -> { + if (key != null) { + String keyText = String.valueOf(key); + String semanticKey = resolveUrlSemanticKey(parentSemanticKey, keyText); + if (isSensitiveKey(keyText) + || (structuredSensitiveKey != null && "value".equalsIgnoreCase(keyText))) { + result.put(keyText, SECRET_PLACEHOLDER); + } else if (value instanceof CharSequence text && shouldTreatAsUrl(semanticKey, text.toString())) { + result.put(keyText, redactSensitiveUrl(text.toString(), semanticKey)); + } else { + result.put(keyText, redactSensitiveValue(value, semanticKey)); + } + } + }); + return result; + } + + private Object redactSensitiveValue(Object value) { + return redactSensitiveValue(value, null); + } + + private Object redactSensitiveValue(Object value, String parentKey) { + if (value instanceof CharSequence text && shouldTreatAsUrl(parentKey, text.toString())) { + return redactSensitiveUrl(text.toString(), parentKey); + } + if (value instanceof Map map) { + return redactSensitiveMap(map, parentKey); + } + if (value instanceof List list) { + return list.stream().map(item -> redactSensitiveValue(item, parentKey)).toList(); + } + return value; + } + + private HashMap preserveCurrentSensitiveMap(Map target, Map current) { + return preserveCurrentSensitiveMap(target, current, null); + } + + private HashMap preserveCurrentSensitiveMap(Map target, Map current, + String parentSemanticKey) { + HashMap result = new HashMap<>(); + if (target == null) { + return result; + } + String structuredSensitiveKey = getStructuredSensitiveKey(target); + if (structuredSensitiveKey != null) { + validateStructuredSensitiveDiscriminator(target, current); + } + target.forEach((key, value) -> { + if (key == null) { + return; + } + String keyText = String.valueOf(key); + String semanticKey = resolveUrlSemanticKey(parentSemanticKey, keyText); + Object currentValue = getMapValue(current, keyText); + if (isSensitiveKey(keyText) + || (structuredSensitiveKey != null && "value".equalsIgnoreCase(keyText))) { + result.put(keyText, preserveSensitiveScalar(value, currentValue)); + } else if (value instanceof CharSequence targetUrl + && shouldTreatAsUrl(semanticKey, targetUrl.toString())) { + result.put(keyText, preserveCurrentSensitiveUrl(targetUrl.toString(), + currentValue instanceof CharSequence currentUrl ? currentUrl.toString() : null, semanticKey)); + } else { + result.put(keyText, preserveCurrentSensitiveValue(value, currentValue, semanticKey)); + } + }); + return result; + } + + private Object preserveCurrentSensitiveValue(Object target, Object current) { + return preserveCurrentSensitiveValue(target, current, null); + } + + private Object preserveCurrentSensitiveValue(Object target, Object current, String parentKey) { + if (target instanceof CharSequence targetText && shouldTreatAsUrl(parentKey, targetText.toString())) { + return preserveCurrentSensitiveUrl(targetText.toString(), + current instanceof CharSequence currentText ? currentText.toString() : null, parentKey); + } + if (target instanceof Map targetMap) { + return preserveCurrentSensitiveMap(targetMap, + current instanceof Map currentMap ? currentMap : null, parentKey); + } + if (target instanceof List targetList) { + List currentList = current instanceof List list ? list : Collections.emptyList(); + return preserveCurrentSensitiveList(targetList, currentList, parentKey); + } + return target; + } + + private List preserveCurrentSensitiveList(List target, List current, String parentKey) { + Map> targetByIdentity = indexListByStableIdentity(target, parentKey); + Map> currentByIdentity = indexListByStableIdentity(current, parentKey); + List result = new ArrayList<>(); + for (Object targetItem : target) { + List matchingCurrentItems = stableListIdentities(targetItem, parentKey).stream() + .filter(candidate -> targetByIdentity.getOrDefault(candidate, Collections.emptyList()).size() == 1) + .filter(candidate -> currentByIdentity.getOrDefault(candidate, Collections.emptyList()).size() == 1) + .map(candidate -> currentByIdentity.get(candidate).get(0)) + .distinct() + .toList(); + Object currentItem = matchingCurrentItems.size() == 1 ? matchingCurrentItems.get(0) : null; + if (currentItem == null && containsSensitiveMaterial(targetItem)) { + throw new RenException("快照中的敏感列表项缺少唯一稳定标识,无法安全恢复"); + } + result.add(preserveCurrentSensitiveValue(targetItem, currentItem, parentKey)); + } + return result; + } + + private Map> indexListByStableIdentity(List values, String parentKey) { + Map> result = new HashMap<>(); + for (Object value : values) { + for (String identity : stableListIdentities(value, parentKey)) { + result.computeIfAbsent(identity, ignored -> new ArrayList<>()).add(value); + } + } + return result; + } + + private List stableListIdentities(Object value, String parentKey) { + if (value instanceof CharSequence text && shouldTreatAsUrl(parentKey, text.toString())) { + String identity = normalizeUrlIdentity(text.toString(), parentKey); + return StringUtils.isBlank(identity) ? Collections.emptyList() : List.of("url:" + identity); + } + if (!(value instanceof Map map)) { + return Collections.emptyList(); + } + List identities = new ArrayList<>(); + for (String field : List.of("id", "name", "key", "url")) { + Object identityValue = getMapValue(map, field); + if (identityValue == null || StringUtils.isBlank(String.valueOf(identityValue))) { + continue; + } + String text = String.valueOf(identityValue).trim(); + if ("url".equals(field)) { + text = normalizeUrlIdentity(text, resolveUrlSemanticKey(parentKey, field)); + } else if ("name".equals(field) || "key".equals(field)) { + text = text.toLowerCase(Locale.ROOT); + } + identities.add(field + ":" + text); + } + if (!map.isEmpty()) { + identities.add("fingerprint:" + JsonUtils.toJsonString(normalizeMap(map, parentKey))); + } + return identities; + } + + private Object preserveSensitiveScalar(Object target, Object current) { + if (current != null && !SECRET_PLACEHOLDER.equals(current)) { + return current; + } + throw new RenException("快照敏感值无法与当前配置可靠匹配"); + } + + private Object getMapValue(Map map, String key) { + if (map == null) { + return null; + } + if (map.containsKey(key)) { + return map.get(key); + } + for (Map.Entry entry : map.entrySet()) { + if (entry.getKey() != null && key.equalsIgnoreCase(String.valueOf(entry.getKey()))) { + return entry.getValue(); + } + } + return null; + } + + private List preserveCurrentContextProviders(List target, + List current) { + if (target == null) { + return null; + } + List currentProviders = nullToEmpty(current); + Map> targetByIdentity = indexProvidersByIdentity(target); + Map> currentByIdentity = indexProvidersByIdentity(currentProviders); + + for (ContextProviderDTO targetProvider : target) { + if (targetProvider == null) { + continue; + } + String identity = normalizeUrlIdentity(targetProvider.getUrl()); + ContextProviderDTO currentProvider = null; + if (StringUtils.isNotBlank(identity) + && targetByIdentity.getOrDefault(identity, Collections.emptyList()).size() == 1 + && currentByIdentity.getOrDefault(identity, Collections.emptyList()).size() == 1) { + currentProvider = currentByIdentity.get(identity).get(0); + } else if (hasSensitiveUrlParts(targetProvider.getUrl()) + || containsSensitiveMaterial(targetProvider.getHeaders())) { + throw new RenException("上下文源敏感配置缺少唯一 URL 标识,无法安全恢复"); + } + + if (targetProvider.getUrl() != null) { + targetProvider.setUrl(preserveCurrentSensitiveUrl(targetProvider.getUrl(), + currentProvider == null ? null : currentProvider.getUrl(), "url")); + } + targetProvider.setHeaders(preserveCurrentSensitiveMap(targetProvider.getHeaders(), + currentProvider == null ? null : currentProvider.getHeaders())); + } + return target; + } + + private Map> indexProvidersByIdentity(List providers) { + Map> result = new HashMap<>(); + for (ContextProviderDTO provider : providers) { + if (provider == null) { + continue; + } + String identity = normalizeUrlIdentity(provider.getUrl()); + if (StringUtils.isNotBlank(identity)) { + result.computeIfAbsent(identity, ignored -> new ArrayList<>()).add(provider); + } + } + return result; + } + + private String getStructuredSensitiveKey(Map map) { + if (map == null) { + return null; + } + for (String discriminator : List.of("key", "name")) { + Object value = getMapValue(map, discriminator); + if (value != null && isSensitiveKey(String.valueOf(value))) { + return String.valueOf(value); + } + } + return null; + } + + private void validateStructuredSensitiveDiscriminator(Map target, Map current) { + List targetIdentities = structuredSensitiveDiscriminatorIdentities(target); + List currentIdentities = structuredSensitiveDiscriminatorIdentities(current); + if (targetIdentities.size() != 1 || currentIdentities.size() != 1 + || !Objects.equals(targetIdentities.get(0), currentIdentities.get(0))) { + throw new RenException("快照结构化敏感值的类型标识无法与当前配置唯一匹配"); + } + } + + private List structuredSensitiveDiscriminatorIdentities(Map map) { + if (map == null) { + return Collections.emptyList(); + } + List identities = new ArrayList<>(); + for (String discriminator : List.of("key", "name")) { + Object value = getMapValue(map, discriminator); + if (value == null || !isSensitiveKey(String.valueOf(value))) { + continue; + } + String identity = String.valueOf(value).toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", ""); + if (!identities.contains(identity)) { + identities.add(identity); + } + } + return identities; + } + + private boolean containsSensitiveMaterial(Object value) { + return containsSensitiveMaterial(value, null); + } + + private boolean containsSensitiveMaterial(Object value, String parentKey) { + if (SECRET_PLACEHOLDER.equals(value)) { + return true; + } + if (value instanceof Map map) { + if (getStructuredSensitiveKey(map) != null) { + return true; + } + for (Map.Entry entry : map.entrySet()) { + if (entry.getKey() == null) { + continue; + } + String key = String.valueOf(entry.getKey()); + String semanticKey = resolveUrlSemanticKey(parentKey, key); + if (isSensitiveKey(key) + || (entry.getValue() instanceof CharSequence text + && shouldTreatAsUrl(semanticKey, text.toString()) + && hasSensitiveUrlParts(text.toString(), semanticKey)) + || containsSensitiveMaterial(entry.getValue(), semanticKey)) { + return true; + } + } + return false; + } + if (value instanceof List list) { + return list.stream().anyMatch(item -> containsSensitiveMaterial(item, parentKey)); + } + if (value instanceof CharSequence text && shouldTreatAsUrl(parentKey, text.toString())) { + return hasSensitiveUrlParts(text.toString(), parentKey); + } + return false; + } + + private boolean isUrlKey(String key) { + String normalized = StringUtils.defaultString(key).toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", ""); + return normalized.endsWith("url") + || normalized.endsWith("uri") + || normalized.endsWith("endpoint") + || normalized.endsWith("webhook"); + } + + private boolean shouldTreatAsUrl(String key, String value) { + return isUrlKey(key) || isWebhookSemanticKey(key) || looksLikeUrl(value); + } + + private String resolveUrlSemanticKey(String parentSemanticKey, String childKey) { + if (isWebhookSemanticKey(childKey)) { + return childKey; + } + if (isWebhookSemanticKey(parentSemanticKey)) { + // Keep the concrete child name for URL detection while carrying the + // enclosing webhook capability semantics through arbitrary wrapper maps. + return StringUtils.isBlank(childKey) + ? parentSemanticKey + : parentSemanticKey + "." + childKey; + } + return childKey; + } + + private boolean looksLikeUrl(String value) { + String text = StringUtils.defaultString(value); + if (text.startsWith("//")) { + int pathStart = text.indexOf('/', 2); + String authority = pathStart < 0 ? text.substring(2) : text.substring(2, pathStart); + return StringUtils.isNotBlank(authority) && authority.chars().noneMatch(Character::isWhitespace); + } + int schemeEnd = text.indexOf("://"); + if (schemeEnd <= 0 || !Character.isLetter(text.charAt(0))) { + return false; + } + for (int i = 1; i < schemeEnd; i++) { + char character = text.charAt(i); + if (!Character.isLetterOrDigit(character) + && character != '+' + && character != '-' + && character != '.') { + return false; + } + } + return true; + } + + private String normalizeUrlForCompare(String value) { + return normalizeUrlForCompare(value, null); + } + + private String normalizeUrlForCompare(String value, String semanticKey) { + return redactSensitiveUrl(value, semanticKey); + } + + private String redactSensitiveUrl(String value) { + return redactSensitiveUrl(value, null); + } + + private String redactSensitiveUrl(String value, String semanticKey) { + if (value == null) { + return null; + } + SensitiveUrlParts parts = splitSensitiveUrl(value); + return buildSensitiveUrl(analyzeSensitiveUrlPath(parts.base(), semanticKey).redactedBase(), + parts.userInfo() == null ? null : SECRET_PLACEHOLDER, + redactSensitiveUrlParameters(parts.query()), + redactSensitiveUrlFragment(parts.fragment())); + } + + private String preserveCurrentSensitiveUrl(String target, String current) { + return preserveCurrentSensitiveUrl(target, current, null); + } + + private String preserveCurrentSensitiveUrl(String target, String current, String semanticKey) { + if (target == null) { + return null; + } + SensitiveUrlParts targetParts = splitSensitiveUrl(target); + SensitiveUrlParts currentParts = splitSensitiveUrl(StringUtils.defaultString(current)); + SensitivePathAnalysis targetPath = analyzeSensitiveUrlPath(targetParts.base(), semanticKey); + boolean forceCurrentGenericMarker = targetPath.slots().stream() + .anyMatch(slot -> slot.identity().startsWith("webhook-suffix:")); + SensitivePathAnalysis currentPath = analyzeSensitiveUrlPath(currentParts.base(), semanticKey, + forceCurrentGenericMarker); + boolean copiesSensitiveComponent = targetParts.userInfo() != null + || !targetPath.slots().isEmpty() + || containsSensitiveUrlParameter(targetParts.query()) + || (targetParts.fragment() != null + && (!isStructuredUrlComponent(targetParts.fragment()) + || containsSensitiveUrlParameter(targetParts.fragment()))); + if (copiesSensitiveComponent && !Objects.equals(targetPath.redactedBase(), currentPath.redactedBase())) { + throw new RenException("快照 URL 敏感信息无法与当前配置的公开地址标识匹配"); + } + 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 中仍包含脱敏占位符,无法安全恢复"); + } + return result; + } + + private String preserveUrlComponent(String target, String current) { + if (target == null) { + return null; + } + if (current == null || current.contains(SECRET_PLACEHOLDER)) { + throw new RenException("快照 URL 中的敏感信息无法与当前配置可靠匹配"); + } + return current; + } + + private String redactSensitiveUrlParameters(String value) { + if (value == null) { + return null; + } + return buildUrlParameters(parseUrlParameters(value).stream() + .map(parameter -> isSensitiveUrlParameter(parameter) + ? new UrlParameter(parameter.rawKey(), SECRET_PLACEHOLDER, parameter.hasEquals()) + : parameter) + .toList()); + } + + private String redactSensitiveUrlFragment(String value) { + if (value == null) { + return null; + } + return isStructuredUrlComponent(value) + ? redactSensitiveUrlParameters(value) + : SECRET_PLACEHOLDER; + } + + private String preserveSensitiveUrlParameters(String target, String current) { + if (target == null) { + return null; + } + List targetParameters = parseUrlParameters(target); + List currentParameters = parseUrlParameters(StringUtils.defaultString(current)); + Map> targetSensitiveParameters = indexSensitiveUrlParameters(targetParameters); + Map> currentSensitiveParameters = indexSensitiveUrlParameters(currentParameters); + List result = new ArrayList<>(); + + for (UrlParameter targetParameter : targetParameters) { + if (!isSensitiveUrlParameter(targetParameter)) { + result.add(targetParameter); + continue; + } + String identity = normalizeUrlParameterName(targetParameter.rawKey()); + List matchingTargets = targetSensitiveParameters.getOrDefault(identity, + Collections.emptyList()); + List matchingCurrent = currentSensitiveParameters.getOrDefault(identity, + Collections.emptyList()); + if (matchingTargets.size() != 1 || matchingCurrent.size() != 1) { + throw new RenException("快照 URL 中的敏感参数无法与当前配置唯一匹配"); + } + UrlParameter currentParameter = matchingCurrent.get(0); + if (currentParameter.rawValue().contains(SECRET_PLACEHOLDER)) { + throw new RenException("快照 URL 中的敏感信息无法与当前配置可靠匹配"); + } + result.add(new UrlParameter(targetParameter.rawKey(), currentParameter.rawValue(), + currentParameter.hasEquals())); + } + return buildUrlParameters(result); + } + + private String preserveSensitiveUrlFragment(String target, String current) { + if (target == null) { + return null; + } + return isStructuredUrlComponent(target) + ? preserveSensitiveUrlParameters(target, current) + : preserveUrlComponent(target, current); + } + + private Map> indexSensitiveUrlParameters(List parameters) { + Map> result = new HashMap<>(); + for (UrlParameter parameter : parameters) { + if (isSensitiveUrlParameter(parameter)) { + result.computeIfAbsent(normalizeUrlParameterName(parameter.rawKey()), ignored -> new ArrayList<>()) + .add(parameter); + } + } + return result; + } + + private List parseUrlParameters(String value) { + List result = new ArrayList<>(); + for (String part : StringUtils.defaultString(value).split("&", -1)) { + int equalsIndex = part.indexOf('='); + if (equalsIndex < 0) { + result.add(new UrlParameter(part, "", false)); + } else { + result.add(new UrlParameter(part.substring(0, equalsIndex), part.substring(equalsIndex + 1), true)); + } + } + return result; + } + + private String buildUrlParameters(List parameters) { + return parameters.stream() + .map(parameter -> parameter.rawKey() + + (parameter.hasEquals() ? "=" + parameter.rawValue() : "")) + .collect(Collectors.joining("&")); + } + + private boolean isSensitiveUrlParameter(UrlParameter parameter) { + String decodedName = decodeUrlParameterName(parameter.rawKey()); + String normalized = decodedName.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", ""); + return isSensitiveKey(decodedName) + || normalized.equals("key") + || normalized.equals("sig") + || normalized.equals("signature") + || normalized.equals("xamzsignature") + || normalized.equals("xgoogsignature") + || normalized.equals("sas"); + } + + private String normalizeUrlParameterName(String value) { + return decodeUrlParameterName(value).toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", ""); + } + + private String decodeUrlParameterName(String value) { + try { + return URLDecoder.decode(StringUtils.defaultString(value), StandardCharsets.UTF_8); + } catch (IllegalArgumentException ignored) { + return StringUtils.defaultString(value); + } + } + + private boolean isStructuredUrlComponent(String value) { + return value != null && (value.contains("=") || value.contains("&")); + } + + private boolean hasSensitiveUrlParts(String value) { + return hasSensitiveUrlParts(value, null); + } + + private boolean hasSensitiveUrlParts(String value, String semanticKey) { + if (StringUtils.isBlank(value)) { + return false; + } + SensitiveUrlParts parts = splitSensitiveUrl(value); + return parts.userInfo() != null + || !analyzeSensitiveUrlPath(parts.base(), semanticKey).slots().isEmpty() + || containsSensitiveUrlParameter(parts.query()) + || (parts.fragment() != null + && (!isStructuredUrlComponent(parts.fragment()) + || containsSensitiveUrlParameter(parts.fragment()))); + } + + private boolean containsSensitiveUrlParameter(String value) { + return value != null && parseUrlParameters(value).stream().anyMatch(this::isSensitiveUrlParameter); + } + + private String normalizeUrlIdentity(String value) { + return normalizeUrlIdentity(value, null); + } + + private String normalizeUrlIdentity(String value, String semanticKey) { + if (StringUtils.isBlank(value)) { + return ""; + } + SensitiveUrlParts parts = splitSensitiveUrl(value); + return analyzeSensitiveUrlPath(parts.base(), semanticKey).redactedBase(); + } + + private String preserveSensitiveUrlPath(String targetBase, String currentBase, String semanticKey) { + SensitivePathAnalysis target = analyzeSensitiveUrlPath(targetBase, semanticKey); + if (target.slots().isEmpty()) { + return targetBase; + } + boolean forceCurrentGenericMarker = target.slots().stream() + .anyMatch(slot -> slot.identity().startsWith("webhook-suffix:")); + SensitivePathAnalysis current = analyzeSensitiveUrlPath(currentBase, semanticKey, forceCurrentGenericMarker); + if (!Objects.equals(target.redactedBase(), current.redactedBase()) + || target.slots().size() != current.slots().size()) { + throw new RenException("快照 URL 路径敏感信息无法与当前配置的公开标识唯一匹配"); + } + + Map> currentSlots = current.slots().stream() + .collect(Collectors.groupingBy(SensitivePathSlot::identity)); + Map replacements = new HashMap<>(); + for (SensitivePathSlot targetSlot : target.slots()) { + List matches = currentSlots.getOrDefault(targetSlot.identity(), Collections.emptyList()); + 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 路径敏感信息无法与当前配置可靠匹配"); + } + if (replacements.put(targetSlot.identity(), matches.get(0)) != null) { + throw new RenException("快照 URL 路径敏感信息存在歧义,无法安全恢复"); + } + } + return rebuildSensitivePath(target, replacements); + } + + private SensitivePathAnalysis analyzeSensitiveUrlPath(String base, String semanticKey) { + return analyzeSensitiveUrlPath(base, semanticKey, false); + } + + private SensitivePathAnalysis analyzeSensitiveUrlPath(String base, String semanticKey, + boolean forceGenericMarker) { + UrlPathParts pathParts = splitUrlPath(base); + if (pathParts == null || pathParts.segments().isEmpty()) { + return new SensitivePathAnalysis(base, base, Collections.emptyList()); + } + List segments = pathParts.segments(); + List slots = new ArrayList<>(); + List claimedMarkers = new ArrayList<>(); + + if (isSlackHooksHost(pathParts.host())) { + for (int i = 0; i + 3 < segments.size(); i++) { + if ("services".equalsIgnoreCase(segments.get(i)) + && allPathSegmentsPresent(segments, i + 1, i + 4)) { + addSensitivePathSlot(slots, new SensitivePathSlot("slack:" + i, i + 3, i + 4, "", + List.of(segments.get(i + 3)))); + } + } + } + + if (isDiscordHost(pathParts.host())) { + for (int i = 0; i + 2 < segments.size(); i++) { + if ("webhooks".equalsIgnoreCase(segments.get(i)) + && isDiscordWebhookPrefix(segments, i) + && allPathSegmentsPresent(segments, i + 1, i + 3)) { + addSensitivePathSlot(slots, new SensitivePathSlot("discord:" + i, i + 2, i + 3, "", + List.of(segments.get(i + 2)))); + claimedMarkers.add(i); + } + } + } + + if (isTelegramHost(pathParts.host())) { + for (int i = 0; i < segments.size(); i++) { + String segment = segments.get(i); + int colon = segment.indexOf(':'); + if (segment.regionMatches(true, 0, "bot", 0, 3) + && colon > 3 && colon < segment.length() - 1) { + String publicPrefix = segment.substring(0, colon + 1); + addSensitivePathSlot(slots, new SensitivePathSlot("telegram:" + i + ":" + publicPrefix, + i, i + 1, publicPrefix, List.of(segment.substring(colon + 1)))); + } + } + } + + for (int i = 0; i < segments.size(); i++) { + if (!isWebhookPathMarker(segments.get(i)) || claimedMarkers.contains(i) || i + 1 >= segments.size()) { + continue; + } + int suffixEnd = segments.size(); + while (suffixEnd > i + 1 && StringUtils.isBlank(segments.get(suffixEnd - 1))) { + suffixEnd--; + } + List capabilitySuffix = new ArrayList<>(segments.subList(i + 1, suffixEnd)); + if (capabilitySuffix.isEmpty()) { + continue; + } + if (capabilitySuffix.stream().anyMatch(StringUtils::isBlank)) { + continue; + } + if (!forceGenericMarker + && !isHighConfidenceWebhookCapability(pathParts, semanticKey, capabilitySuffix)) { + continue; + } + addSensitivePathSlot(slots, new SensitivePathSlot("webhook-suffix:" + i, i + 1, suffixEnd, "", + capabilitySuffix)); + break; + } + + if (slots.isEmpty() && isWebhookSemanticKey(semanticKey)) { + int lastSegment = segments.size() - 1; + while (lastSegment >= 0 && StringUtils.isBlank(segments.get(lastSegment))) { + lastSegment--; + } + if (lastSegment >= 0 && StringUtils.isNotBlank(segments.get(lastSegment))) { + addSensitivePathSlot(slots, new SensitivePathSlot("webhook-key:" + lastSegment, + lastSegment, lastSegment + 1, "", List.of(segments.get(lastSegment)))); + } + } + + if (slots.isEmpty()) { + return new SensitivePathAnalysis(base, base, Collections.emptyList()); + } + SensitivePathAnalysis analysis = new SensitivePathAnalysis(base, null, slots); + return new SensitivePathAnalysis(base, rebuildSensitivePath(analysis, Collections.emptyMap()), slots); + } + + private String rebuildSensitivePath(SensitivePathAnalysis analysis, + Map replacements) { + UrlPathParts pathParts = splitUrlPath(analysis.originalBase()); + if (pathParts == null) { + return analysis.originalBase(); + } + Map slotsByStart = analysis.slots().stream() + .collect(Collectors.toMap(SensitivePathSlot::startIndex, Function.identity(), (left, right) -> left)); + List result = new ArrayList<>(); + for (int i = 0; i < pathParts.segments().size();) { + SensitivePathSlot slot = slotsByStart.get(i); + if (slot == null) { + result.add(pathParts.segments().get(i)); + i++; + continue; + } + SensitivePathSlot replacement = replacements.get(slot.identity()); + if (replacement == null) { + result.add(slot.publicPrefix() + SECRET_PLACEHOLDER); + } else if (StringUtils.isNotEmpty(slot.publicPrefix())) { + result.add(slot.publicPrefix() + replacement.secretSegments().get(0)); + } else { + result.addAll(replacement.secretSegments()); + } + i = slot.endIndex(); + } + return pathParts.prefix() + String.join("/", result); + } + + private UrlPathParts splitUrlPath(String base) { + String value = StringUtils.defaultString(base); + int schemeIndex = value.indexOf("://"); + if (schemeIndex < 0 && !value.startsWith("/")) { + if (StringUtils.isBlank(value) || value.chars().anyMatch(Character::isWhitespace)) { + return null; + } + return new UrlPathParts("", + new ArrayList<>(List.of(value.split("/", -1))), ""); + } + if (schemeIndex < 0 && !value.startsWith("//")) { + return new UrlPathParts("", + new ArrayList<>(List.of(value.split("/", -1))), ""); + } + int authorityStart = schemeIndex < 0 ? 2 : schemeIndex + 3; + int pathStart = value.indexOf('/', authorityStart); + String authority = pathStart < 0 ? value.substring(authorityStart) : value.substring(authorityStart, pathStart); + String host = normalizeAuthorityHost(authority); + if (pathStart < 0) { + return new UrlPathParts(value, Collections.emptyList(), host); + } + return new UrlPathParts(value.substring(0, pathStart), + new ArrayList<>(List.of(value.substring(pathStart).split("/", -1))), host); + } + + private String normalizeAuthorityHost(String authority) { + String value = StringUtils.defaultString(authority).toLowerCase(Locale.ROOT); + if (value.startsWith("[")) { + int closingBracket = value.indexOf(']'); + return closingBracket < 0 ? value : value.substring(0, closingBracket + 1); + } + int portSeparator = value.lastIndexOf(':'); + return portSeparator < 0 ? value : value.substring(0, portSeparator); + } + + private boolean isSlackHooksHost(String host) { + return "hooks.slack.com".equals(host) || "hooks.slack-gov.com".equals(host); + } + + private boolean isDiscordHost(String host) { + return "discord.com".equals(host) || host.endsWith(".discord.com") + || "discordapp.com".equals(host) || host.endsWith(".discordapp.com"); + } + + private boolean isTelegramHost(String host) { + return "api.telegram.org".equals(host); + } + + private boolean isDiscordWebhookPrefix(List segments, int markerIndex) { + if (markerIndex >= 1 && "api".equalsIgnoreCase(segments.get(markerIndex - 1))) { + return true; + } + return markerIndex >= 2 + && "api".equalsIgnoreCase(segments.get(markerIndex - 2)) + && isVersionPathSegment(segments.get(markerIndex - 1)); + } + + private boolean isVersionPathSegment(String value) { + String normalized = StringUtils.defaultString(value).toLowerCase(Locale.ROOT); + return normalized.length() > 1 && normalized.charAt(0) == 'v' + && normalized.substring(1).chars().allMatch(Character::isDigit); + } + + private boolean isWebhookPathMarker(String value) { + String normalized = StringUtils.defaultString(value).toLowerCase(Locale.ROOT); + return normalized.equals("webhook") || normalized.equals("webhooks") + || normalized.equals("hook") || normalized.equals("hooks"); + } + + private boolean isHighConfidenceWebhookCapability(UrlPathParts pathParts, String semanticKey, + List capabilitySuffix) { + return isWebhookSemanticKey(semanticKey) + || hasWebhookHostLabel(pathParts.host()) + || isSlackHooksHost(pathParts.host()) + || isDiscordHost(pathParts.host()) + || isTelegramHost(pathParts.host()) + || capabilitySuffix.stream().anyMatch(this::looksLikeCapabilitySecret); + } + + private boolean hasWebhookHostLabel(String host) { + return List.of(StringUtils.defaultString(host).split("\\.")).stream() + .anyMatch(this::isWebhookPathMarker); + } + + private boolean looksLikeCapabilitySecret(String value) { + String text = StringUtils.defaultString(value); + String normalized = text.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", ""); + if (normalized.contains("secret") + || normalized.contains("token") + || normalized.contains("capability") + || normalized.contains("credential") + || normalized.contains("signature") + || normalized.contains("apikey") + || normalized.contains("accesskey") + || normalized.contains("authkey")) { + return true; + } + if (text.length() < 20) { + return false; + } + boolean hasLetter = text.chars().anyMatch(Character::isLetter); + boolean hasDigit = text.chars().anyMatch(Character::isDigit); + boolean hasSymbol = text.chars().anyMatch(character -> !Character.isLetterOrDigit(character)); + long distinctCharacters = text.chars().distinct().count(); + return distinctCharacters >= 10 + && ((hasLetter && hasDigit) || (hasLetter && hasSymbol) || (hasDigit && hasSymbol)); + } + + private boolean isWebhookSemanticKey(String value) { + String normalized = StringUtils.defaultString(value).toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", ""); + return normalized.contains("webhook") || normalized.equals("hook") || normalized.equals("hooks") + || normalized.endsWith("hook") || normalized.endsWith("hooks"); + } + + private boolean allPathSegmentsPresent(List segments, int fromInclusive, int toExclusive) { + return segments.subList(fromInclusive, toExclusive).stream().noneMatch(StringUtils::isBlank); + } + + private void addSensitivePathSlot(List slots, SensitivePathSlot candidate) { + boolean overlaps = slots.stream().anyMatch(slot -> candidate.startIndex() < slot.endIndex() + && slot.startIndex() < candidate.endIndex()); + if (!overlaps) { + slots.add(candidate); + } + } + + private SensitiveUrlParts splitSensitiveUrl(String value) { + String remaining = StringUtils.defaultString(value); + String fragment = null; + int fragmentIndex = remaining.indexOf('#'); + if (fragmentIndex >= 0) { + fragment = remaining.substring(fragmentIndex + 1); + remaining = remaining.substring(0, fragmentIndex); + } + String query = null; + int queryIndex = remaining.indexOf('?'); + if (queryIndex >= 0) { + query = remaining.substring(queryIndex + 1); + remaining = remaining.substring(0, queryIndex); + } + + String userInfo = null; + int schemeIndex = remaining.indexOf("://"); + int authorityStart = schemeIndex >= 0 + ? schemeIndex + 3 + : remaining.startsWith("//") ? 2 : -1; + if (authorityStart >= 0) { + int pathStart = remaining.indexOf('/', authorityStart); + if (pathStart < 0) { + pathStart = remaining.length(); + } + String authority = remaining.substring(authorityStart, pathStart); + int userInfoEnd = authority.lastIndexOf('@'); + if (userInfoEnd >= 0) { + userInfo = authority.substring(0, userInfoEnd); + remaining = remaining.substring(0, authorityStart) + + authority.substring(userInfoEnd + 1) + + remaining.substring(pathStart); + } + } + return new SensitiveUrlParts(remaining, userInfo, query, fragment); + } + + private String buildSensitiveUrl(String base, String userInfo, String query, String fragment) { + String result = StringUtils.defaultString(base); + if (userInfo != null) { + int schemeIndex = result.indexOf("://"); + int authorityStart = schemeIndex >= 0 + ? schemeIndex + 3 + : result.startsWith("//") ? 2 : -1; + if (authorityStart < 0) { + throw new RenException("带用户凭据的 URL 格式无效,无法安全恢复"); + } + result = result.substring(0, authorityStart) + userInfo + "@" + result.substring(authorityStart); + } + if (query != null) { + result += "?" + query; + } + if (fragment != null) { + result += "#" + fragment; + } + return result; + } + + private record SensitiveUrlParts(String base, String userInfo, String query, String fragment) { + } + + private record UrlPathParts(String prefix, List segments, String host) { + } + + private record SensitivePathAnalysis(String originalBase, String redactedBase, + List slots) { + } + + private record SensitivePathSlot(String identity, int startIndex, int endIndex, + String publicPrefix, List secretSegments) { + } + + private record UrlParameter(String rawKey, String rawValue, boolean hasEquals) { + } + + private boolean isSensitiveKey(String key) { + String normalized = StringUtils.defaultString(key).toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", ""); + return normalized.equals("authorization") + || normalized.contains("authorization") + || normalized.contains("authentication") + || normalized.equals("auth") + || normalized.endsWith("auth") + || normalized.equals("cookie") + || normalized.equals("cookie2") + || normalized.equals("setcookie") + || normalized.equals("setcookie2") + || normalized.endsWith("cookie") + || normalized.equals("session") + || normalized.endsWith("session") + || normalized.contains("sessionid") + || normalized.contains("sessionkey") + || normalized.contains("sessiontoken") + || normalized.contains("sessioncookie") + || normalized.endsWith("sessid") + || normalized.equals("token") + || normalized.endsWith("token") + || normalized.contains("apikey") + || normalized.contains("appkey") + || normalized.contains("accesskey") + || normalized.contains("subscriptionkey") + || normalized.contains("privatekey") + || normalized.contains("password") + || normalized.contains("passwd") + || normalized.contains("secret") + || normalized.contains("credential"); + } + + private List nullToEmpty(List list) { + return list == null ? Collections.emptyList() : list; + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTagServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTagServiceImpl.java index 2bcee73a0..518864840 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTagServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTagServiceImpl.java @@ -133,7 +133,7 @@ public class AgentTagServiceImpl extends BaseServiceImpl tagIdEntities = baseDao.selectBatchIds(tagIds); + List tagIdEntities = baseDao.selectByIds(tagIds); for (AgentTagEntity tag : tagIdEntities) { if (tag != null && (currentTagNames.contains(tag.getTagName()) || newTagNames.contains(tag.getTagName()))) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java index 20c1d6cbf..5371f6c37 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java @@ -4,8 +4,8 @@ import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; - +import com.baomidou.mybatisplus.spring.repository.CrudRepository; + import xiaozhi.modules.agent.dao.AgentTemplateDao; import xiaozhi.modules.agent.entity.AgentTemplateEntity; import xiaozhi.modules.agent.service.AgentTemplateService; @@ -21,7 +21,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; * @createDate 2025-03-22 11:48:18 */ @Service -public class AgentTemplateServiceImpl extends ServiceImpl +public class AgentTemplateServiceImpl extends CrudRepository implements AgentTemplateService { /** diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentVoicePrintServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentVoicePrintServiceImpl.java index d075089cc..cbff4f854 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentVoicePrintServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentVoicePrintServiceImpl.java @@ -22,7 +22,7 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.baomidou.mybatisplus.spring.repository.CrudRepository; import lombok.extern.slf4j.Slf4j; import xiaozhi.common.constant.Constant; @@ -46,7 +46,7 @@ import xiaozhi.modules.sys.service.SysParamsService; */ @Service @Slf4j -public class AgentVoicePrintServiceImpl extends ServiceImpl +public class AgentVoicePrintServiceImpl extends CrudRepository implements AgentVoicePrintService { private final AgentChatAudioService agentChatAudioService; private final RestTemplate restTemplate; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/typehandler/ContextProviderListTypeHandler.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/typehandler/ContextProviderListTypeHandler.java new file mode 100644 index 000000000..4f7012338 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/typehandler/ContextProviderListTypeHandler.java @@ -0,0 +1,59 @@ +package xiaozhi.modules.agent.typehandler; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import com.fasterxml.jackson.core.type.TypeReference; + +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.modules.agent.dto.ContextProviderDTO; + +/** + * JSON type handler for context providers. + * + *

Do not extend MyBatis-Plus {@code AbstractJsonTypeHandler}: its constructor and JSON handler + * contract changed in MyBatis-Plus 3.5.6. {@link BaseTypeHandler} is part of MyBatis itself and + * keeps this handler compatible with both 3.5.5 and newer MyBatis-Plus releases.

+ */ +public class ContextProviderListTypeHandler extends BaseTypeHandler> { + private static final TypeReference> CONTEXT_PROVIDER_LIST_TYPE = new TypeReference<>() { + }; + + @Override + public void setNonNullParameter(PreparedStatement ps, int i, List parameter, + JdbcType jdbcType) throws SQLException { + ps.setString(i, JsonUtils.toJsonString(parameter)); + } + + @Override + public List getNullableResult(ResultSet rs, String columnName) throws SQLException { + return parseNullable(rs.getString(columnName)); + } + + @Override + public List getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + return parseNullable(rs.getString(columnIndex)); + } + + @Override + public List getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + return parseNullable(cs.getString(columnIndex)); + } + + private List parseNullable(String json) { + if (StringUtils.isBlank(json)) { + return null; + } + List providers = JsonUtils.parseObject(json, CONTEXT_PROVIDER_LIST_TYPE); + return providers == null ? Collections.emptyList() : providers; + } + +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentInfoVO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentInfoVO.java index 04d13f1e9..2ea5c9b48 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentInfoVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentInfoVO.java @@ -1,7 +1,5 @@ package xiaozhi.modules.agent.vo; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import lombok.EqualsAndHashCode; @@ -28,4 +26,7 @@ public class AgentInfoVO extends AgentEntity @Schema(description = "替换词文件ID列表") private List correctWordFileIds; + + @Schema(description = "当前配置版本号") + private Integer currentVersionNo; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentSnapshotVO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentSnapshotVO.java new file mode 100644 index 000000000..d5a44e1da --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentSnapshotVO.java @@ -0,0 +1,34 @@ +package xiaozhi.modules.agent.vo; + +import java.util.Date; +import java.util.List; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import xiaozhi.modules.agent.dto.AgentSnapshotDataDTO; + +@Data +@Schema(description = "智能体配置快照") +public class AgentSnapshotVO { + private String id; + private String agentId; + @Schema(description = "所属用户ID,表示该快照归属的智能体所有者") + private Long userId; + private Integer versionNo; + private List changedFields; + private List fieldOrder; + private String source; + @Schema(description = "恢复来源快照ID,仅恢复结果版本有值") + private String restoreFromSnapshotId; + @Schema(description = "恢复来源版本号,仅恢复结果版本有值") + private Integer restoreFromVersionNo; + @Schema(description = "创建者,表示触发本次快照写入的操作人") + private Long creator; + private Date createdAt; + private AgentSnapshotDataDTO snapshotData; + private AgentSnapshotDataDTO afterSnapshotData; + @Schema(description = "恢复预览对应的脱敏当前配置,仅详情接口有值") + private AgentSnapshotDataDTO currentSnapshotData; + @Schema(description = "恢复预览对应的当前配置状态指纹,仅详情接口有值") + private String currentStateToken; +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/service/ConfigService.java b/main/manager-api/src/main/java/xiaozhi/modules/config/service/ConfigService.java index e234e22dc..81f19853e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/service/ConfigService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/service/ConfigService.java @@ -10,7 +10,7 @@ public interface ConfigService { * @param isCache 是否缓存 * @return 配置信息 */ - Object getConfig(Boolean isCache); + Map getConfig(Boolean isCache); /** * 获取智能体模型配置 @@ -28,4 +28,4 @@ public interface ConfigService { * @return 替换词列表,格式如 ["模板1|模板01", "模板2|模板02"] */ List getCorrectWords(String macAddress); -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java index 886e904af..0bd0c7cbd 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java @@ -65,12 +65,12 @@ public class ConfigServiceImpl implements ConfigService { private final CorrectWordFileService correctWordFileService; @Override - public Object getConfig(Boolean isCache) { + public Map getConfig(Boolean isCache) { if (isCache) { // Check Redis first. Object cachedConfig = redisUtils.get(RedisKeys.getServerConfigKey()); if (cachedConfig != null) { - return cachedConfig; + return JsonUtils.toStringObjectMap(cachedConfig); } } @@ -277,10 +277,10 @@ public class ConfigServiceImpl implements ConfigService { // Walk every key except the final one. for (int i = 0; i < keys.length - 1; i++) { String key = keys[i]; - if (!current.containsKey(key)) { - current.put(key, new HashMap()); - } - current = (Map) current.get(key); + Object nestedConfig = current.computeIfAbsent(key, ignored -> new HashMap()); + Map nestedMap = JsonUtils.toStringObjectMap(nestedConfig); + current.put(key, nestedMap); + current = nestedMap; } // Handle the final key. diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java index 6f5a1f996..f8a9b7025 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java @@ -8,6 +8,7 @@ import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.BeanUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -124,7 +125,9 @@ public class DeviceController { return new Result().error("设备不存在"); } BeanUtils.copyProperties(deviceUpdateDTO, entity); - deviceService.updateById(entity); + if (!deviceService.updateById(entity)) { + return new Result().error(ErrorCode.UPDATE_DATA_FAILED); + } return new Result(); } @@ -174,20 +177,26 @@ public class DeviceController { return new Result().ok(deviceAddressBookService.getAddressBookList(macAddress)); } - @GetMapping("/address-book/lookup") - @Operation(summary = "根据昵称查找目标设备") - public Result> lookupByNickname(String callerMac, String nickname) { - Map result = deviceAddressBookService.lookupByNickname(callerMac, nickname); + @GetMapping("/address-book/call") + @Operation(summary = "根据昵称发起呼叫") + public Result> callByNickname(String callerMac, String nickname, + @RequestParam(required = false, defaultValue = "false") boolean answer) { + Map result = deviceAddressBookService.callByNickname(callerMac, nickname, answer); if (result == null) { - return new Result>().error("未找到对应设备"); + return new Result>().error("未找到对应设备"); } - return new Result>().ok(result); + return new Result>().ok(result); } @PutMapping("/address-book/alias") @Operation(summary = "更新设备通讯录别名") @RequiresPermissions("sys:role:normal") public Result 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().error("无权限操作该设备"); + } deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), dto.getAlias(), null); return new Result(); } @@ -196,14 +205,12 @@ public class DeviceController { @Operation(summary = "更新设备通讯录权限") @RequiresPermissions("sys:role:normal") public Result 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().error("无权限操作该设备"); + } deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), null, dto.getHasPermission()); return new Result(); } - - @GetMapping("/call/forward") - @Operation(summary = "转发呼叫请求到网关") - public Result> forwardCallRequest(String callerMac, String targetMac, String callerNickname) { - Map result = deviceService.forwardCallRequest(callerMac, targetMac, callerNickname); - return new Result>().ok(result); - } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAMagController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAMagController.java index 2bd98efc6..77fed2896 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAMagController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAMagController.java @@ -5,8 +5,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Map; import java.util.Optional; @@ -31,6 +29,7 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; +import cn.hutool.crypto.digest.DigestUtil; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameters; @@ -329,13 +328,7 @@ public class OTAMagController { return result; } - private String calculateMD5(MultipartFile file) throws IOException, NoSuchAlgorithmException { - MessageDigest md = MessageDigest.getInstance("MD5"); - byte[] digest = md.digest(file.getBytes()); - StringBuilder sb = new StringBuilder(); - for (byte b : digest) { - sb.append(String.format("%02x", b)); - } - return sb.toString(); + private String calculateMD5(MultipartFile file) throws IOException { + return DigestUtil.md5Hex(file.getBytes()); } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceAddressBookDao.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceAddressBookDao.java index 43601f6bd..fc7d6428b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceAddressBookDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceAddressBookDao.java @@ -12,6 +12,11 @@ import xiaozhi.modules.device.entity.DeviceAddressBookEntity; @Mapper public interface DeviceAddressBookDao extends BaseMapper { + /** + * 新增设备通讯录记录 + */ + int insertAddressBook(DeviceAddressBookEntity entity); + /** * 获取设备通讯录列表 */ @@ -26,4 +31,9 @@ public interface DeviceAddressBookDao extends BaseMapper macAddresses); +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceAddressBookService.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceAddressBookService.java index 8d91fc5b9..d0b383940 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceAddressBookService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceAddressBookService.java @@ -38,10 +38,15 @@ public interface DeviceAddressBookService { void refreshCache(); /** - * 根据昵称查找目标设备信息 + * 根据昵称发起呼叫 * @param callerMac 主叫方MAC地址 * @param nickname 被叫方昵称 - * @return {targetMac: 目标MAC, callerNickname: 目标如何称呼主叫方} + * @param isAnswer 是否为接听模式(跳过权限检查) */ - Map lookupByNickname(String callerMac, String nickname); + Map callByNickname(String callerMac, String nickname, boolean isAnswer); + + /** + * 批量删除设备相关的通讯录记录 + */ + void deleteByMacAddresses(List macAddresses); } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java index 29aac1360..b663ceb60 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java @@ -138,10 +138,4 @@ public interface DeviceService extends BaseService { */ Object callDeviceTool(String deviceId, String toolName, Map arguments); - /** - * 转发呼叫请求到网关 - * @return 网关响应 {status, message} - */ - Map forwardCallRequest(String callerMac, String targetMac, String callerNickname); - -} \ No newline at end of file + } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImpl.java index 4f663897d..ff2e43176 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImpl.java @@ -1,20 +1,26 @@ package xiaozhi.modules.device.service.impl; +import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; +import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import cn.hutool.json.JSONUtil; +import xiaozhi.common.constant.Constant; import xiaozhi.common.redis.RedisKeys; import xiaozhi.common.redis.RedisUtils; import xiaozhi.modules.device.dao.DeviceAddressBookDao; import xiaozhi.modules.device.entity.DeviceAddressBookEntity; import xiaozhi.modules.device.service.DeviceAddressBookService; import xiaozhi.modules.device.service.DeviceService; +import xiaozhi.modules.sys.service.SysParamsService; @Service public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { @@ -22,12 +28,14 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { private final DeviceAddressBookDao deviceAddressBookDao; private final RedisUtils redisUtils; private final DeviceService deviceService; + private final SysParamsService sysParamsService; public DeviceAddressBookServiceImpl(DeviceAddressBookDao deviceAddressBookDao, RedisUtils redisUtils, - DeviceService deviceService) { + @Lazy DeviceService deviceService, SysParamsService sysParamsService) { this.deviceAddressBookDao = deviceAddressBookDao; this.redisUtils = redisUtils; this.deviceService = deviceService; + this.sysParamsService = sysParamsService; } @Override @@ -47,33 +55,46 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { } @Override - public Map lookupByNickname(String callerMac, String nickname) { + public Map callByNickname(String callerMac, String nickname, boolean isAnswer) { Map> allBooks = getAllAddressBooks(); + + if (isAnswer) { + return postToMqtt("/api/call/accept", Map.of("mac", callerMac), "接听"); + } + + // 主动呼叫模式 Map callerBook = allBooks.get(callerMac.toLowerCase()); if (callerBook == null) { - return null; + return errorResult("未找到备注为'" + nickname + "'的设备"); } - // 从缓存获取 targetMac,格式: "mac|permission" String targetMacWithPerm = callerBook.get(nickname); if (targetMacWithPerm == null) { - return null; + return errorResult("未找到备注为'" + nickname + "'的设备"); } - // 解析 targetMac 和 permission String[] parts = targetMacWithPerm.split("\\|"); String targetMac = parts[0]; boolean hasPermission = parts.length > 1 && "1".equals(parts[1]); - Map targetBook = allBooks.get(targetMac.toLowerCase()); - if (targetBook == null) { - return null; + if (!hasPermission) { + return errorResult("呼叫失败,您没有权限呼叫该设备"); } - // 检查双向关系:目标设备是否也添加了主叫方为联系人 - String callerNickname = targetBook.get(callerMac.toLowerCase()); - Map result = new HashMap<>(); - result.put("targetMac", targetMac); - result.put("callerNickname", callerNickname); - result.put("hasPermission", hasPermission ? "true" : "false"); - return result; + + // 获取目标设备如何称呼主叫方 + Map targetBook = allBooks.get(targetMac.toLowerCase()); + String callerNickname = null; + if (targetBook != null) { + callerNickname = targetBook.get(callerMac.toLowerCase()); + } + if (StringUtils.isBlank(callerNickname)) { + callerNickname = deviceService.getDeviceByMacAddress(callerMac).getAlias(); + if (StringUtils.isBlank(callerNickname)) { + callerNickname = formatMacAsDeviceName(callerMac); + } + } + + return postToMqtt("/api/call/request", + Map.of("caller_mac", callerMac, "target_mac", targetMac, "caller_nickname", callerNickname), + "呼叫"); } @Override @@ -81,43 +102,44 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { Map> result = new HashMap<>(); List allRecords = deviceAddressBookDao.selectList(null); Map reverseMap = new HashMap<>(); - Map permissionMap = new HashMap<>(); + for (DeviceAddressBookEntity entity : allRecords) { String macA = entity.getMacAddress().toLowerCase(); String macB = entity.getTargetMac().toLowerCase(); String alias = entity.getAlias(); Boolean hasPermission = entity.getHasPermission(); + + // 构建正向映射: A对B的映射 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的称呼 if (alias != null && !alias.isEmpty()) { - // 反向记录: (macB, macA) = B对A的称呼 reverseMap.put(macB + ":" + macA, alias); } - // 记录 A 对 B 是否有权限呼叫 - permissionMap.put(macA + ":" + macB, hasPermission != null && hasPermission); } + + // 构建反向映射: B对A的映射 macA -> nickname for (DeviceAddressBookEntity entity : allRecords) { String macA = entity.getMacAddress().toLowerCase(); String macB = entity.getTargetMac().toLowerCase(); - String aliasAtoB = entity.getAlias(); - result.computeIfAbsent(macA, k -> new HashMap<>()); - result.computeIfAbsent(macB, k -> new HashMap<>()); - if (aliasAtoB != null && !aliasAtoB.isEmpty()) { - // A对B的映射: nickname -> macB|permission - Boolean perm = entity.getHasPermission(); - String permStr = (perm != null && perm) ? "1" : "0"; - result.get(macA).put(aliasAtoB, macB + "|" + permStr); - } - // B对A的映射: macA -> nickname(查反向记录) String aliasBtoA = reverseMap.get(macA + ":" + macB); if (aliasBtoA != null && !aliasBtoA.isEmpty()) { + result.computeIfAbsent(macB, k -> new HashMap<>()); result.get(macB).put(macA, aliasBtoA); } } + redisUtils.set(RedisKeys.getAddressBookKey(), result); } @Override public void updateAlias(String macAddress, String targetMac, String alias) { - deviceAddressBookDao.updateAlias(macAddress, targetMac, alias); + String finalAlias = generateUniqueAlias(macAddress, targetMac, alias); + deviceAddressBookDao.updateAlias(macAddress, targetMac, finalAlias); refreshCache(); } @@ -132,20 +154,23 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { QueryWrapper wrapper = new QueryWrapper<>(); wrapper.eq("mac_address", macAddress).eq("target_mac", targetMac); DeviceAddressBookEntity record = deviceAddressBookDao.selectOne(wrapper); + System.out.println("saveOrUpdate - mac=" + macAddress + ", targetMac=" + targetMac + ", alias=" + alias + ", record=" + (record == null ? "null" : "not null")); if (record == null) { DeviceAddressBookEntity entity = new DeviceAddressBookEntity(); entity.setMacAddress(macAddress); entity.setTargetMac(targetMac); - // 如果 alias 为空,就用默认使用设备名称 + // 如果 alias 为空,就默认使用设备名称 if (StringUtils.isBlank(alias)) { alias = deviceService.getDeviceByMacAddress(targetMac).getAlias(); } + // 检查重名 + alias = generateUniqueAlias(macAddress, targetMac, alias); entity.setAlias(alias); entity.setHasPermission(hasPermission); - deviceAddressBookDao.insert(entity); + deviceAddressBookDao.insertAddressBook(entity); } else { if (alias != null) { - deviceAddressBookDao.updateAlias(macAddress, targetMac, alias); + updateAlias(macAddress, targetMac, alias); } if (hasPermission != null) { deviceAddressBookDao.updatePermission(macAddress, targetMac, hasPermission); @@ -153,4 +178,81 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { } refreshCache(); } -} \ No newline at end of file + + @Override + public void deleteByMacAddresses(List macAddresses) { + if (macAddresses == null || macAddresses.isEmpty()) { + return; + } + deviceAddressBookDao.deleteByMacAddresses(macAddresses); + refreshCache(); + } + + private Map errorResult(String message) { + Map result = new HashMap<>(); + result.put("status", "error"); + result.put("message", message); + return result; + } + + private Map postToMqtt(String path, Map body, String action) { + Map result = new HashMap<>(); + result.put("status", "error"); + + String mqttGatewayUrl = sysParamsService.getValue("server.mqtt_manager_api", true); + String mqttSignatureKey = sysParamsService.getValue(Constant.SERVER_MQTT_SECRET, true); + + if (StringUtils.isBlank(mqttGatewayUrl) || "null".equals(mqttGatewayUrl) + || MqttGatewayAuthorization.isMissingSignatureKey(mqttSignatureKey)) { + result.put("message", action + "失败,网关配置缺失"); + return result; + } + + try { + String url = "http://" + mqttGatewayUrl + path; + String response = MqttGatewayAuthorization.postJson( + url, + JSONUtil.toJsonStr(body), + mqttSignatureKey, + Instant.now(), + 5000); + + if (StringUtils.isNotBlank(response)) { + Map gwResult = JSONUtil.parseObj(response); + result.put("status", gwResult.get("status")); + result.put("message", gwResult.get("message")); + } + return result; + } catch (Exception e) { + result.put("message", action + "失败,请稍后再试"); + return result; + } + } + + private String formatMacAsDeviceName(String mac) { + if (StringUtils.isBlank(mac) || mac.length() < 2) { + return mac; + } + String lastTwo = mac.substring(mac.length() - 2); + return "尾号为" + lastTwo + "的设备"; + } + + private String generateUniqueAlias(String macAddress, String targetMac, String alias) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("mac_address", macAddress); + List existing = deviceAddressBookDao.selectList(wrapper); + List existNames = existing.stream() + .map(DeviceAddressBookEntity::getAlias) + .filter(a -> a != null && !a.isEmpty()) + .collect(Collectors.toList()); + if (!existNames.contains(alias)) { + return alias; + } + int suffix = 1; + String newAlias; + while (existNames.contains(newAlias = alias + suffix)) { + suffix++; + } + return newAlias; + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java index 66f2a616d..e5a262736 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java @@ -6,6 +6,7 @@ import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.util.ArrayList; import java.util.Base64; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -30,15 +31,10 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; -import cn.hutool.core.date.DatePattern; -import cn.hutool.core.date.DateUtil; +import cn.hutool.core.collection.CollUtil; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.StrUtil; -import cn.hutool.crypto.digest.DigestUtil; -import cn.hutool.http.ContentType; -import cn.hutool.http.Header; -import cn.hutool.http.HttpRequest; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; @@ -55,7 +51,7 @@ import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.user.UserDetail; import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.DateUtils; -import xiaozhi.common.utils.ToolUtil; +import xiaozhi.common.utils.JsonUtils; import xiaozhi.modules.device.dao.DeviceDao; import xiaozhi.modules.device.dto.DeviceManualAddDTO; import xiaozhi.modules.device.dto.DevicePageUserDTO; @@ -63,6 +59,7 @@ import xiaozhi.modules.device.dto.DeviceReportReqDTO; import xiaozhi.modules.device.dto.DeviceReportRespDTO; import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.entity.OtaEntity; +import xiaozhi.modules.device.service.DeviceAddressBookService; import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.device.service.OtaService; import xiaozhi.modules.device.vo.UserShowDeviceListVO; @@ -80,6 +77,7 @@ public class DeviceServiceImpl extends BaseServiceImpl private final SysParamsService sysParamsService; private final RedisUtils redisUtils; private final OtaService otaService; + private final DeviceAddressBookService deviceAddressBookService; @Async public void updateDeviceConnectionInfo(String agentId, String deviceId, String appVersion) { @@ -105,15 +103,15 @@ public class DeviceServiceImpl extends BaseServiceImpl throw new RenException(ErrorCode.ACTIVATION_CODE_EMPTY); } String deviceKey = RedisKeys.getOtaActivationCode(activationCode); - Object cacheDeviceId = redisUtils.get(deviceKey); - if (ToolUtil.isEmpty(cacheDeviceId)) { + String cacheDeviceId = (String) redisUtils.get(deviceKey); + if (StringUtils.isBlank(cacheDeviceId)) { throw new RenException(ErrorCode.ACTIVATION_CODE_ERROR); } - String deviceId = (String) cacheDeviceId; + String deviceId = cacheDeviceId; String safeDeviceId = deviceId.replace(":", "_").toLowerCase(); String cacheDeviceKey = RedisKeys.getOtaDeviceActivationInfo(safeDeviceId); - Map cacheMap = (Map) redisUtils.get(cacheDeviceKey); - if (ToolUtil.isEmpty(cacheMap)) { + Map cacheMap = JsonUtils.toStringObjectMap(redisUtils.get(cacheDeviceKey)); + if (MapUtil.isEmpty(cacheMap)) { throw new RenException(ErrorCode.ACTIVATION_CODE_ERROR); } String cachedCode = (String) cacheMap.get("activation_code"); @@ -302,15 +300,21 @@ public class DeviceServiceImpl extends BaseServiceImpl @Override public List getUserDeviceList(Long userId, String agentId) { List devices = getUserDevices(userId, agentId); - return devices.stream().map(device -> { - UserShowDeviceListVO vo = ConvertUtils.sourceToTarget(device, UserShowDeviceListVO.class); - vo.setDeviceType(device.getBoard()); - // 设置UTC时间戳供前端使用时区转换 - if (device.getLastConnectedAt() != null) { - vo.setLastConnectedAtTimestamp(device.getLastConnectedAt().getTime()); - } - return vo; - }).toList(); + return devices.stream().map(this::toUserShowDeviceListVO).toList(); + } + + private UserShowDeviceListVO toUserShowDeviceListVO(DeviceEntity device) { + UserShowDeviceListVO vo = ConvertUtils.sourceToTarget(device, UserShowDeviceListVO.class); + vo.setDeviceType(device.getBoard()); + vo.setBoard(device.getBoard()); + vo.setAutoUpdate(device.getAutoUpdate()); + vo.setCreateDateTimestamp(toTimestamp(device.getCreateDate())); + vo.setLastConnectedAtTimestamp(toTimestamp(device.getLastConnectedAt())); + return vo; + } + + private Long toTimestamp(Date date) { + return date == null ? null : date.getTime(); } @Override @@ -320,6 +324,7 @@ public class DeviceServiceImpl extends BaseServiceImpl if (device == null) { return; } + String macAddress = device.getMacAddress(); if (StringUtils.isNotBlank(device.getAgentId())) { // Clear the cached agent device count. redisUtils.delete(RedisKeys.getAgentDeviceCountById(device.getAgentId())); @@ -329,6 +334,9 @@ public class DeviceServiceImpl extends BaseServiceImpl wrapper.eq("user_id", userId); wrapper.eq("id", deviceId); baseDao.delete(wrapper); + + // 删除设备相关的通讯录权限记录 + deviceAddressBookService.deleteByMacAddresses(Collections.singletonList(macAddress)); } @Override @@ -347,9 +355,23 @@ public class DeviceServiceImpl extends BaseServiceImpl @Override public void deleteByAgentId(String agentId) { + // 先查询该智能体下的所有设备,获取mac地址用于删除通讯录记录 + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("agent_id", agentId); + List devices = baseDao.selectList(queryWrapper); + + // 删除设备 UpdateWrapper wrapper = new UpdateWrapper<>(); wrapper.eq("agent_id", agentId); baseDao.delete(wrapper); + + // 批量删除这些设备相关的所有通讯录权限记录 + if (!devices.isEmpty()) { + List macAddresses = devices.stream() + .map(DeviceEntity::getMacAddress) + .collect(Collectors.toList()); + deviceAddressBookService.deleteByMacAddresses(macAddresses); + } } @Override @@ -370,12 +392,6 @@ public class DeviceServiceImpl extends BaseServiceImpl vo.setRecentChatTime(DateUtils.getShortTime(device.getUpdateDate())); sysUserUtilService.assignUsername(device.getUserId(), vo::setBindUserName); - vo.setDeviceType(device.getBoard()); - vo.setBoard(device.getBoard()); - // 设置UTC时间戳供前端使用时区转换 - if (device.getLastConnectedAt() != null) { - vo.setLastConnectedAtTimestamp(device.getLastConnectedAt().getTime()); - } return vo; }).toList(); // Return the paged result. @@ -405,7 +421,7 @@ public class DeviceServiceImpl extends BaseServiceImpl public String geCodeByDeviceId(String deviceId) { String dataKey = getDeviceCacheKey(deviceId); - Map cacheMap = (Map) redisUtils.get(dataKey); + Map cacheMap = JsonUtils.toStringObjectMap(redisUtils.get(dataKey)); if (cacheMap != null && cacheMap.containsKey("activation_code")) { String cachedCode = (String) cacheMap.get("activation_code"); return cachedCode; @@ -893,70 +909,4 @@ public class DeviceServiceImpl extends BaseServiceImpl } return null; } - - @Override - public Map forwardCallRequest(String callerMac, String targetMac, String callerNickname) { - Map result = new HashMap<>(); - result.put("status", "error"); - result.put("message", "网关配置缺失"); - - // 从系统参数获取网关配置 - String mqttGatewayUrl = sysParamsService.getValue("server.mqtt_manager_api", true); - String mqttSignatureKey = sysParamsService.getValue("server.mqtt_signature_key", true); - - if (StringUtils.isBlank(mqttGatewayUrl) || "null".equals(mqttGatewayUrl)) { - log.error("MQTT网关地址未配置"); - result.put("message", "MQTT网关地址未配置"); - return result; - } - if (StringUtils.isBlank(mqttSignatureKey) || "null".equals(mqttSignatureKey)) { - log.error("MQTT签名密钥未配置"); - result.put("message", "MQTT签名密钥未配置"); - return result; - } - - // 生成token: SHA256(date + secret) - String dateStr = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date()); - try { - java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256"); - byte[] hash = md.digest((dateStr + mqttSignatureKey).getBytes(StandardCharsets.UTF_8)); - StringBuilder hexString = new StringBuilder(); - for (byte b : hash) { - String hex = Integer.toHexString(0xff & b); - if (hex.length() == 1) { - hexString.append('0'); - } - hexString.append(hex); - } - String token = hexString.toString(); - - // 构建请求体 - Map body = new HashMap<>(); - body.put("caller_mac", callerMac); - body.put("target_mac", targetMac); - body.put("caller_nickname", callerNickname); - - // 发送请求并获取响应 - String url = "http://" + mqttGatewayUrl + "/api/call/request"; - String response = cn.hutool.http.HttpRequest.post(url) - .header("Authorization", "Bearer " + token) - .header("Content-Type", "application/json") - .body(JSONUtil.toJsonStr(body)) - .timeout(5000) - .execute() - .body(); - - // 解析网关响应 - if (StringUtils.isNotBlank(response)) { - Map gwResult = JSONUtil.parseObj(response); - result.put("status", gwResult.get("status")); - result.put("message", gwResult.get("message")); - } - return result; - } catch (Exception e) { - log.error("转发呼叫请求失败: {}", e.getMessage()); - result.put("message", "呼叫请求转发失败: " + e.getMessage()); - return result; - } - } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/MqttGatewayAuthorization.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/MqttGatewayAuthorization.java new file mode 100644 index 000000000..f165419a1 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/MqttGatewayAuthorization.java @@ -0,0 +1,111 @@ +package xiaozhi.modules.device.service.impl; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneOffset; +import java.util.List; +import java.util.function.Function; + +import org.apache.commons.lang3.StringUtils; + +import cn.hutool.crypto.digest.DigestUtil; +import cn.hutool.http.ContentType; +import cn.hutool.http.Header; +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; + +final class MqttGatewayAuthorization { + + private static final int HTTP_UNAUTHORIZED = 401; + private static final int DEFAULT_TIMEOUT_MILLIS = 10000; + + private MqttGatewayAuthorization() { + } + + static String postJson(String url, String jsonBody, String signatureKey, Instant now) { + return postJson(url, jsonBody, signatureKey, now, DEFAULT_TIMEOUT_MILLIS); + } + + static String postJson(String url, String jsonBody, String signatureKey, Instant now, int timeoutMillis) { + GatewayResponse response = executeWithDateFallback( + signatureKey, + now, + token -> executeRequest(url, jsonBody, token, timeoutMillis)); + + if (response.statusCode() < 200 || response.statusCode() >= 300) { + throw new GatewayRequestException( + "MQTT Gateway request failed with HTTP status " + response.statusCode(), + response.statusCode()); + } + return response.body(); + } + + static List generateDailyTokens(String signatureKey, Instant now) { + if (isMissingSignatureKey(signatureKey)) { + throw new GatewayRequestException("MQTT Gateway signature key is empty", null); + } + + LocalDate utcDate = now.atZone(ZoneOffset.UTC).toLocalDate(); + return List.of( + tokenFor(utcDate, signatureKey), + tokenFor(utcDate.minusDays(1), signatureKey), + tokenFor(utcDate.plusDays(1), signatureKey)); + } + + static GatewayResponse executeWithDateFallback(String signatureKey, Instant now, + Function requestExecutor) { + GatewayResponse lastAuthenticationFailure = null; + for (String token : generateDailyTokens(signatureKey, now)) { + GatewayResponse response = requestExecutor.apply(token); + if (!isAuthenticationFailure(response.statusCode())) { + return response; + } + lastAuthenticationFailure = response; + } + + Integer statusCode = lastAuthenticationFailure == null ? null : lastAuthenticationFailure.statusCode(); + throw new GatewayRequestException( + "MQTT Gateway rejected all daily authorization tokens" + + (statusCode == null ? "" : " (HTTP " + statusCode + ")"), + statusCode); + } + + private static String tokenFor(LocalDate date, String signatureKey) { + return DigestUtil.sha256Hex(date + signatureKey); + } + + private static boolean isAuthenticationFailure(int statusCode) { + return statusCode == HTTP_UNAUTHORIZED; + } + + static boolean isMissingSignatureKey(String signatureKey) { + return StringUtils.isBlank(signatureKey) || "null".equalsIgnoreCase(signatureKey.trim()); + } + + private static GatewayResponse executeRequest(String url, String jsonBody, String token, int timeoutMillis) { + try (HttpResponse response = HttpRequest.post(url) + .header(Header.CONTENT_TYPE, ContentType.JSON.getValue()) + .header(Header.AUTHORIZATION, "Bearer " + token) + .body(jsonBody) + .timeout(timeoutMillis) + .execute()) { + return new GatewayResponse(response.getStatus(), response.body()); + } + } + + record GatewayResponse(int statusCode, String body) { + } + + static final class GatewayRequestException extends RuntimeException { + private final Integer statusCode; + + GatewayRequestException(String message, Integer statusCode) { + super(message); + this.statusCode = statusCode; + } + + Integer statusCode() { + return statusCode; + } + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java index 856d00145..1f43402aa 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java @@ -56,7 +56,7 @@ public class OtaServiceImpl extends BaseServiceImpl implement @Override public void delete(String[] ids) { - baseDao.deleteBatchIds(Arrays.asList(ids)); + baseDao.deleteByIds(Arrays.asList(ids)); } @Override @@ -82,4 +82,4 @@ public class OtaServiceImpl extends BaseServiceImpl implement .last("LIMIT 1"); return baseDao.selectOne(wrapper); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/vo/UserShowDeviceListVO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/vo/UserShowDeviceListVO.java index a2582c28a..b00a16865 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/vo/UserShowDeviceListVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/vo/UserShowDeviceListVO.java @@ -32,17 +32,20 @@ public class UserShowDeviceListVO { @Schema(description = "设备别名") private String alias; - @Schema(description = "开启OTA") - private Integer otaUpgrade; + @Schema(description = "自动更新开关(0关闭/1开启)") + private Integer autoUpdate; @Schema(description = "最近对话时间") private String recentChatTime; - @Schema(description = "最后连接时间(UTC毫秒)") + @Schema(description = "最后连接时间戳(毫秒)", type = "string", example = "1783689702000") private Long lastConnectedAtTimestamp; - @Schema(description = "绑定时间") + @Schema(description = "绑定时间戳(毫秒)", type = "string", example = "1783689702000") + private Long createDateTimestamp; + + @Schema(description = "绑定时间(兼容字段,请使用 createDateTimestamp)", deprecated = true) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "UTC") private Date createDate; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeBaseController.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeBaseController.java index ade6bc704..f6821b5d3 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeBaseController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeBaseController.java @@ -15,6 +15,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import cn.hutool.core.collection.CollUtil; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; @@ -23,7 +24,6 @@ import xiaozhi.common.exception.ErrorCode; import xiaozhi.common.exception.RenException; import xiaozhi.common.page.PageData; import xiaozhi.common.utils.Result; -import xiaozhi.common.utils.ToolUtil; import xiaozhi.modules.knowledge.dto.KnowledgeBaseDTO; import xiaozhi.modules.knowledge.service.KnowledgeBaseService; import xiaozhi.modules.knowledge.service.KnowledgeManagerService; @@ -140,7 +140,7 @@ public class KnowledgeBaseController { List idList = Arrays.asList(ids.split(",")); List knowledgeBaseDTOs = Optional.ofNullable(knowledgeBaseService.getByDatasetIdList(idList)) .orElseGet(ArrayList::new); - if (ToolUtil.isNotEmpty(knowledgeBaseDTOs)) { + if (CollUtil.isNotEmpty(knowledgeBaseDTOs)) { knowledgeBaseDTOs.forEach(item -> { // Users may only delete knowledge bases they created. if (item.getCreator() == null || !item.getCreator().equals(currentUserId)) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/impl/RAGFlowAdapter.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/impl/RAGFlowAdapter.java index f66623f7e..ae6f913a3 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/impl/RAGFlowAdapter.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/rag/impl/RAGFlowAdapter.java @@ -149,8 +149,8 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { log.info("=== [RAGFlow] 获取文档列表: datasetId={} ===", datasetId); // 使用 Jackson 将 DTO 转为 Map 作为查询参数 - @SuppressWarnings("unchecked") - Map params = objectMapper.convertValue(req, Map.class); + Map params = objectMapper.convertValue(req, new TypeReference>() { + }); Map response = getClient().get("/api/v1/datasets/" + datasetId + "/documents", params); @@ -174,13 +174,12 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { .pageSize(1) .build(); - @SuppressWarnings("unchecked") - Map params = objectMapper.convertValue(req, Map.class); + Map params = objectMapper.convertValue(req, new TypeReference>() { + }); Map response = getClient().get("/api/v1/datasets/" + datasetId + "/documents", params); Object dataObj = response.get("data"); - if (dataObj instanceof Map) { - Map dataMap = (Map) dataObj; + if (dataObj instanceof Map dataMap) { List documents = (List) dataMap.get("docs"); if (documents != null && !documents.isEmpty()) { return objectMapper.convertValue(documents.get(0), DocumentDTO.InfoVO.class); @@ -567,8 +566,8 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { return new PageData<>(new ArrayList<>(), 0); } - Map dataMap = (Map) dataObj; - List> documents = (List>) dataMap.get("docs"); + Map dataMap = Map.class.cast(dataObj); + List documents = List.class.cast(dataMap.get("docs")); if (documents == null || documents.isEmpty()) { // RAGFlow 明确返回了空文档列表,这是合法的"真空" return new PageData<>(new ArrayList<>(), 0); @@ -679,7 +678,9 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { dto.setChunkMethod(info.getChunkMethod().name().toLowerCase()); } if (info.getParserConfig() != null) { - dto.setParserConfig(objectMapper.convertValue(info.getParserConfig(), Map.class)); + dto.setParserConfig(objectMapper.convertValue(info.getParserConfig(), + new TypeReference>() { + })); } return dto; @@ -717,4 +718,4 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { return !multipartFile.isEmpty(); } } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java index 005d2adf2..b89ae982f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java @@ -36,6 +36,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { static { THINKING_DISABLED_DOMAINS.put("aliyuncs.com", Map.of("enable_thinking", false)); Map thinkingDisabled = Map.of("thinking", Map.of("type", "disabled")); + THINKING_DISABLED_DOMAINS.put("deepseek.com", thinkingDisabled); THINKING_DISABLED_DOMAINS.put("bigmodel.cn", thinkingDisabled); THINKING_DISABLED_DOMAINS.put("moonshot.cn", thinkingDisabled); THINKING_DISABLED_DOMAINS.put("volces.com", thinkingDisabled); @@ -116,13 +117,11 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { Map requestBody = new HashMap<>(); requestBody.put("model", model != null ? model : "gpt-3.5-turbo"); - Map[] messages = new Map[1]; Map message = new HashMap<>(); message.put("role", "user"); message.put("content", prompt); - messages[0] = message; - requestBody.put("messages", messages); + requestBody.put("messages", List.of(message)); requestBody.put("temperature", temperature != null ? temperature : 0.7); requestBody.put("max_tokens", maxTokens != null ? maxTokens : 2000); @@ -212,13 +211,11 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { Map requestBody = new HashMap<>(); requestBody.put("model", model != null ? model : "gpt-3.5-turbo"); - Map[] messages = new Map[1]; Map message = new HashMap<>(); message.put("role", "user"); message.put("content", prompt); - messages[0] = message; - requestBody.put("messages", messages); + requestBody.put("messages", List.of(message)); requestBody.put("temperature", 0.2); requestBody.put("max_tokens", 2000); @@ -368,13 +365,11 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { Map requestBody = new HashMap<>(); requestBody.put("model", model != null ? model : "gpt-3.5-turbo"); - Map[] messages = new Map[1]; Map message = new HashMap<>(); message.put("role", "user"); message.put("content", prompt); - messages[0] = message; - requestBody.put("messages", messages); + requestBody.put("messages", List.of(message)); requestBody.put("temperature", 0.3); requestBody.put("max_tokens", 50); @@ -422,4 +417,4 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { return null; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java index 0f43eb95a..007e8abf9 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java @@ -374,7 +374,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl ids) { - if (modelProviderDao.deleteBatchIds(ids) == 0) { + if (modelProviderDao.deleteByIds(ids) == 0) { throw new RenException(ErrorCode.DELETE_DATA_FAILED); } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java index 1255e9a76..4766063c2 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java @@ -4,16 +4,19 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; -import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.mgt.SessionManager; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.config.ShiroFilterConfiguration; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; +import org.apache.shiro.web.mgt.WebSecurityManager; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.context.annotation.Role; import jakarta.servlet.Filter; import xiaozhi.modules.security.oauth2.Oauth2Filter; @@ -39,7 +42,7 @@ public class ShiroConfig { } @Bean("securityManager") - public SecurityManager securityManager(Oauth2Realm oAuth2Realm, SessionManager sessionManager) { + public WebSecurityManager securityManager(Oauth2Realm oAuth2Realm, SessionManager sessionManager) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(oAuth2Realm); securityManager.setSessionManager(sessionManager); @@ -48,7 +51,8 @@ public class ShiroConfig { } @Bean("shiroFilter") - public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager, SysParamsService sysParamsService) { + public static ShiroFilterFactoryBean shirFilter(@Lazy WebSecurityManager securityManager, + @Lazy SysParamsService sysParamsService) { ShiroFilterConfiguration config = new ShiroFilterConfiguration(); config.setFilterOncePerRequest(true); @@ -87,8 +91,7 @@ public class ShiroConfig { filterMap.put("/user/retrieve-password", "anon"); // Use server service filter for config path filterMap.put("/config/**", "server"); - filterMap.put("/device/address-book/lookup", "server"); - filterMap.put("/device/call/forward", "server"); + filterMap.put("/device/address-book/call", "server"); filterMap.put("/agent/chat-history/report", "server"); filterMap.put("/agent/chat-history/download/**", "anon"); filterMap.put("/agent/chat-summary/**", "server"); @@ -102,12 +105,14 @@ public class ShiroConfig { } @Bean("lifecycleBeanPostProcessor") - public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { + public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean - public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + public static AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor( + @Lazy WebSecurityManager securityManager) { AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); advisor.setSecurityManager(securityManager); return advisor; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java index d24306fd3..21422b045 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java @@ -1,8 +1,7 @@ package xiaozhi.modules.security.service.impl; import java.io.IOException; -import java.util.Random; -import java.util.concurrent.TimeUnit; +import java.time.Duration; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; @@ -13,6 +12,7 @@ import com.google.common.cache.CacheBuilder; import com.wf.captcha.SpecCaptcha; import com.wf.captcha.base.Captcha; +import cn.hutool.core.util.RandomUtil; import jakarta.annotation.Resource; import jakarta.servlet.http.HttpServletResponse; import xiaozhi.common.constant.Constant; @@ -41,7 +41,7 @@ public class CaptchaServiceImpl implements CaptchaService { * Local Cache expires in 5 minutes */ Cache localCache = CacheBuilder.newBuilder().maximumSize(1000) - .expireAfterAccess(5, TimeUnit.MINUTES).build(); + .expireAfterAccess(Duration.ofMinutes(5)).build(); @Override public void create(HttpServletResponse response, String uuid) throws IOException { @@ -113,7 +113,7 @@ public class CaptchaServiceImpl implements CaptchaService { } String key = RedisKeys.getSMSValidateCodeKey(phone); - String validateCodes = generateValidateCode(6); + String validateCodes = RandomUtil.randomNumbers(6); // Set verification code setCache(key, validateCodes); @@ -180,4 +180,4 @@ public class CaptchaServiceImpl implements CaptchaService { } return captcha; } -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysUserDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysUserDTO.java index abf3c073b..161781c0a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysUserDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysUserDTO.java @@ -84,4 +84,4 @@ public class SysUserDTO implements Serializable { @Schema(description = "Department name") private String deptName; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImpl.java index d66cce572..955fc5b71 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImpl.java @@ -12,6 +12,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; +import cn.hutool.core.collection.CollUtil; import lombok.AllArgsConstructor; import xiaozhi.common.exception.RenException; import xiaozhi.common.exception.ErrorCode; @@ -20,7 +21,7 @@ import xiaozhi.common.redis.RedisKeys; import xiaozhi.common.redis.RedisUtils; import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.utils.ConvertUtils; -import xiaozhi.common.utils.ToolUtil; +import xiaozhi.common.utils.JsonUtils; import xiaozhi.modules.sys.dao.SysDictDataDao; import xiaozhi.modules.sys.dao.SysUserDao; import xiaozhi.modules.sys.dto.SysDictDataDTO; @@ -170,7 +171,7 @@ public class SysDictDataServiceImpl extends BaseServiceImpl cachedData = (List) redisUtils.get(key); + List cachedData = JsonUtils.toList(redisUtils.get(key), SysDictDataItem.class); if (cachedData != null) { return cachedData; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictTypeServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictTypeServiceImpl.java index 9d1b6a024..c5fa6b6ff 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictTypeServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictTypeServiceImpl.java @@ -151,4 +151,4 @@ public class SysDictTypeServiceImpl extends BaseServiceImpl currentFeatures = (Map) currentMap.get("features"); - Map newFeatures = (Map) newMap.get("features"); + Map currentFeatures = Map.class.cast(currentMap.get("features")); + Map newFeatures = Map.class.cast(newMap.get("features")); if (currentFeatures != null && newFeatures != null) { Object currentAddressBookObj = currentFeatures.get("addressBook"); @@ -308,16 +308,14 @@ public class SysParamsServiceImpl extends BaseServiceImpl currentAddressBook = (Map) currentAddressBookObj; - currentEnabled = currentAddressBook.get("enabled") != null - ? (Boolean) currentAddressBook.get("enabled") : false; + if (currentAddressBookObj instanceof Map currentAddressBook) { + Object enabled = currentAddressBook.get("enabled"); + currentEnabled = enabled != null ? Boolean.class.cast(enabled) : false; } - if (newAddressBookObj instanceof Map) { - Map newAddressBook = (Map) newAddressBookObj; - newEnabled = newAddressBook.get("enabled") != null - ? (Boolean) newAddressBook.get("enabled") : false; + if (newAddressBookObj instanceof Map newAddressBook) { + Object enabled = newAddressBook.get("enabled"); + newEnabled = enabled != null ? Boolean.class.cast(enabled) : false; } // 如果之前是启用状态,现在被禁用,删除所有call_device插件 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/dto/TimbreDataDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/dto/TimbreDataDTO.java index ab52ba651..a7cb12443 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/dto/TimbreDataDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/dto/TimbreDataDTO.java @@ -34,7 +34,7 @@ public class TimbreDataDTO { @Schema(description = "Sort Order") @Min(value = 0, message = "{sort.number}") - private long sort; + private Long sort; @Schema(description = "Corresponding TTS Model Primary Key") @NotBlank(message = "{timbre.ttsModelId.require}") @@ -46,4 +46,4 @@ public class TimbreDataDTO { @Schema(description = "Audio Playback URL") private String voiceDemo; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/entity/TimbreEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/entity/TimbreEntity.java index 44960a2d6..5d638389e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/entity/TimbreEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/entity/TimbreEntity.java @@ -3,6 +3,7 @@ package xiaozhi.modules.timbre.entity; import java.util.Date; import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.FieldStrategy; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; @@ -68,4 +69,4 @@ public class TimbreEntity { @TableField(fill = FieldFill.INSERT) private Date createDate; -} \ No newline at end of file +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java index 8b124d18e..39c5c6717 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java @@ -1,6 +1,7 @@ package xiaozhi.modules.timbre.service.impl; import java.util.*; +import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; @@ -41,6 +42,8 @@ import xiaozhi.modules.voiceclone.entity.VoiceCloneEntity; @Service public class TimbreServiceImpl extends BaseServiceImpl implements TimbreService { + private static final Pattern LANGUAGE_SEPARATOR = Pattern.compile("[、;;,,]"); + private final TimbreDao timbreDao; private final VoiceCloneDao voiceCloneDao; private final RedisUtils redisUtils; @@ -96,6 +99,9 @@ public class TimbreServiceImpl extends BaseServiceImpl @Transactional(rollbackFor = Exception.class) public void save(TimbreDataDTO dto) { isTtsModelId(dto.getTtsModelId()); + if (dto.getSort() == null) { + dto.setSort(0L); + } TimbreEntity timbreEntity = ConvertUtils.sourceToTarget(dto, TimbreEntity.class); baseDao.insert(timbreEntity); } @@ -114,7 +120,7 @@ public class TimbreServiceImpl extends BaseServiceImpl @Override @Transactional(rollbackFor = Exception.class) public void delete(String[] ids) { - baseDao.deleteBatchIds(Arrays.asList(ids)); + baseDao.deleteByIds(Arrays.asList(ids)); } @Override @@ -158,6 +164,32 @@ public class TimbreServiceImpl extends BaseServiceImpl return CollectionUtil.isEmpty(voiceDTOs) ? null : voiceDTOs; } + @Override + public String getDefaultLanguageById(String id) { + if (StringUtils.isBlank(id)) { + return null; + } + + TimbreEntity timbre = timbreDao.selectById(id); + if (timbre != null) { + return firstNonBlankLanguage(timbre.getLanguages()); + } + + VoiceCloneEntity voiceClone = voiceCloneDao.selectById(id); + return voiceClone == null ? null : firstNonBlankLanguage(voiceClone.getLanguages()); + } + + private String firstNonBlankLanguage(String languages) { + if (StringUtils.isBlank(languages)) { + return null; + } + return LANGUAGE_SEPARATOR.splitAsStream(languages) + .map(StringUtils::trimToNull) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); + } + /** * Process whether it is TTS model ID */ diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/impl/VoiceCloneServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/impl/VoiceCloneServiceImpl.java index 0d5a52ec5..5e6b17e77 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/impl/VoiceCloneServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/impl/VoiceCloneServiceImpl.java @@ -17,6 +17,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.fasterxml.jackson.databind.ObjectMapper; +import cn.hutool.core.collection.CollUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import xiaozhi.common.exception.ErrorCode; @@ -25,7 +26,6 @@ import xiaozhi.common.page.PageData; import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.DateUtils; -import xiaozhi.common.utils.ToolUtil; import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.sys.dao.SysUserDao; @@ -119,14 +119,14 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl - - @@ -38,6 +35,13 @@ + + + + + + - \ No newline at end of file + + + + + UPDATE ai_agent + SET agent_code = #{agent.agentCode,jdbcType=VARCHAR}, + agent_name = #{agent.agentName,jdbcType=VARCHAR}, + asr_model_id = #{agent.asrModelId,jdbcType=VARCHAR}, + vad_model_id = #{agent.vadModelId,jdbcType=VARCHAR}, + llm_model_id = #{agent.llmModelId,jdbcType=VARCHAR}, + slm_model_id = #{agent.slmModelId,jdbcType=VARCHAR}, + vllm_model_id = #{agent.vllmModelId,jdbcType=VARCHAR}, + tts_model_id = #{agent.ttsModelId,jdbcType=VARCHAR}, + tts_voice_id = #{agent.ttsVoiceId,jdbcType=VARCHAR}, + tts_language = #{agent.ttsLanguage,jdbcType=VARCHAR}, + tts_volume = #{agent.ttsVolume,jdbcType=INTEGER}, + tts_rate = #{agent.ttsRate,jdbcType=INTEGER}, + tts_pitch = #{agent.ttsPitch,jdbcType=INTEGER}, + mem_model_id = #{agent.memModelId,jdbcType=VARCHAR}, + intent_model_id = #{agent.intentModelId,jdbcType=VARCHAR}, + chat_history_conf = #{agent.chatHistoryConf,jdbcType=INTEGER}, + system_prompt = #{agent.systemPrompt,jdbcType=LONGVARCHAR}, + summary_memory = #{agent.summaryMemory,jdbcType=LONGVARCHAR}, + lang_code = #{agent.langCode,jdbcType=VARCHAR}, + language = #{agent.language,jdbcType=VARCHAR}, + sort = #{agent.sort,jdbcType=INTEGER}, + updater = #{agent.updater,jdbcType=BIGINT}, + updated_at = #{agent.updatedAt,jdbcType=TIMESTAMP} + WHERE id = #{agent.id} + + + diff --git a/main/manager-api/src/main/resources/mapper/agent/AgentSnapshotDao.xml b/main/manager-api/src/main/resources/mapper/agent/AgentSnapshotDao.xml new file mode 100644 index 000000000..39e3211cb --- /dev/null +++ b/main/manager-api/src/main/resources/mapper/agent/AgentSnapshotDao.xml @@ -0,0 +1,123 @@ + + + + + + + + + + + + INSERT INTO ai_agent_snapshot ( + id, + agent_id, + user_id, + version_no, + snapshot_data, + changed_fields, + source, + restore_from_snapshot_id, + restore_from_version_no, + creator, + created_at, + redaction_version + ) + SELECT #{snapshot.id}, + #{snapshot.agentId}, + #{snapshot.userId}, + COALESCE(MAX(version_no), 0) + 1, + #{snapshot.snapshotData}, + #{snapshot.changedFields}, + #{snapshot.source}, + #{snapshot.restoreFromSnapshotId}, + #{snapshot.restoreFromVersionNo}, + #{snapshot.creator}, + #{snapshot.createdAt}, + #{snapshot.redactionVersion} + FROM ai_agent_snapshot + WHERE agent_id = #{snapshot.agentId} + + + + DELETE FROM ai_agent_snapshot + WHERE agent_id = #{agentId} + AND id NOT IN ( + SELECT id + FROM ( + SELECT id + FROM ai_agent_snapshot + WHERE agent_id = #{agentId} + ORDER BY version_no DESC + LIMIT #{keepLimit} + ) retained_snapshots + ) + + + + + + UPDATE ai_agent_snapshot + SET snapshot_data = CASE id + + WHEN #{snapshot.id} THEN #{snapshot.snapshotData} + + ELSE snapshot_data + END, + redaction_version = #{redactionVersion} + WHERE redaction_version < #{redactionVersion} + AND id IN + + #{snapshot.id} + + + + diff --git a/main/manager-api/src/main/resources/mapper/device/DeviceAddressBookDao.xml b/main/manager-api/src/main/resources/mapper/device/DeviceAddressBookDao.xml index cc4476a47..2601f60e5 100644 --- a/main/manager-api/src/main/resources/mapper/device/DeviceAddressBookDao.xml +++ b/main/manager-api/src/main/resources/mapper/device/DeviceAddressBookDao.xml @@ -21,8 +21,19 @@ WHERE mac_address = #{macAddress} AND target_mac = #{targetMac} - + INSERT INTO ai_device_address_book (mac_address, target_mac, alias, has_permission, creator, create_date, updater, update_date) VALUES (#{macAddress}, #{targetMac}, #{alias}, #{hasPermission}, #{creator}, NOW(), #{updater}, NOW()) - \ No newline at end of file + + + DELETE FROM ai_device_address_book WHERE mac_address IN + + #{mac} + + OR target_mac IN + + #{mac} + + + diff --git a/main/manager-api/src/test/java/xiaozhi/common/redis/RedisSerializationTest.java b/main/manager-api/src/test/java/xiaozhi/common/redis/RedisSerializationTest.java new file mode 100644 index 000000000..26610ae5b --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/common/redis/RedisSerializationTest.java @@ -0,0 +1,57 @@ +package xiaozhi.common.redis; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.serializer.RedisSerializer; + +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.modules.sys.vo.SysDictDataItem; + +class RedisSerializationTest { + private final RedisSerializer serializer = RedisSerializer.json(); + + @Test + void serverConfigRoundTripRestoresStringKeyedMaps() { + Map features = new HashMap<>(); + features.put("addressBook", Map.of("enabled", true)); + Map config = new HashMap<>(); + config.put("features", features); + + Object restored = roundTrip(config); + Map restoredConfig = JsonUtils.toStringObjectMap(restored); + Map restoredFeatures = JsonUtils.toStringObjectMap(restoredConfig.get("features")); + Map addressBook = JsonUtils.toStringObjectMap(restoredFeatures.get("addressBook")); + + assertEquals(true, addressBook.get("enabled")); + } + + @Test + void dictionaryListRoundTripRestoresDtoElements() { + SysDictDataItem item = new SysDictDataItem(); + item.setName("enabled"); + item.setKey("1"); + + Object restored = roundTrip(new ArrayList<>(List.of(item))); + List restoredItems = JsonUtils.toList(restored, SysDictDataItem.class); + + assertInstanceOf(SysDictDataItem.class, restoredItems.get(0)); + assertEquals("enabled", restoredItems.get(0).getName()); + assertEquals("1", restoredItems.get(0).getKey()); + } + + private Object roundTrip(Object value) { + byte[] bytes = serializer.serialize(value); + assertNotNull(bytes); + Object restored = serializer.deserialize(bytes); + assertNotNull(restored); + return restored; + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/common/service/impl/BaseServiceImplTest.java b/main/manager-api/src/test/java/xiaozhi/common/service/impl/BaseServiceImplTest.java new file mode 100644 index 000000000..50c206553 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/common/service/impl/BaseServiceImplTest.java @@ -0,0 +1,219 @@ +package xiaozhi.common.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; + +import org.apache.ibatis.binding.MapperMethod; +import org.apache.ibatis.executor.BatchResult; +import org.apache.ibatis.logging.nologging.NoLoggingImpl; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.session.ExecutorType; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import com.baomidou.mybatisplus.core.enums.SqlMethod; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.toolkit.Constants; +import com.baomidou.mybatisplus.extension.toolkit.SqlHelper; + +class BaseServiceImplTest { + private static final String INSERT_STATEMENT = TestMapper.class.getName() + ".insert"; + private static final String UPDATE_STATEMENT = TestMapper.class.getName() + ".updateById"; + + private final TestService service = new TestService(); + + @AfterEach + void clearTransactionSynchronization() { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void insertBatchFlushesAtTheRequestedBatchSizeAndCommitsWithoutATransaction() { + SqlSessionFactory sqlSessionFactory = mock(SqlSessionFactory.class); + SqlSession sqlSession = mock(SqlSession.class); + when(sqlSessionFactory.openSession(ExecutorType.BATCH)).thenReturn(sqlSession); + when(sqlSession.insert(eq(INSERT_STATEMENT), any(TestEntity.class))).thenReturn(1); + when(sqlSession.flushStatements()) + .thenReturn(List.of(batchResult(1, 1))) + .thenReturn(List.of(batchResult(1))); + + TestEntity first = new TestEntity(1L); + TestEntity second = new TestEntity(2L); + TestEntity third = new TestEntity(3L); + + try (MockedStatic sqlHelper = sqlHelperUsing(sqlSessionFactory)) { + assertTrue(service.insertBatch(List.of(first, second, third), 2)); + } + + verify(sqlSession).insert(INSERT_STATEMENT, first); + verify(sqlSession).insert(INSERT_STATEMENT, second); + verify(sqlSession).insert(INSERT_STATEMENT, third); + verify(sqlSession, times(2)).flushStatements(); + verify(sqlSession).commit(true); + verify(sqlSession).close(); + } + + @Test + void updateBatchByIdPassesEachEntityAndReturnsSuccessfulFlushResult() { + SqlSessionFactory sqlSessionFactory = mock(SqlSessionFactory.class); + SqlSession sqlSession = mock(SqlSession.class); + when(sqlSessionFactory.openSession(ExecutorType.BATCH)).thenReturn(sqlSession); + when(sqlSession.update(eq(UPDATE_STATEMENT), any())).thenReturn(1); + when(sqlSession.flushStatements()).thenReturn(List.of(batchResult(1, 1))); + + TestEntity first = new TestEntity(1L); + TestEntity second = new TestEntity(2L); + + try (MockedStatic sqlHelper = sqlHelperUsing(sqlSessionFactory)) { + assertTrue(service.updateBatchById(List.of(first, second), 10)); + } + + ArgumentCaptor params = ArgumentCaptor.forClass(Object.class); + verify(sqlSession, times(2)).update(eq(UPDATE_STATEMENT), params.capture()); + assertSame(first, entityFrom(params.getAllValues().get(0))); + assertSame(second, entityFrom(params.getAllValues().get(1))); + verify(sqlSession).flushStatements(); + } + + @Test + void batchCallbacksReturnActualAffectedRowCounts() { + SqlSession sqlSession = mock(SqlSession.class); + when(sqlSession.insert(eq(INSERT_STATEMENT), any(TestEntity.class))).thenReturn(3); + when(sqlSession.update(eq(UPDATE_STATEMENT), any())).thenReturn(2); + CallbackCapturingTestService capturingService = new CallbackCapturingTestService(sqlSession); + TestEntity entity = new TestEntity(1L); + + assertTrue(capturingService.insertBatch(List.of(entity), 7)); + assertEquals(7, capturingService.batchSize); + assertEquals(List.of(3), capturingService.affectedRows); + + assertTrue(capturingService.updateBatchById(List.of(entity), 9)); + assertEquals(9, capturingService.batchSize); + assertEquals(List.of(2), capturingService.affectedRows); + } + + @Test + void emptyBatchesReturnFalseWithoutOpeningABatchSession() { + SqlSessionFactory sqlSessionFactory = mock(SqlSessionFactory.class); + + try (MockedStatic sqlHelper = sqlHelperUsing(sqlSessionFactory)) { + assertFalse(service.insertBatch(List.of(), 10)); + assertFalse(service.updateBatchById(List.of(), 10)); + } + + verifyNoInteractions(sqlSessionFactory); + } + + @Test + void deleteBatchIdsDelegatesToCompatibleApiAndPreservesAffectedRowResult() { + TestMapper mapper = mock(TestMapper.class); + List ids = List.of(1L, 2L); + service.baseDao = mapper; + when(mapper.deleteByIds(ids)).thenReturn(2).thenReturn(0); + + assertTrue(service.deleteBatchIds(ids)); + assertFalse(service.deleteBatchIds(ids)); + + verify(mapper, times(2)).deleteByIds(ids); + } + + @Test + void activeTransactionSynchronizationUsesTransactionAwareCommitAndLifecycle() { + SqlSessionFactory sqlSessionFactory = mock(SqlSessionFactory.class); + SqlSession sqlSession = mock(SqlSession.class); + when(sqlSessionFactory.openSession(ExecutorType.BATCH)).thenReturn(sqlSession); + when(sqlSession.insert(eq(INSERT_STATEMENT), any(TestEntity.class))).thenReturn(1); + when(sqlSession.flushStatements()).thenReturn(List.of(batchResult(1))); + TransactionSynchronizationManager.initSynchronization(); + + try (MockedStatic sqlHelper = sqlHelperUsing(sqlSessionFactory)) { + assertTrue(service.insertBatch(List.of(new TestEntity(1L)), 1)); + } + + verify(sqlSession).flushStatements(); + verify(sqlSession).commit(false); + verify(sqlSession, never()).commit(true); + verify(sqlSession, never()).close(); + } + + @SuppressWarnings("deprecation") + private static MockedStatic sqlHelperUsing(SqlSessionFactory sqlSessionFactory) { + MockedStatic sqlHelper = mockStatic(SqlHelper.class, CALLS_REAL_METHODS); + sqlHelper.when(() -> SqlHelper.sqlSessionFactory(TestEntity.class)).thenReturn(sqlSessionFactory); + return sqlHelper; + } + + private static BatchResult batchResult(int... updateCounts) { + BatchResult result = new BatchResult(mock(MappedStatement.class), "batch"); + result.setUpdateCounts(updateCounts); + return result; + } + + private static Object entityFrom(Object parameter) { + assertTrue(parameter instanceof MapperMethod.ParamMap); + return ((Map) parameter).get(Constants.ENTITY); + } + + private interface TestMapper extends BaseMapper { + } + + private record TestEntity(Long id) { + } + + private static class TestService extends BaseServiceImpl { + private TestService() { + log = new NoLoggingImpl(TestService.class.getName()); + } + + @Override + protected String getSqlStatement(SqlMethod sqlMethod) { + return switch (sqlMethod) { + case INSERT_ONE -> INSERT_STATEMENT; + case UPDATE_BY_ID -> UPDATE_STATEMENT; + default -> throw new IllegalArgumentException("Unexpected SQL method: " + sqlMethod); + }; + } + } + + private static class CallbackCapturingTestService extends TestService { + private final SqlSession sqlSession; + private int batchSize; + private List affectedRows; + + private CallbackCapturingTestService(SqlSession sqlSession) { + this.sqlSession = sqlSession; + } + + @Override + protected boolean executeBatch(Collection list, int batchSize, + BiFunction operation) { + this.batchSize = batchSize; + this.affectedRows = list.stream().map(entity -> operation.apply(sqlSession, entity)).toList(); + return true; + } + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/common/utils/JsonUtilsTest.java b/main/manager-api/src/test/java/xiaozhi/common/utils/JsonUtilsTest.java new file mode 100644 index 000000000..c740ad64f --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/common/utils/JsonUtilsTest.java @@ -0,0 +1,77 @@ +package xiaozhi.common.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +class JsonUtilsTest { + + @Test + void parsesTypedMapsAndPreservesNestedCollectionShapes() { + Map map = JsonUtils.parseMap( + "{\"enabled\":true,\"nested\":{\"items\":[{\"name\":\"tool\"}]}}"); + Map nested = assertInstanceOf(Map.class, map.get("nested")); + List items = assertInstanceOf(List.class, nested.get("items")); + Map item = assertInstanceOf(Map.class, items.get(0)); + + assertEquals(true, map.get("enabled")); + assertEquals("tool", item.get("name")); + + List> maps = JsonUtils.parseMapList( + "[{\"name\":\"first\",\"values\":[1,2]},{\"name\":\"second\"}]"); + assertEquals("first", maps.get(0).get("name")); + assertEquals(List.of(1, 2), maps.get(0).get("values")); + assertEquals("second", maps.get(1).get("name")); + } + + @Test + void checkedConvertersAreShallowMutableCopies() { + List nested = new ArrayList<>(List.of(Map.of("name", "tool"))); + Map source = new LinkedHashMap<>(); + source.put("nested", nested); + + Map map = JsonUtils.toStringObjectMap(source); + List> maps = JsonUtils.toStringObjectMapList(List.of(source)); + List strings = JsonUtils.toList(Arrays.asList("a", null), String.class); + + assertSame(nested, map.get("nested")); + assertSame(nested, maps.get(0).get("nested")); + map.put("enabled", true); + maps.add(Map.of("name", "second")); + strings.add("b"); + assertEquals(true, map.get("enabled")); + assertEquals(2, maps.size()); + assertEquals(Arrays.asList("a", null, "b"), strings); + } + + @Test + void preservesNullInputs() { + assertNull(JsonUtils.parseMap("")); + assertNull(JsonUtils.parseMapList(null)); + assertNull(JsonUtils.toStringObjectMap(null)); + assertNull(JsonUtils.toStringObjectMapList(null)); + assertNull(JsonUtils.toList(null, String.class)); + } + + @Test + void rejectsUnexpectedJsonShapesAndRuntimeTypes() { + assertThrows(RuntimeException.class, () -> JsonUtils.parseMap("[]")); + assertThrows(RuntimeException.class, () -> JsonUtils.parseMapList("{}")); + assertThrows(ClassCastException.class, () -> JsonUtils.toStringObjectMap(List.of())); + assertThrows(ClassCastException.class, () -> JsonUtils.toStringObjectMap(Map.of(1, "value"))); + assertThrows(ClassCastException.class, () -> JsonUtils.toStringObjectMapList(List.of("value"))); + assertThrows(ClassCastException.class, () -> JsonUtils.toStringObjectMapList(Map.of())); + assertThrows(ClassCastException.class, () -> JsonUtils.toList(List.of(1), String.class)); + assertThrows(ClassCastException.class, () -> JsonUtils.toList(Map.of(), String.class)); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/common/utils/SensitiveDataUtilsTest.java b/main/manager-api/src/test/java/xiaozhi/common/utils/SensitiveDataUtilsTest.java new file mode 100644 index 000000000..d93b4163b --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/common/utils/SensitiveDataUtilsTest.java @@ -0,0 +1,83 @@ +package xiaozhi.common.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import cn.hutool.json.JSONObject; + +class SensitiveDataUtilsTest { + + @Test + void isSensitiveField_recognizes_known_field_names() { + assertTrue(SensitiveDataUtils.isSensitiveField("api_key")); + assertTrue(SensitiveDataUtils.isSensitiveField("API_KEY")); + assertTrue(SensitiveDataUtils.isSensitiveField("personal_access_token")); + assertTrue(SensitiveDataUtils.isSensitiveField("secret")); + assertTrue(SensitiveDataUtils.isSensitiveField("secret_key")); + } + + @Test + void isSensitiveField_rejects_blank_and_unknown_field_names() { + assertFalse(SensitiveDataUtils.isSensitiveField("")); + assertFalse(SensitiveDataUtils.isSensitiveField(" ")); + assertFalse(SensitiveDataUtils.isSensitiveField(null)); + assertFalse(SensitiveDataUtils.isSensitiveField("not_a_secret")); + } + + @Test + void maskMiddle_returns_input_unchanged_for_short_or_blank_values() { + assertNull(SensitiveDataUtils.maskMiddle(null)); + assertEquals("", SensitiveDataUtils.maskMiddle("")); + assertEquals("a", SensitiveDataUtils.maskMiddle("a")); + } + + @Test + void maskMiddle_keeps_two_at_each_end_for_short_strings() { + assertEquals("ab****yz", SensitiveDataUtils.maskMiddle("abcdefyz")); + } + + @Test + void maskMiddle_keeps_four_at_each_end_for_long_strings() { + String masked = SensitiveDataUtils.maskMiddle("verylongapikeyvalue123"); + assertTrue(masked.startsWith("very")); + assertTrue(masked.endsWith("3123")); + assertTrue(masked.contains("****")); + assertEquals("verylongapikeyvalue123".length(), masked.length()); + } + + @Test + void isMaskedValue_detects_masked_values() { + assertTrue(SensitiveDataUtils.isMaskedValue("ab****yz")); + assertTrue(SensitiveDataUtils.isMaskedValue("abc****def****ghi")); + assertFalse(SensitiveDataUtils.isMaskedValue("plainstring")); + } + + @Test + void isMaskedValue_rejects_blank_values() { + assertFalse(SensitiveDataUtils.isMaskedValue(null)); + assertFalse(SensitiveDataUtils.isMaskedValue("")); + assertFalse(SensitiveDataUtils.isMaskedValue(" ")); + } + + @Test + void maskSensitiveFields_masks_known_sensitive_keys_only() { + JSONObject source = new JSONObject(); + source.set("api_key", "sk-supersecretapikey"); + source.set("name", "alice"); + + JSONObject masked = SensitiveDataUtils.maskSensitiveFields(source); + + String apiKey = (String) masked.get("api_key"); + assertTrue(apiKey.contains("****")); + assertEquals("alice", masked.get("name")); + } + + @Test + void maskSensitiveFields_returns_null_when_input_is_null() { + assertNull(SensitiveDataUtils.maskSensitiveFields(null)); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/agent/dto/AgentUpdateDTOTest.java b/main/manager-api/src/test/java/xiaozhi/modules/agent/dto/AgentUpdateDTOTest.java new file mode 100644 index 000000000..8ffe01c4b --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/agent/dto/AgentUpdateDTOTest.java @@ -0,0 +1,44 @@ +package xiaozhi.modules.agent.dto; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +class AgentUpdateDTOTest { + + @Test + void functionInfoAcceptsJsonStringParamInfo() { + AgentUpdateDTO.FunctionInfo info = new AgentUpdateDTO.FunctionInfo(); + + info.setParamInfo("{\"api_key\":\"abc\",\"max_results\":5}"); + + assertEquals("abc", info.getParamInfo().get("api_key")); + assertEquals(5, info.getParamInfo().get("max_results")); + } + + @Test + void functionInfoNormalizesMapKeysToStrings() { + AgentUpdateDTO.FunctionInfo info = new AgentUpdateDTO.FunctionInfo(); + Map params = new LinkedHashMap<>(); + params.put("api_key", "abc"); + params.put(42, true); + + info.setParamInfo(params); + + assertEquals("abc", info.getParamInfo().get("api_key")); + assertEquals(true, info.getParamInfo().get("42")); + } + + @Test + void functionInfoFallsBackToEmptyMapForBlankParamInfo() { + AgentUpdateDTO.FunctionInfo info = new AgentUpdateDTO.FunctionInfo(); + + info.setParamInfo(" "); + + assertTrue(info.getParamInfo().isEmpty()); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/agent/service/impl/AgentSnapshotRedactionRunnerTest.java b/main/manager-api/src/test/java/xiaozhi/modules/agent/service/impl/AgentSnapshotRedactionRunnerTest.java new file mode 100644 index 000000000..42dd244f5 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/agent/service/impl/AgentSnapshotRedactionRunnerTest.java @@ -0,0 +1,77 @@ +package xiaozhi.modules.agent.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Method; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; +import org.springframework.scheduling.annotation.Scheduled; + +import xiaozhi.modules.agent.service.AgentSnapshotService; + +@ExtendWith(OutputCaptureExtension.class) +class AgentSnapshotRedactionRunnerTest { + + @Test + void startupRedactionRunsSynchronouslyAndReportsCompensationWindow(CapturedOutput output) { + assertTrue(SmartInitializingSingleton.class.isAssignableFrom(AgentSnapshotRedactionRunner.class)); + AgentSnapshotService service = mock(AgentSnapshotService.class); + AgentSnapshotRedactionRunner runner = new AgentSnapshotRedactionRunner(service); + when(service.redactLegacySnapshots()).thenReturn(0L); + + runner.afterSingletonsInstantiated(); + + verify(service).redactLegacySnapshots(); + assertTrue(output.getAll().contains("startup pass completed")); + assertTrue(output.getAll().contains("starts after 5000 ms and repeats every 15000 ms")); + } + + @Test + void startupRedactionFailureIsLoggedAndPropagatedToKeepStartupFailClosed(CapturedOutput output) { + AgentSnapshotService service = mock(AgentSnapshotService.class); + AgentSnapshotRedactionRunner runner = new AgentSnapshotRedactionRunner(service); + IllegalStateException failure = new IllegalStateException("database unavailable"); + when(service.redactLegacySnapshots()).thenThrow(failure); + + IllegalStateException thrown = assertThrows(IllegalStateException.class, + runner::afterSingletonsInstantiated); + + assertSame(failure, thrown); + assertTrue(output.getAll().contains("blocking application startup before it can accept traffic")); + } + + @Test + void rollingDeploymentRedactionReportsTriggerCountAndCredentialRotation(CapturedOutput output) { + AgentSnapshotService service = mock(AgentSnapshotService.class); + AgentSnapshotRedactionRunner runner = new AgentSnapshotRedactionRunner(service); + when(service.redactLegacySnapshots()).thenReturn(3L); + + runner.redactLateRollingDeploymentWrites(); + + assertTrue(output.getAll().contains("trigger=rolling-deployment migrated=3")); + assertTrue(output.getAll().contains("Rotate credentials")); + } + + @Test + void rollingDeploymentScheduleKeepsLegacyWriteExposureWindowShort() throws Exception { + Method method = AgentSnapshotRedactionRunner.class.getMethod("redactLateRollingDeploymentWrites"); + Scheduled scheduled = method.getAnnotation(Scheduled.class); + + assertNotNull(scheduled); + assertEquals(5_000, scheduled.initialDelay()); + assertEquals(15_000, scheduled.fixedDelay()); + assertTrue(scheduled.initialDelay() <= 10_000); + assertTrue(scheduled.fixedDelay() <= 30_000); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/agent/service/impl/AgentSnapshotServiceImplTest.java b/main/manager-api/src/test/java/xiaozhi/modules/agent/service/impl/AgentSnapshotServiceImplTest.java new file mode 100644 index 000000000..8a3473e6b --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/agent/service/impl/AgentSnapshotServiceImplTest.java @@ -0,0 +1,1962 @@ +package xiaozhi.modules.agent.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.repository.IRepository; +import com.fasterxml.jackson.core.type.TypeReference; +import java.lang.reflect.Method; +import java.lang.reflect.InvocationTargetException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.annotation.Transactional; + +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.common.exception.RenException; +import xiaozhi.modules.agent.Enums.AgentSnapshotField; +import xiaozhi.modules.agent.dao.AgentDao; +import xiaozhi.modules.agent.dao.AgentSnapshotDao; +import xiaozhi.modules.agent.dao.AgentTagDao; +import xiaozhi.modules.agent.dao.AgentTagRelationDao; +import xiaozhi.modules.agent.dto.AgentCreateDTO; +import xiaozhi.modules.agent.dto.AgentSnapshotDataDTO; +import xiaozhi.modules.agent.dto.AgentSnapshotPageDTO; +import xiaozhi.modules.agent.dto.AgentSnapshotTagDTO; +import xiaozhi.modules.agent.dto.AgentUpdateDTO; +import xiaozhi.modules.agent.dto.ContextProviderDTO; +import xiaozhi.modules.agent.entity.AgentEntity; +import xiaozhi.modules.agent.entity.AgentPluginMapping; +import xiaozhi.modules.agent.entity.AgentTemplateEntity; +import xiaozhi.modules.agent.entity.AgentSnapshotEntity; +import xiaozhi.modules.agent.entity.AgentTagEntity; +import xiaozhi.modules.agent.service.AgentChatHistoryService; +import xiaozhi.modules.agent.service.AgentPluginMappingService; +import xiaozhi.modules.agent.service.AgentContextProviderService; +import xiaozhi.modules.agent.service.AgentSnapshotService; +import xiaozhi.modules.agent.service.AgentTagService; +import xiaozhi.modules.agent.service.AgentTemplateService; +import xiaozhi.modules.agent.vo.AgentSnapshotVO; +import xiaozhi.modules.agent.vo.AgentInfoVO; +import xiaozhi.modules.correctword.service.CorrectWordFileService; +import xiaozhi.modules.model.service.ModelProviderService; +import xiaozhi.modules.timbre.service.TimbreService; + +class AgentSnapshotServiceImplTest { + + @Test + @SuppressWarnings("unchecked") + void normalizeJsonListTreatsDtoAndMapShapesEqually() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("normalizeJsonList", List.class); + method.setAccessible(true); + + ContextProviderDTO dto = new ContextProviderDTO(); + dto.setUrl("https://example.com/context"); + dto.setHeaders(Map.of("Authorization", "Bearer token")); + + Map map = new LinkedHashMap<>(); + map.put("headers", Map.of("Authorization", "Bearer token")); + map.put("url", "https://example.com/context"); + + assertEquals(method.invoke(service, List.of(dto)), method.invoke(service, List.of(map))); + } + + @Test + @SuppressWarnings("unchecked") + void contextProviderOrderIsARealSnapshotChange() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("getChangedFields", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + method.setAccessible(true); + + ContextProviderDTO first = new ContextProviderDTO(); + first.setUrl("https://example.com/first"); + first.setHeaders(Map.of()); + ContextProviderDTO second = new ContextProviderDTO(); + second.setUrl("https://example.com/second"); + second.setHeaders(Map.of()); + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setContextProviders(List.of(first, second)); + AgentSnapshotDataDTO reordered = new AgentSnapshotDataDTO(); + reordered.setContextProviders(List.of(second, first)); + + List changedFields = (List) method.invoke(service, current, reordered); + + assertEquals(List.of(AgentSnapshotField.CONTEXT_PROVIDERS.getFieldName()), changedFields); + } + + @Test + void redactSnapshotDataMasksSensitiveFunctionAndHeaderValues() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSnapshotData", + AgentSnapshotDataDTO.class); + method.setAccessible(true); + + AgentSnapshotDataDTO data = buildExtendedSensitiveSnapshot(); + + AgentSnapshotDataDTO redacted = (AgentSnapshotDataDTO) method.invoke(service, data); + String json = JsonUtils.toJsonString(redacted); + + assertExtendedSecretsAbsent(json); + assertTrue(json.contains("__SNAPSHOT_SECRET_REDACTED__")); + assertTrue(json.contains("max_tokens")); + assertTrue(json.contains("application/json")); + } + + @Test + void snapshotDetailMasksCookieProxyAuthorizationAndSessionHeaders() throws Exception { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, null, null, null, null, null, null, + null, null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("toVO", + AgentSnapshotEntity.class, boolean.class); + method.setAccessible(true); + + AgentSnapshotEntity entity = snapshotEntity("snapshot-id", "agent-id", 4, buildExtendedSensitiveSnapshot()); + when(snapshotDao.selectNextSnapshot("agent-id", 4)).thenReturn(null); + + AgentSnapshotVO detail = (AgentSnapshotVO) method.invoke(service, entity, true); + String json = JsonUtils.toJsonString(detail); + + assertExtendedSecretsAbsent(json); + assertTrue(json.contains("__SNAPSHOT_SECRET_REDACTED__")); + assertTrue(json.contains("application/json")); + } + + @Test + void snapshotDetailReturnsCurrentPreviewDataAndTokenFromTheSameServerRead() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentDao agentDao = mock(AgentDao.class); + AgentTagDao tagDao = mock(AgentTagDao.class); + AgentContextProviderService contextProviderService = mock(AgentContextProviderService.class); + CorrectWordFileService correctWordFileService = mock(CorrectWordFileService.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, agentDao, tagDao, null, null, + contextProviderService, null, null, null, correctWordFileService); + ReflectionTestUtils.setField(service, "baseDao", snapshotDao); + + String agentId = "agent-id"; + String snapshotId = "snapshot-id"; + AgentInfoVO current = snapshotAgentInfo(agentId, 7L, "current", "current-summary"); + AgentPluginMapping mapping = new AgentPluginMapping(); + mapping.setPluginId("plugin"); + mapping.setParamInfo("{\"api_key\":\"live-secret\",\"visible\":\"kept\"," + + "\"webhookUrl\":\"https://hooks.slack.com/services/T111/B222/live-path-secret\"}"); + current.setFunctions(List.of(mapping)); + AgentEntity lockedAgent = new AgentEntity(); + lockedAgent.setId(agentId); + when(agentDao.selectByIdForUpdate(agentId)).thenReturn(lockedAgent); + when(snapshotDao.selectById(snapshotId)) + .thenReturn(snapshotEntity(snapshotId, agentId, 2, snapshotData("target", "target-summary"))); + when(snapshotDao.selectNextSnapshot(agentId, 2)).thenReturn(null); + when(agentDao.selectAgentInfoById(agentId)).thenReturn(current); + when(contextProviderService.getByAgentId(agentId)).thenReturn(null); + when(correctWordFileService.getAgentCorrectWordFileIds(agentId)).thenReturn(List.of()); + when(tagDao.selectByAgentId(agentId)).thenReturn(List.of()); + + AgentSnapshotVO detail = service.getSnapshot(agentId, snapshotId); + + assertNotNull(detail.getCurrentSnapshotData()); + assertEquals(64, detail.getCurrentStateToken().length()); + String currentJson = JsonUtils.toJsonString(detail.getCurrentSnapshotData()); + assertFalse(currentJson.contains("live-secret")); + assertFalse(currentJson.contains("live-path-secret")); + assertTrue(currentJson.contains("__SNAPSHOT_SECRET_REDACTED__")); + assertTrue(currentJson.contains("kept")); + } + + @Test + void legacyRedactionMigrationCleansStructuredAndUrlSecretsWithoutDroppingUnknownFields() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, null, null, null, null, null, + null, null, null, null); + AgentSnapshotEntity legacy = new AgentSnapshotEntity(); + legacy.setId("legacy-id"); + legacy.setRedactionVersion(1); + legacy.setSnapshotData(JsonUtils.toJsonString(Map.of( + "futureField", Map.of( + "kept", true, + "primaryEndpoint", "https://api.example.com/hooks/events/status", + "secondaryEndpoint", "https://api.example.com/webhooks/events/status", + "singleHookEndpoint", "https://api.example.com/hooks/events", + "statusEndpoint", "https://api.example.com/webhooks/status", + "webhook", "incoming/legacy-token", + "description", "incoming/token", + "outgoingWebhookUrl", "https://example.com/incoming/legacy-path-secret"), + "functions", List.of(Map.of("paramInfo", Map.of( + "headers", List.of(Map.of("NAME", "Authorization", "VALUE", "Bearer legacy-secret")), + "Cookie", "legacy-cookie", + "protocolRelativeEndpoint", + "//legacy-relative-user:legacy-relative-pass@example.com/public/path", + "endpoint", "https://user:pass@example.com/hook?subscription-key=legacy-key")))))); + when(snapshotDao.selectLegacyRedactionBatch(null, 100, 2)).thenReturn(List.of(legacy)); + when(snapshotDao.selectLegacyRedactionBatch("legacy-id", 100, 2)).thenReturn(List.of()); + when(snapshotDao.updateRedactedSnapshots(any(), eq(2))).thenReturn(1); + + long migrated = service.redactLegacySnapshots(); + + verify(snapshotDao).updateRedactedSnapshots( + argThat(snapshots -> snapshots.size() == 1 && "legacy-id".equals(snapshots.get(0).getId())), eq(2)); + assertEquals(1, migrated); + assertFalse(legacy.getSnapshotData().contains("legacy-secret")); + assertFalse(legacy.getSnapshotData().contains("legacy-cookie")); + assertFalse(legacy.getSnapshotData().contains("legacy-key")); + assertFalse(legacy.getSnapshotData().contains("user:pass")); + assertFalse(legacy.getSnapshotData().contains("legacy-path-secret")); + assertFalse(legacy.getSnapshotData().contains("legacy-relative-user")); + assertFalse(legacy.getSnapshotData().contains("legacy-relative-pass")); + assertFalse(legacy.getSnapshotData().contains("incoming/legacy-token")); + assertTrue(legacy.getSnapshotData().contains("futureField")); + assertTrue(legacy.getSnapshotData().contains("\"kept\":true")); + assertTrue(legacy.getSnapshotData().contains("https://api.example.com/hooks/events/status")); + assertTrue(legacy.getSnapshotData().contains("https://api.example.com/webhooks/events/status")); + assertTrue(legacy.getSnapshotData().contains("https://api.example.com/hooks/events")); + assertTrue(legacy.getSnapshotData().contains("https://api.example.com/webhooks/status")); + assertTrue(legacy.getSnapshotData().contains("//__SNAPSHOT_SECRET_REDACTED__@example.com/public/path")); + assertTrue(legacy.getSnapshotData().contains("incoming/__SNAPSHOT_SECRET_REDACTED__")); + assertTrue(legacy.getSnapshotData().contains("incoming/token")); + assertTrue(legacy.getSnapshotData().contains("__SNAPSHOT_SECRET_REDACTED__")); + } + + @Test + void preserveCurrentSensitiveValuesKeepsCurrentSecretsWhenRestoringSnapshot() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveValues", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + method.setAccessible(true); + + AgentSnapshotDataDTO snapshot = buildSnapshot("old-key", "old-token", "old-value"); + AgentSnapshotDataDTO current = buildSnapshot("current-key", "current-token", "current-value"); + + AgentSnapshotDataDTO restored = (AgentSnapshotDataDTO) method.invoke(service, snapshot, current); + + assertEquals("current-key", restored.getFunctions().get(0).getParamInfo().get("api_key")); + assertEquals("old-value", restored.getFunctions().get(0).getParamInfo().get("description")); + assertEquals("current-token", restored.getContextProviders().get(0).getHeaders().get("Authorization")); + } + + @Test + void redactSnapshotDataMasksStructuredHeadersAndUrlCredentials() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSnapshotData", + AgentSnapshotDataDTO.class); + method.setAccessible(true); + + Map params = new HashMap<>(); + params.put("headers", List.of( + Map.of("key", "Authorization", "value", "Bearer structured-secret"), + Map.of("name", "Cookie", "value", "cookie=structured-cookie"))); + 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"); + params.put("transport", + "https://example.com/transport?mode=push&key=transport-key"); + params.put("mirrors", List.of( + "https://example.com/nested?locale=en&token=nested-token")); + AgentSnapshotDataDTO data = new AgentSnapshotDataDTO(); + data.setFunctions(List.of(functionInfo("plugin", params))); + ContextProviderDTO provider = new ContextProviderDTO(); + provider.setUrl("https://provider-user:provider-pass@example.com/context?token=provider-token#provider-fragment"); + provider.setHeaders(Map.of()); + data.setContextProviders(List.of(provider)); + + AgentSnapshotDataDTO redacted = (AgentSnapshotDataDTO) method.invoke(service, data); + String json = JsonUtils.toJsonString(redacted); + + for (String secret : List.of("structured-secret", "structured-cookie", "function-user", "function-pass", + "function-token", "function-fragment", "provider-user", "provider-pass", "provider-token", + "provider-fragment", "endpoint-signature", "transport-key", "nested-token")) { + assertFalse(json.contains(secret), () -> "Sensitive value leaked: " + secret); + } + 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__", + 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")); + assertTrue(json.contains("__SNAPSHOT_SECRET_REDACTED__")); + } + + @Test + void capabilityUrlPathsAreRedactedPreciselyAndIdempotently() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSensitiveUrl", + String.class, String.class); + method.setAccessible(true); + + Map cases = new LinkedHashMap<>(); + cases.put("https://hooks.slack.com/services/T111/B222/slack-secret", + "https://hooks.slack.com/services/T111/B222/__SNAPSHOT_SECRET_REDACTED__"); + cases.put("https://discord.com/api/v10/webhooks/123456/discord-secret", + "https://discord.com/api/v10/webhooks/123456/__SNAPSHOT_SECRET_REDACTED__"); + cases.put("https://api.telegram.org/bot123456:telegram-secret/sendMessage", + "https://api.telegram.org/bot123456:__SNAPSHOT_SECRET_REDACTED__/sendMessage"); + cases.put("https://hooks.zapier.com/hooks/catch/987/generic-secret", + "https://hooks.zapier.com/hooks/__SNAPSHOT_SECRET_REDACTED__"); + cases.put("/api/webhooks/relative-secret/continuation", + "/api/webhooks/__SNAPSHOT_SECRET_REDACTED__"); + + for (Map.Entry entry : cases.entrySet()) { + String redacted = (String) method.invoke(service, entry.getKey(), "endpoint"); + assertEquals(entry.getValue(), redacted); + assertEquals(redacted, method.invoke(service, redacted, "endpoint")); + } + + assertEquals("https://example.com/incoming/__SNAPSHOT_SECRET_REDACTED__", + method.invoke(service, "https://example.com/incoming/key-secret", "outgoingWebhookUrl")); + assertEquals("https://api.example.com/v1/users/123/preferences", + method.invoke(service, "https://api.example.com/v1/users/123/preferences", "endpoint")); + assertEquals("https://api.example.com/hooks/events/status", + method.invoke(service, "https://api.example.com/hooks/events/status", "endpoint")); + assertEquals("https://api.example.com/webhooks/events/status", + method.invoke(service, "https://api.example.com/webhooks/events/status", "endpoint")); + assertEquals("https://api.example.com/hooks/events", + method.invoke(service, "https://api.example.com/hooks/events", "endpoint")); + assertEquals("https://api.example.com/webhooks/status", + method.invoke(service, "https://api.example.com/webhooks/status", "endpoint")); + assertEquals("https://api.example.com/hooks/__SNAPSHOT_SECRET_REDACTED__", + method.invoke(service, "https://api.example.com/hooks/access-token-value", "endpoint")); + assertEquals("https://api.example.com/webhooks/__SNAPSHOT_SECRET_REDACTED__", + method.invoke(service, "https://api.example.com/webhooks/aB3dE5fG7hI9jK1mN3pQ5rS7", "endpoint")); + assertEquals("/api/v1/agents/42", + method.invoke(service, "/api/v1/agents/42", "endpoint")); + assertEquals("incoming/__SNAPSHOT_SECRET_REDACTED__", + method.invoke(service, "incoming/token", "webhook")); + assertEquals("incoming/token", + method.invoke(service, "incoming/token", "description")); + } + + @Test + @SuppressWarnings("unchecked") + void pathCapabilityRotationDoesNotChangeSnapshotStateButPublicIdentityDoes() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method changedMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("getChangedFields", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + changedMethod.setAccessible(true); + + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setFunctions(List.of(functionInfo("plugin", Map.of( + "webhookUrl", "https://hooks.slack.com/services/T111/B222/first-secret", + "endpoint", "/api/webhooks/first-relative-secret/continuation")))); + AgentSnapshotDataDTO rotated = new AgentSnapshotDataDTO(); + rotated.setFunctions(List.of(functionInfo("plugin", Map.of( + "webhookUrl", "https://hooks.slack.com/services/T111/B222/second-secret", + "endpoint", "/api/webhooks/second-relative-secret/continuation")))); + AgentSnapshotDataDTO differentPublicIdentity = new AgentSnapshotDataDTO(); + differentPublicIdentity.setFunctions(List.of(functionInfo("plugin", Map.of( + "webhookUrl", "https://hooks.slack.com/services/T111/B999/second-secret", + "endpoint", "/api/webhooks/second-relative-secret/continuation")))); + + assertTrue(((List) changedMethod.invoke(service, current, rotated)).isEmpty()); + assertEquals(currentStateToken(service, current), currentStateToken(service, rotated)); + assertEquals(List.of(AgentSnapshotField.FUNCTIONS.getFieldName()), + changedMethod.invoke(service, current, differentPublicIdentity)); + assertFalse(currentStateToken(service, current).equals(currentStateToken(service, differentPublicIdentity))); + } + + @Test + @SuppressWarnings("unchecked") + void nestedWebhookSemanticKeysPropagateAcrossRedactionComparisonAndRestore() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method redactMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSnapshotData", + AgentSnapshotDataDTO.class); + redactMethod.setAccessible(true); + Method changedMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("getChangedFields", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + changedMethod.setAccessible(true); + Method preserveMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveValues", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + preserveMethod.setAccessible(true); + Method containsMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("containsSensitiveMaterial", + Object.class); + containsMethod.setAccessible(true); + + List> nestedCases = List.of( + Map.of("webhookConfig", Map.of("value", + "https://capability.example.com/public/nested-secret-one")), + Map.of("deliveryWebhook", Map.of("options", Map.of("target", + "https://capability.example.com/public/nested-secret-two"))), + Map.of("config", Map.of("webhookUrl", + "https://capability.example.com/public/nested-secret-three"))); + for (Map params : nestedCases) { + AgentSnapshotDataDTO candidate = new AgentSnapshotDataDTO(); + candidate.setFunctions(List.of(functionInfo("plugin", params))); + AgentSnapshotDataDTO redacted = (AgentSnapshotDataDTO) redactMethod.invoke(service, candidate); + String json = JsonUtils.toJsonString(redacted); + for (String secret : List.of("nested-secret-one", "nested-secret-two", "nested-secret-three")) { + assertFalse(json.contains(secret), () -> "Nested webhook capability leaked: " + secret); + } + assertTrue(json.contains("__SNAPSHOT_SECRET_REDACTED__")); + } + + AgentSnapshotDataDTO first = nestedWebhookSnapshot("first-current-secret"); + AgentSnapshotDataDTO rotated = nestedWebhookSnapshot("rotated-current-secret"); + assertTrue(((List) changedMethod.invoke(service, first, rotated)).isEmpty()); + assertEquals(currentStateToken(service, first), currentStateToken(service, rotated)); + + AgentSnapshotDataDTO target = (AgentSnapshotDataDTO) redactMethod.invoke(service, + nestedWebhookSnapshot("historical-secret")); + AgentSnapshotDataDTO restored = (AgentSnapshotDataDTO) preserveMethod.invoke(service, target, rotated); + Map webhookConfig = (Map) restored.getFunctions().get(0) + .getParamInfo().get("webhookConfig"); + assertEquals("https://capability.example.com/public/rotated-current-secret", webhookConfig.get("value")); + assertTrue((Boolean) containsMethod.invoke(service, + target.getFunctions().get(0).getParamInfo())); + } + + @Test + void restoringPathCapabilitiesCopiesOnlyCurrentSecretAndRejectsUnsafeIdentity() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method redactMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSensitiveUrl", + String.class, String.class); + redactMethod.setAccessible(true); + Method preserveMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveUrl", + String.class, String.class, String.class); + preserveMethod.setAccessible(true); + + String target = (String) redactMethod.invoke(service, + "https://hooks.slack.com/services/T111/B222/historical-secret", "webhookUrl"); + assertEquals("https://hooks.slack.com/services/T111/B222/current-secret", + preserveMethod.invoke(service, target, + "https://hooks.slack.com/services/T111/B222/current-secret", "webhookUrl")); + String relativeTarget = (String) redactMethod.invoke(service, + "/api/webhooks/historical-secret/continuation", "endpoint"); + assertEquals("/api/webhooks/current-relative/callback", + preserveMethod.invoke(service, relativeTarget, + "/api/webhooks/current-relative/callback", "endpoint")); + String bareRelativeTarget = (String) redactMethod.invoke(service, + "incoming/historical-token", "webhook"); + assertEquals("incoming/current-token", + preserveMethod.invoke(service, bareRelativeTarget, + "incoming/current-token", "webhook")); + + InvocationTargetException mismatch = assertThrows(InvocationTargetException.class, + () -> preserveMethod.invoke(service, target, + "https://hooks.slack.com/services/T111/B999/current-secret", "webhookUrl")); + assertTrue(mismatch.getCause() instanceof RenException); + InvocationTargetException missing = assertThrows(InvocationTargetException.class, + () -> preserveMethod.invoke(service, target, null, "webhookUrl")); + assertTrue(missing.getCause() instanceof RenException); + InvocationTargetException placeholder = assertThrows(InvocationTargetException.class, + () -> preserveMethod.invoke(service, target, + "https://hooks.slack.com/services/T111/B222/__SNAPSHOT_SECRET_REDACTED__", "webhookUrl")); + assertTrue(placeholder.getCause() instanceof RenException); + InvocationTargetException relativeMismatch = assertThrows(InvocationTargetException.class, + () -> preserveMethod.invoke(service, relativeTarget, + "/different/webhooks/current-relative/callback", "endpoint")); + assertTrue(relativeMismatch.getCause() instanceof RenException); + InvocationTargetException bareRelativeMismatch = assertThrows(InvocationTargetException.class, + () -> preserveMethod.invoke(service, bareRelativeTarget, + "outgoing/current-token", "webhook")); + assertTrue(bareRelativeMismatch.getCause() instanceof RenException); + } + + @Test + void duplicatePublicPathIdentitiesAreRejectedInsteadOfGuessingASecret() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method redactMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSnapshotData", + AgentSnapshotDataDTO.class); + redactMethod.setAccessible(true); + Method preserveMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveValues", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + preserveMethod.setAccessible(true); + + AgentSnapshotDataDTO target = new AgentSnapshotDataDTO(); + target.setFunctions(List.of(functionInfo("plugin", Map.of("webhooks", List.of( + "https://hooks.slack.com/services/T111/B222/historical-secret"))))); + target = (AgentSnapshotDataDTO) redactMethod.invoke(service, target); + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setFunctions(List.of(functionInfo("plugin", Map.of("webhooks", List.of( + "https://hooks.slack.com/services/T111/B222/current-one", + "https://hooks.slack.com/services/T111/B222/current-two"))))); + + AgentSnapshotDataDTO redactedTarget = target; + InvocationTargetException ambiguous = assertThrows(InvocationTargetException.class, + () -> preserveMethod.invoke(service, redactedTarget, current)); + assertTrue(ambiguous.getCause() instanceof RenException); + } + + @Test + @SuppressWarnings("unchecked") + void sensitiveListItemsWithoutNamedIdsUseUniquePublicFingerprint() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method redactMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSnapshotData", + AgentSnapshotDataDTO.class); + redactMethod.setAccessible(true); + Method preserveMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveValues", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + preserveMethod.setAccessible(true); + + AgentSnapshotDataDTO target = new AgentSnapshotDataDTO(); + target.setFunctions(List.of(functionInfo("plugin", Map.of("destinations", List.of( + Map.of("host", "alpha.example.com", "api_key", "historical-secret")))))); + target = (AgentSnapshotDataDTO) redactMethod.invoke(service, target); + + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setFunctions(List.of(functionInfo("plugin", Map.of("destinations", List.of( + Map.of("host", "alpha.example.com", "api_key", "current-secret")))))); + AgentSnapshotDataDTO restored = (AgentSnapshotDataDTO) preserveMethod.invoke(service, target, current); + List> destinations = (List>) restored.getFunctions().get(0) + .getParamInfo().get("destinations"); + assertEquals("current-secret", destinations.get(0).get("api_key")); + + AgentSnapshotDataDTO ambiguousCurrent = new AgentSnapshotDataDTO(); + ambiguousCurrent.setFunctions(List.of(functionInfo("plugin", Map.of("destinations", List.of( + Map.of("host", "alpha.example.com", "api_key", "first-current-secret"), + Map.of("host", "alpha.example.com", "api_key", "second-current-secret")))))); + AgentSnapshotDataDTO redactedTarget = target; + InvocationTargetException ambiguous = assertThrows(InvocationTargetException.class, + () -> preserveMethod.invoke(service, redactedTarget, ambiguousCurrent)); + assertTrue(ambiguous.getCause() instanceof RenException); + } + + @Test + void contextProvidersMatchPathCapabilitiesByUniquePublicIdentity() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method redactMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSnapshotData", + AgentSnapshotDataDTO.class); + redactMethod.setAccessible(true); + Method preserveMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveValues", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + preserveMethod.setAccessible(true); + + AgentSnapshotDataDTO target = new AgentSnapshotDataDTO(); + ContextProviderDTO targetProvider = new ContextProviderDTO(); + targetProvider.setUrl("https://discord.com/api/webhooks/123456/historical-secret"); + targetProvider.setHeaders(Map.of()); + target.setContextProviders(List.of(targetProvider)); + target = (AgentSnapshotDataDTO) redactMethod.invoke(service, target); + + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + ContextProviderDTO currentProvider = new ContextProviderDTO(); + currentProvider.setUrl("https://discord.com/api/webhooks/123456/current-secret"); + currentProvider.setHeaders(Map.of()); + current.setContextProviders(List.of(currentProvider)); + AgentSnapshotDataDTO restored = (AgentSnapshotDataDTO) preserveMethod.invoke(service, target, current); + assertEquals("https://discord.com/api/webhooks/123456/current-secret", + restored.getContextProviders().get(0).getUrl()); + + currentProvider.setUrl("https://discord.com/api/webhooks/999999/current-secret"); + AgentSnapshotDataDTO redactedTarget = target; + InvocationTargetException mismatch = assertThrows(InvocationTargetException.class, + () -> preserveMethod.invoke(service, redactedTarget, current)); + assertTrue(mismatch.getCause() instanceof RenException); + } + + @Test + void snapshotPayloadReaderIgnoresFutureFieldsWithoutChangingGlobalJsonValidation() { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + String payload = "{\"agentName\":\"future-safe\",\"futureField\":{\"enabled\":true}}"; + + AgentSnapshotDataDTO parsed = ReflectionTestUtils.invokeMethod(service, "parseSnapshotData", payload); + + assertNotNull(parsed); + assertEquals("future-safe", parsed.getAgentName()); + assertThrows(RuntimeException.class, () -> JsonUtils.parseObject(payload, AgentSnapshotDataDTO.class)); + } + + @Test + @SuppressWarnings("unchecked") + void preserveSensitiveUrlListsByUrlIdentityInsteadOfIndex() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method redactMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSnapshotData", + AgentSnapshotDataDTO.class); + redactMethod.setAccessible(true); + Method preserveMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveValues", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + preserveMethod.setAccessible(true); + + AgentSnapshotDataDTO target = new AgentSnapshotDataDTO(); + target.setFunctions(List.of(functionInfo("plugin", Map.of("mirrors", List.of( + "https://a.example.com/hook?token=old-a&locale=en", + "https://b.example.com/hook?token=old-b&locale=en"))))); + target = (AgentSnapshotDataDTO) redactMethod.invoke(service, target); + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setFunctions(List.of(functionInfo("plugin", Map.of("mirrors", List.of( + "https://b.example.com/hook?token=current-b&locale=de", + "https://a.example.com/hook?token=current-a&locale=de"))))); + + AgentSnapshotDataDTO restored = (AgentSnapshotDataDTO) preserveMethod.invoke(service, target, current); + List mirrors = (List) restored.getFunctions().get(0).getParamInfo().get("mirrors"); + + assertEquals(List.of( + "https://a.example.com/hook?token=current-a&locale=en", + "https://b.example.com/hook?token=current-b&locale=en"), mirrors); + } + + @Test + @SuppressWarnings("unchecked") + void urlComparisonIgnoresOnlySensitiveParameterValues() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("getChangedFields", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + method.setAccessible(true); + + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setFunctions(List.of(functionInfo("plugin", Map.of("endpoint", + "https://api.example.com/hook?locale=en&api_key=first&X-Amz-Signature=first-signature")))); + AgentSnapshotDataDTO secretOnlyChange = new AgentSnapshotDataDTO(); + secretOnlyChange.setFunctions(List.of(functionInfo("plugin", Map.of("endpoint", + "https://api.example.com/hook?locale=en&api_key=second&X-Amz-Signature=second-signature")))); + AgentSnapshotDataDTO publicParameterChange = new AgentSnapshotDataDTO(); + publicParameterChange.setFunctions(List.of(functionInfo("plugin", Map.of("endpoint", + "https://api.example.com/hook?locale=de&api_key=second&X-Amz-Signature=second-signature")))); + + assertTrue(((List) method.invoke(service, current, secretOnlyChange)).isEmpty()); + assertEquals(List.of(AgentSnapshotField.FUNCTIONS.getFieldName()), + method.invoke(service, current, publicParameterChange)); + } + + @Test + @SuppressWarnings("unchecked") + void preserveSensitiveHeaderListsByStableIdentityInsteadOfIndex() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method redactMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSnapshotData", + AgentSnapshotDataDTO.class); + redactMethod.setAccessible(true); + Method preserveMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveValues", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + preserveMethod.setAccessible(true); + + AgentSnapshotDataDTO target = new AgentSnapshotDataDTO(); + target.setFunctions(List.of(functionInfo("plugin", Map.of("headers", List.of( + Map.of("key", "Authorization", "value", "old-auth"), + Map.of("name", "Cookie", "value", "old-cookie")))))); + target = (AgentSnapshotDataDTO) redactMethod.invoke(service, target); + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setFunctions(List.of(functionInfo("plugin", Map.of("headers", List.of( + Map.of("name", "Cookie", "value", "current-cookie"), + Map.of("key", "Authorization", "value", "current-auth")))))); + + AgentSnapshotDataDTO restored = (AgentSnapshotDataDTO) preserveMethod.invoke(service, target, current); + List> headers = (List>) restored.getFunctions().get(0) + .getParamInfo().get("headers"); + + assertEquals("Authorization", headers.get(0).get("key")); + assertEquals("current-auth", headers.get(0).get("value")); + assertEquals("Cookie", headers.get(1).get("name")); + assertEquals("current-cookie", headers.get(1).get("value")); + assertFalse(JsonUtils.toJsonString(restored).contains("__SNAPSHOT_SECRET_REDACTED__")); + } + + @Test + @SuppressWarnings("unchecked") + void structuredSensitiveValuesRequireOneEquivalentDiscriminator() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method redactMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSensitiveMap", Map.class); + redactMethod.setAccessible(true); + Method preserveMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveMap", + Map.class, Map.class); + preserveMethod.setAccessible(true); + + Map target = (Map) redactMethod.invoke(service, + Map.of("key", "Authorization", "value", "historical-secret")); + Map restored = (Map) preserveMethod.invoke(service, target, + Map.of("key", "authorization", "value", "current-secret")); + assertEquals("current-secret", restored.get("value")); + + InvocationTargetException mismatchedType = assertThrows(InvocationTargetException.class, + () -> preserveMethod.invoke(service, target, + Map.of("key", "Cookie", "value", "cookie-secret"))); + assertTrue(mismatchedType.getCause() instanceof RenException); + + Map ambiguousTarget = (Map) redactMethod.invoke(service, + Map.of("key", "Authorization", "name", "Cookie", "value", "historical-secret")); + InvocationTargetException ambiguous = assertThrows(InvocationTargetException.class, + () -> preserveMethod.invoke(service, ambiguousTarget, + Map.of("key", "Authorization", "name", "Cookie", "value", "current-secret"))); + assertTrue(ambiguous.getCause() instanceof RenException); + } + + @Test + void restoringRedactedUrlsUsesTargetLocationAndCurrentCredentials() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method redactMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSnapshotData", + AgentSnapshotDataDTO.class); + redactMethod.setAccessible(true); + Method preserveMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveValues", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + preserveMethod.setAccessible(true); + + AgentSnapshotDataDTO target = new AgentSnapshotDataDTO(); + target.setFunctions(List.of(functionInfo("plugin", Map.of("callbackUrl", + "https://old-user:old-pass@old.example.com/hook" + + "?api%5Fkey=old-token&locale=en#token=old-fragment§ion=target")))); + ContextProviderDTO targetProvider = new ContextProviderDTO(); + targetProvider.setUrl("https://old-user:old-pass@api.example.com/context" + + "?api_key=old-token&locale=en#sig=old-fragment§ion=target"); + targetProvider.setHeaders(Map.of()); + target.setContextProviders(List.of(targetProvider)); + target = (AgentSnapshotDataDTO) redactMethod.invoke(service, target); + + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setFunctions(List.of(functionInfo("plugin", Map.of("callbackUrl", + "https://current-user:current-pass@old.example.com/hook" + + "?api_key=current-token&locale=de#token=current-fragment§ion=current")))); + ContextProviderDTO currentProvider = new ContextProviderDTO(); + currentProvider.setUrl( + "https://current-user:current-pass@api.example.com/context" + + "?api_key=current-token&locale=de#sig=current-fragment§ion=current"); + currentProvider.setHeaders(Map.of()); + current.setContextProviders(List.of(currentProvider)); + + AgentSnapshotDataDTO restored = (AgentSnapshotDataDTO) preserveMethod.invoke(service, target, current); + + assertEquals("https://current-user:current-pass@old.example.com/hook" + + "?api%5Fkey=current-token&locale=en#token=current-fragment§ion=target", + restored.getFunctions().get(0).getParamInfo().get("callbackUrl")); + assertEquals("https://current-user:current-pass@api.example.com/context" + + "?api_key=current-token&locale=en#sig=current-fragment§ion=target", + restored.getContextProviders().get(0).getUrl()); + assertFalse(JsonUtils.toJsonString(restored).contains("__SNAPSHOT_SECRET_REDACTED__")); + } + + @Test + void urlSecretRestoreRequiresTheSamePublicSchemeAuthorityAndPath() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method redactMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSensitiveUrl", + String.class, String.class); + redactMethod.setAccessible(true); + Method preserveMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveUrl", + String.class, String.class, String.class); + preserveMethod.setAccessible(true); + + String target = (String) redactMethod.invoke(service, + "https://old-user:old-pass@example.com/callback?token=old-token#old-fragment", "callbackUrl"); + assertEquals("https://new-user:new-pass@example.com/callback?token=current-token#current-fragment", + preserveMethod.invoke(service, target, + "https://new-user:new-pass@example.com/callback?token=current-token#current-fragment", + "callbackUrl")); + + for (String mismatch : List.of( + "https://new-user:new-pass@other.example.com/callback?token=current-token#current-fragment", + "https://new-user:new-pass@example.com/other?token=current-token#current-fragment", + "http://new-user:new-pass@example.com/callback?token=current-token#current-fragment")) { + InvocationTargetException error = assertThrows(InvocationTargetException.class, + () -> preserveMethod.invoke(service, target, mismatch, "callbackUrl")); + assertTrue(error.getCause() instanceof RenException); + } + } + + @Test + void protocolRelativeUrlsRedactUserInfoAndRequireTheSamePublicBaseOnRestore() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method redactMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("redactSensitiveUrl", + String.class, String.class); + redactMethod.setAccessible(true); + Method preserveMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveUrl", + String.class, String.class, String.class); + preserveMethod.setAccessible(true); + + String target = (String) redactMethod.invoke(service, + "//old-user:old-pass@example.com/path?token=old-token", "endpoint"); + assertEquals("//__SNAPSHOT_SECRET_REDACTED__@example.com/path" + + "?token=__SNAPSHOT_SECRET_REDACTED__", target); + assertEquals("//current-user:current-pass@example.com/path?token=current-token", + preserveMethod.invoke(service, target, + "//current-user:current-pass@example.com/path?token=current-token", "endpoint")); + + for (String mismatch : List.of( + "//current-user:current-pass@other.example.com/path?token=current-token", + "//current-user:current-pass@example.com/other?token=current-token", + "https://current-user:current-pass@example.com/path?token=current-token")) { + InvocationTargetException error = assertThrows(InvocationTargetException.class, + () -> preserveMethod.invoke(service, target, mismatch, "endpoint")); + assertTrue(error.getCause() instanceof RenException); + } + } + + @Test + @SuppressWarnings("unchecked") + void restoringOlderStructureDetectsIrreversibleSensitiveRemovals() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveValues", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + method.setAccessible(true); + Method validateMethod = AgentSnapshotServiceImpl.class.getDeclaredMethod( + "validateSensitiveRestoreIsReversible", AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + validateMethod.setAccessible(true); + + AgentSnapshotDataDTO noPluginsTarget = new AgentSnapshotDataDTO(); + noPluginsTarget.setFunctions(List.of()); + AgentSnapshotDataDTO currentWithPlugin = new AgentSnapshotDataDTO(); + currentWithPlugin.setFunctions(List.of(functionInfo("new-plugin", Map.of("api_key", "current-secret")))); + + AgentSnapshotDataDTO removedPlugin = (AgentSnapshotDataDTO) method.invoke(service, noPluginsTarget, + currentWithPlugin); + assertTrue(removedPlugin.getFunctions().isEmpty()); + InvocationTargetException removedPluginError = assertThrows(InvocationTargetException.class, + () -> validateMethod.invoke(service, currentWithPlugin, removedPlugin)); + assertTrue(removedPluginError.getCause() instanceof RenException); + + AgentSnapshotDataDTO headerTarget = new AgentSnapshotDataDTO(); + headerTarget.setFunctions(List.of(functionInfo("plugin", Map.of("headers", List.of( + Map.of("key", "Content-Type", "value", "application/json")))))); + AgentSnapshotDataDTO headerCurrent = new AgentSnapshotDataDTO(); + headerCurrent.setFunctions(List.of(functionInfo("plugin", Map.of("headers", List.of( + Map.of("key", "Authorization", "value", "current-secret"), + Map.of("key", "Content-Type", "value", "text/plain")))))); + + AgentSnapshotDataDTO removedHeader = (AgentSnapshotDataDTO) method.invoke(service, headerTarget, + headerCurrent); + List> headers = (List>) removedHeader.getFunctions().get(0) + .getParamInfo().get("headers"); + assertEquals(1, headers.size()); + assertEquals("Content-Type", headers.get(0).get("key")); + assertEquals("application/json", headers.get(0).get("value")); + InvocationTargetException removedHeaderError = assertThrows(InvocationTargetException.class, + () -> validateMethod.invoke(service, headerCurrent, removedHeader)); + assertTrue(removedHeaderError.getCause() instanceof RenException); + + AgentSnapshotDataDTO urlTarget = new AgentSnapshotDataDTO(); + urlTarget.setFunctions(List.of(functionInfo("plugin", Map.of("endpoint", + "https://example.com/hook?locale=en")))); + AgentSnapshotDataDTO urlCurrent = new AgentSnapshotDataDTO(); + urlCurrent.setFunctions(List.of(functionInfo("plugin", Map.of("endpoint", + "https://example.com/hook?api_key=current-secret&locale=de")))); + AgentSnapshotDataDTO removedUrlSecret = (AgentSnapshotDataDTO) method.invoke(service, urlTarget, urlCurrent); + assertEquals("https://example.com/hook?locale=en", + removedUrlSecret.getFunctions().get(0).getParamInfo().get("endpoint")); + InvocationTargetException removedUrlError = assertThrows(InvocationTargetException.class, + () -> validateMethod.invoke(service, urlCurrent, removedUrlSecret)); + assertTrue(removedUrlError.getCause() instanceof RenException); + } + + @Test + void ambiguousOrHistoricalRawSensitiveTargetsAreRejectedInsteadOfGuessed() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("preserveCurrentSensitiveValues", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + method.setAccessible(true); + + AgentSnapshotDataDTO ambiguous = new AgentSnapshotDataDTO(); + ambiguous.setFunctions(List.of(functionInfo("plugin", Map.of("headers", List.of( + Map.of("value", "__SNAPSHOT_SECRET_REDACTED__")))))); + InvocationTargetException ambiguousError = assertThrows(InvocationTargetException.class, + () -> method.invoke(service, ambiguous, new AgentSnapshotDataDTO())); + assertTrue(ambiguousError.getCause() instanceof RenException); + + AgentSnapshotDataDTO conflictingIdentities = new AgentSnapshotDataDTO(); + conflictingIdentities.setFunctions(List.of(functionInfo("plugin", Map.of("headers", List.of( + Map.of("name", "Shared", "key", "Authorization", "value", + "__SNAPSHOT_SECRET_REDACTED__")))))); + AgentSnapshotDataDTO conflictingCurrent = new AgentSnapshotDataDTO(); + conflictingCurrent.setFunctions(List.of(functionInfo("plugin", Map.of("headers", List.of( + Map.of("name", "Shared", "key", "Cookie", "value", "cookie-secret"), + Map.of("name", "Different", "key", "Authorization", "value", "auth-secret")))))); + InvocationTargetException conflictingError = assertThrows(InvocationTargetException.class, + () -> method.invoke(service, conflictingIdentities, conflictingCurrent)); + assertTrue(conflictingError.getCause() instanceof RenException); + + AgentSnapshotDataDTO historicalRaw = new AgentSnapshotDataDTO(); + historicalRaw.setFunctions(List.of(functionInfo("plugin", Map.of("Authorization", "old-raw-secret")))); + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setFunctions(List.of(functionInfo("plugin", Map.of()))); + InvocationTargetException rawSecretError = assertThrows(InvocationTargetException.class, + () -> method.invoke(service, historicalRaw, current)); + assertTrue(rawSecretError.getCause() instanceof RenException); + + AgentSnapshotDataDTO historicalRawUrl = new AgentSnapshotDataDTO(); + historicalRawUrl.setFunctions(List.of(functionInfo("plugin", Map.of("endpoint", + "https://example.com/hook?api_key=historical-secret&locale=en")))); + AgentSnapshotDataDTO currentUrlWithoutSecret = new AgentSnapshotDataDTO(); + currentUrlWithoutSecret.setFunctions(List.of(functionInfo("plugin", Map.of("endpoint", + "https://example.com/hook?locale=de")))); + InvocationTargetException rawUrlSecretError = assertThrows(InvocationTargetException.class, + () -> method.invoke(service, historicalRawUrl, currentUrlWithoutSecret)); + assertTrue(rawUrlSecretError.getCause() instanceof RenException); + } + + @Test + @SuppressWarnings("unchecked") + void getChangedFieldsFollowsCentralFieldOrder() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("getChangedFields", + AgentSnapshotDataDTO.class, AgentUpdateDTO.class); + method.setAccessible(true); + + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setAgentName("old-name"); + current.setCorrectWordFileIds(List.of("b", "a")); + + AgentUpdateDTO pendingUpdate = new AgentUpdateDTO(); + pendingUpdate.setAgentName("new-name"); + pendingUpdate.setCorrectWordFileIds(List.of("a", "b")); + AgentUpdateDTO.FunctionInfo function = new AgentUpdateDTO.FunctionInfo(); + function.setPluginId("rag"); + function.setParamInfo(Map.of("api_key", "secret-key")); + pendingUpdate.setFunctions(List.of(function)); + + List changedFields = (List) method.invoke(service, current, pendingUpdate); + + assertEquals(List.of(AgentSnapshotField.AGENT_NAME.getFieldName(), + AgentSnapshotField.FUNCTIONS.getFieldName()), changedFields); + } + + @Test + @SuppressWarnings("unchecked") + void tagIdsAreNotExposedAsIndependentSnapshotFields() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("getChangedFields", + AgentSnapshotDataDTO.class, AgentUpdateDTO.class); + method.setAccessible(true); + + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setTagNames(List.of("alpha", "beta")); + + AgentUpdateDTO pendingUpdate = new AgentUpdateDTO(); + pendingUpdate.setTagNames(List.of("beta", "alpha")); + pendingUpdate.setTagIds(List.of("new-id")); + + List changedFields = (List) method.invoke(service, current, pendingUpdate); + + assertFalse(AgentSnapshotField.names().contains("tagIds")); + assertFalse(changedFields.contains("tagIds")); + assertTrue(changedFields.isEmpty()); + + pendingUpdate.setTagNames(List.of("alpha", "gamma")); + changedFields = (List) method.invoke(service, current, pendingUpdate); + + assertEquals(List.of(AgentSnapshotField.TAG_NAMES.getFieldName()), changedFields); + } + + @Test + @SuppressWarnings("unchecked") + void blankSummaryMemoryValuesAreNotSnapshotChanges() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("getChangedFields", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + method.setAccessible(true); + + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setSummaryMemory(null); + AgentSnapshotDataDTO next = new AgentSnapshotDataDTO(); + next.setSummaryMemory(""); + + List changedFields = (List) method.invoke(service, current, next); + + assertFalse(changedFields.contains(AgentSnapshotField.SUMMARY_MEMORY.getFieldName())); + assertTrue(changedFields.isEmpty()); + } + + @Test + @SuppressWarnings("unchecked") + void nullTtsAdvancedValuesDifferFromExplicitZero() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("getChangedFields", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + method.setAccessible(true); + + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setTtsVolume(null); + current.setTtsRate(null); + current.setTtsPitch(null); + AgentSnapshotDataDTO next = new AgentSnapshotDataDTO(); + next.setTtsVolume(0); + next.setTtsRate(0); + next.setTtsPitch(0); + + List changedFields = (List) method.invoke(service, current, next); + + assertEquals(List.of( + AgentSnapshotField.TTS_VOLUME.getFieldName(), + AgentSnapshotField.TTS_RATE.getFieldName(), + AgentSnapshotField.TTS_PITCH.getFieldName()), changedFields); + } + + @Test + @SuppressWarnings("unchecked") + void redactedSecretsDoNotCreateFalseSnapshotChangeButNonSensitiveValuesDo() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("getChangedFields", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + method.setAccessible(true); + + AgentSnapshotDataDTO stored = buildSnapshot( + "__SNAPSHOT_SECRET_REDACTED__", "__SNAPSHOT_SECRET_REDACTED__", "same-value"); + AgentSnapshotDataDTO current = buildSnapshot("current-key", "current-token", "same-value"); + + List changedFields = (List) method.invoke(service, stored, current); + + assertTrue(changedFields.isEmpty()); + + current.getFunctions().get(0).getParamInfo().put("description", "changed-value"); + changedFields = (List) method.invoke(service, stored, current); + + assertEquals(List.of(AgentSnapshotField.FUNCTIONS.getFieldName()), changedFields); + } + + @Test + @SuppressWarnings("unchecked") + void explicitTtsLanguageIsStoredAsSnapshotChangeEvenWhenItMatchesVoiceDefault() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("getChangedFields", + AgentSnapshotDataDTO.class, AgentSnapshotDataDTO.class); + method.setAccessible(true); + + AgentSnapshotDataDTO current = new AgentSnapshotDataDTO(); + current.setTtsVoiceId("voice-id"); + current.setTtsLanguage(null); + AgentSnapshotDataDTO next = new AgentSnapshotDataDTO(); + next.setTtsVoiceId("voice-id"); + next.setTtsLanguage("普通话"); + + List changedFields = (List) method.invoke(service, current, next); + + assertEquals(List.of(AgentSnapshotField.TTS_LANGUAGE.getFieldName()), changedFields); + } + + @Test + void tagOnlySavePathCreatesSnapshot() throws Exception { + String controller = Files.readString(Path.of("src/main/java/xiaozhi/modules/agent/controller/AgentController.java")); + String roleConfig = Files.readString(Path.of("../manager-web/src/views/roleConfig.vue")); + + assertTrue(controller.contains("agentService.updateAgentById(id, dto);")); + assertFalse(controller.contains("agentService.updateAgentById(id, dto, false);")); + assertTrue(roleConfig.contains("configData.tagNames = tagNames;")); + assertFalse(roleConfig.contains("this.handleSaveAgentTags(agentId, tagNames)")); + } + + @Test + void firstAgentSaveKeepsInitialBaselineBeforePersistingNewState() { + AgentDao agentDao = mock(AgentDao.class); + AgentContextProviderService contextProviderService = mock(AgentContextProviderService.class); + CorrectWordFileService correctWordFileService = mock(CorrectWordFileService.class); + AgentSnapshotService snapshotService = mock(AgentSnapshotService.class); + AgentServiceImpl service = new AgentServiceImpl(agentDao, null, null, null, null, null, null, null, + null, null, contextProviderService, null, correctWordFileService, snapshotService); + ReflectionTestUtils.setField(service, "baseDao", agentDao); + + String agentId = "agent-id"; + AgentEntity lockedAgent = new AgentEntity(); + lockedAgent.setId(agentId); + AgentInfoVO currentAgent = new AgentInfoVO(); + currentAgent.setId(agentId); + currentAgent.setAgentName("old-name"); + AgentUpdateDTO update = new AgentUpdateDTO(); + update.setAgentName("new-name"); + + when(agentDao.selectByIdForUpdate(agentId)).thenReturn(lockedAgent); + when(agentDao.selectAgentInfoById(agentId)).thenReturn(currentAgent); + when(snapshotService.getCurrentVersionNo(agentId)).thenReturn(0); + when(contextProviderService.getByAgentId(agentId)).thenReturn(null); + when(correctWordFileService.getAgentCorrectWordFileIds(agentId)).thenReturn(List.of()); + when(agentDao.updateById(any(AgentEntity.class))).thenReturn(1); + + service.updateAgentById(agentId, update); + + InOrder inOrder = inOrder(agentDao, snapshotService); + inOrder.verify(snapshotService).createSnapshot(agentId, "initial"); + inOrder.verify(agentDao).updateById(argThat((AgentEntity agent) -> "new-name".equals(agent.getAgentName()))); + inOrder.verify(snapshotService).createSnapshot(agentId, "config"); + } + + @Test + void subsequentAgentSaveCapturesUnversionedCurrentStateBeforePersistingNewState() { + AgentDao agentDao = mock(AgentDao.class); + AgentContextProviderService contextProviderService = mock(AgentContextProviderService.class); + CorrectWordFileService correctWordFileService = mock(CorrectWordFileService.class); + AgentSnapshotService snapshotService = mock(AgentSnapshotService.class); + AgentServiceImpl service = new AgentServiceImpl(agentDao, null, null, null, null, null, null, null, + null, null, contextProviderService, null, correctWordFileService, snapshotService); + ReflectionTestUtils.setField(service, "baseDao", agentDao); + + String agentId = "agent-id"; + AgentEntity lockedAgent = new AgentEntity(); + lockedAgent.setId(agentId); + AgentInfoVO currentAgent = new AgentInfoVO(); + currentAgent.setId(agentId); + currentAgent.setAgentName("old-name"); + AgentUpdateDTO update = new AgentUpdateDTO(); + update.setAgentName("new-name"); + + when(agentDao.selectByIdForUpdate(agentId)).thenReturn(lockedAgent); + when(agentDao.selectAgentInfoById(agentId)).thenReturn(currentAgent); + when(snapshotService.getCurrentVersionNo(agentId)).thenReturn(4); + when(contextProviderService.getByAgentId(agentId)).thenReturn(null); + when(correctWordFileService.getAgentCorrectWordFileIds(agentId)).thenReturn(List.of()); + when(agentDao.updateById(any(AgentEntity.class))).thenReturn(1); + + service.updateAgentById(agentId, update); + + InOrder inOrder = inOrder(agentDao, snapshotService); + inOrder.verify(snapshotService).createSnapshot(agentId, "current"); + inOrder.verify(agentDao).updateById(argThat((AgentEntity agent) -> "new-name".equals(agent.getAgentName()))); + inOrder.verify(snapshotService).createSnapshot(agentId, "config"); + } + + @Test + void createAgentPersistsDisplayDefaultsBeforeInitialSnapshot() { + AgentDao agentDao = mock(AgentDao.class); + TimbreService timbreService = mock(TimbreService.class); + AgentPluginMappingService pluginMappingService = mock(AgentPluginMappingService.class); + AgentTemplateService templateService = mock(AgentTemplateService.class); + ModelProviderService providerService = mock(ModelProviderService.class); + AgentSnapshotService snapshotService = mock(AgentSnapshotService.class); + AgentServiceImpl service = new AgentServiceImpl(agentDao, null, timbreService, null, null, null, + pluginMappingService, null, templateService, providerService, null, null, null, snapshotService); + ReflectionTestUtils.setField(service, "baseDao", agentDao); + + AgentTemplateEntity template = new AgentTemplateEntity(); + template.setTtsModelId("TTS_EdgeTTS"); + template.setTtsVoiceId("TTS_EdgeTTS0001"); + template.setMemModelId("Memory_nomem"); + template.setSummaryMemory(null); + when(templateService.getDefaultTemplate()).thenReturn(template); + + when(timbreService.getDefaultLanguageById("TTS_EdgeTTS0001")).thenReturn("普通话"); + when(agentDao.insert(any(AgentEntity.class))).thenReturn(1); + + AgentCreateDTO dto = new AgentCreateDTO(); + dto.setAgentName("test123"); + + String agentId = service.createAgent(dto); + + InOrder inOrder = inOrder(agentDao, pluginMappingService, snapshotService); + inOrder.verify(agentDao).insert(argThat((AgentEntity agent) -> "test123".equals(agent.getAgentName()) + && "普通话".equals(agent.getTtsLanguage()) + && "".equals(agent.getSummaryMemory()) + && Integer.valueOf(0).equals(agent.getChatHistoryConf()))); + inOrder.verify(pluginMappingService).saveBatch(any(), eq(IRepository.DEFAULT_BATCH_SIZE)); + inOrder.verify(snapshotService).createSnapshot(agentId, "initial"); + } + + @Test + void agentSnapshotFieldAppliesRestorableAgentFields() { + AgentSnapshotDataDTO data = new AgentSnapshotDataDTO(); + data.setAgentName("restored-name"); + data.setLlmModelId("llm-new"); + data.setSystemPrompt("restored prompt"); + data.setSort(7); + + AgentEntity agent = new AgentEntity(); + for (AgentSnapshotField field : AgentSnapshotField.values()) { + field.applyTo(agent, data); + } + + assertEquals("restored-name", agent.getAgentName()); + assertEquals("llm-new", agent.getLlmModelId()); + assertEquals("restored prompt", agent.getSystemPrompt()); + assertEquals(7, agent.getSort()); + } + + @Test + void restoreSnapshotRollsBackForAnyException() throws Exception { + Method method = AgentSnapshotServiceImpl.class.getMethod("restoreSnapshot", String.class, String.class, + String.class); + + Transactional transactional = method.getAnnotation(Transactional.class); + + assertNotNull(transactional); + assertTrue(List.of(transactional.rollbackFor()).contains(Exception.class)); + } + + @Test + void restoreSnapshotRejectsStalePreviewTokenBeforeAnyMutation() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentDao agentDao = mock(AgentDao.class); + AgentTagDao tagDao = mock(AgentTagDao.class); + AgentPluginMappingService pluginMappingService = mock(AgentPluginMappingService.class); + AgentContextProviderService contextProviderService = mock(AgentContextProviderService.class); + CorrectWordFileService correctWordFileService = mock(CorrectWordFileService.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, agentDao, tagDao, null, + pluginMappingService, contextProviderService, null, null, null, correctWordFileService); + ReflectionTestUtils.setField(service, "baseDao", snapshotDao); + + String agentId = "agent-id"; + String targetId = "target-id"; + AgentEntity lockedAgent = new AgentEntity(); + lockedAgent.setId(agentId); + when(agentDao.selectByIdForUpdate(agentId)).thenReturn(lockedAgent); + when(snapshotDao.selectById(targetId)) + .thenReturn(snapshotEntity(targetId, agentId, 2, snapshotData("target", "target-summary"))); + when(agentDao.selectAgentInfoById(agentId)) + .thenReturn(snapshotAgentInfo(agentId, 7L, "changed-after-preview", "live-summary")); + when(contextProviderService.getByAgentId(agentId)).thenReturn(null); + when(correctWordFileService.getAgentCorrectWordFileIds(agentId)).thenReturn(List.of()); + when(tagDao.selectByAgentId(agentId)).thenReturn(List.of()); + + RenException error = assertThrows(RenException.class, + () -> service.restoreSnapshot(agentId, targetId, "stale-token")); + + assertTrue(error.getMessage().contains("重新打开恢复预览")); + verify(snapshotDao, never()).selectLatestSnapshot(agentId); + verify(snapshotDao, never()).insertWithNextVersion(any()); + verify(agentDao, never()).updateSnapshotFields(any()); + verify(pluginMappingService, never()).deleteByAgentId(any()); + } + + @Test + void restoreSnapshotBacksUpUnversionedMemoryThenStoresAppliedStateAsLatest() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentDao agentDao = mock(AgentDao.class); + AgentTagDao tagDao = mock(AgentTagDao.class); + AgentTagRelationDao tagRelationDao = mock(AgentTagRelationDao.class); + AgentPluginMappingService pluginMappingService = mock(AgentPluginMappingService.class); + AgentContextProviderService contextProviderService = mock(AgentContextProviderService.class); + AgentTagService tagService = mock(AgentTagService.class); + AgentChatHistoryService chatHistoryService = mock(AgentChatHistoryService.class); + CorrectWordFileService correctWordFileService = mock(CorrectWordFileService.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, agentDao, tagDao, tagRelationDao, + pluginMappingService, contextProviderService, tagService, chatHistoryService, null, + correctWordFileService); + ReflectionTestUtils.setField(service, "baseDao", snapshotDao); + + String agentId = "agent-id"; + String targetId = "target-id"; + AgentEntity lockedAgent = new AgentEntity(); + lockedAgent.setId(agentId); + lockedAgent.setUserId(7L); + AgentInfoVO currentInfo = snapshotAgentInfo(agentId, 7L, "current-name", "live-summary"); + AgentInfoVO restoredInfo = snapshotAgentInfo(agentId, 7L, "target-name", "target-summary"); + AgentSnapshotDataDTO currentData = snapshotData("current-name", "live-summary"); + AgentSnapshotDataDTO latestData = snapshotData("current-name", "snapshot-summary"); + AgentSnapshotDataDTO targetData = snapshotData("target-name", "target-summary"); + AgentSnapshotEntity target = snapshotEntity(targetId, agentId, 2, targetData); + AgentSnapshotEntity latest = snapshotEntity("latest-id", agentId, 5, latestData); + + when(agentDao.selectByIdForUpdate(agentId)).thenReturn(lockedAgent); + when(snapshotDao.selectById(targetId)).thenReturn(target); + when(agentDao.selectAgentInfoById(agentId)).thenReturn(currentInfo, restoredInfo); + when(snapshotDao.selectLatestSnapshot(agentId)).thenReturn(latest); + when(contextProviderService.getByAgentId(agentId)).thenReturn(null); + when(correctWordFileService.getAgentCorrectWordFileIds(agentId)).thenReturn(List.of()); + when(tagDao.selectByAgentId(agentId)).thenReturn(List.of()); + when(agentDao.updateSnapshotFields(any())).thenReturn(1); + when(snapshotDao.insertWithNextVersion(any())).thenReturn(1); + + service.restoreSnapshot(agentId, targetId, currentStateToken(service, currentData)); + + ArgumentCaptor snapshotCaptor = ArgumentCaptor.forClass(AgentSnapshotEntity.class); + verify(snapshotDao, org.mockito.Mockito.times(2)).insertWithNextVersion(snapshotCaptor.capture()); + List inserted = snapshotCaptor.getAllValues(); + AgentSnapshotEntity backup = inserted.get(0); + AgentSnapshotEntity restored = inserted.get(1); + + assertEquals("current", backup.getSource()); + assertNull(backup.getRestoreFromSnapshotId()); + assertNull(backup.getRestoreFromVersionNo()); + assertEquals(List.of(AgentSnapshotField.SUMMARY_MEMORY.getFieldName()), + JsonUtils.parseObject(backup.getChangedFields(), new TypeReference>() { + })); + assertEquals("live-summary", + JsonUtils.parseObject(backup.getSnapshotData(), AgentSnapshotDataDTO.class).getSummaryMemory()); + + assertEquals("restore", restored.getSource()); + assertEquals(targetId, restored.getRestoreFromSnapshotId()); + assertEquals(2, restored.getRestoreFromVersionNo()); + assertEquals("target-name", + JsonUtils.parseObject(restored.getSnapshotData(), AgentSnapshotDataDTO.class).getAgentName()); + assertEquals("target-summary", + JsonUtils.parseObject(restored.getSnapshotData(), AgentSnapshotDataDTO.class).getSummaryMemory()); + + InOrder order = inOrder(snapshotDao, agentDao); + order.verify(snapshotDao).insertWithNextVersion(backup); + order.verify(agentDao).updateSnapshotFields(lockedAgent); + order.verify(snapshotDao).insertWithNextVersion(restored); + verify(snapshotDao).deleteOlderThanKeepLimit(agentId, 100); + } + + @Test + void restoreSnapshotSkipsBackupWhenLatestAlreadyRepresentsCurrentState() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentDao agentDao = mock(AgentDao.class); + AgentTagDao tagDao = mock(AgentTagDao.class); + AgentPluginMappingService pluginMappingService = mock(AgentPluginMappingService.class); + AgentContextProviderService contextProviderService = mock(AgentContextProviderService.class); + AgentTagService tagService = mock(AgentTagService.class); + CorrectWordFileService correctWordFileService = mock(CorrectWordFileService.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, agentDao, tagDao, null, + pluginMappingService, contextProviderService, tagService, null, null, correctWordFileService); + ReflectionTestUtils.setField(service, "baseDao", snapshotDao); + + String agentId = "agent-id"; + String targetId = "target-id"; + AgentEntity lockedAgent = new AgentEntity(); + lockedAgent.setId(agentId); + AgentInfoVO currentInfo = snapshotAgentInfo(agentId, 7L, "current-name", "current-summary"); + AgentInfoVO restoredInfo = snapshotAgentInfo(agentId, 7L, "target-name", "target-summary"); + AgentSnapshotDataDTO currentData = snapshotData("current-name", "current-summary"); + AgentSnapshotEntity target = snapshotEntity(targetId, agentId, 2, + snapshotData("target-name", "target-summary")); + + when(agentDao.selectByIdForUpdate(agentId)).thenReturn(lockedAgent); + when(snapshotDao.selectById(targetId)).thenReturn(target); + when(agentDao.selectAgentInfoById(agentId)).thenReturn(currentInfo, restoredInfo); + when(snapshotDao.selectLatestSnapshot(agentId)).thenReturn(snapshotEntity("latest-id", agentId, 5, currentData)); + when(contextProviderService.getByAgentId(agentId)).thenReturn(null); + when(correctWordFileService.getAgentCorrectWordFileIds(agentId)).thenReturn(List.of()); + when(tagDao.selectByAgentId(agentId)).thenReturn(List.of()); + when(agentDao.updateSnapshotFields(any())).thenReturn(1); + when(snapshotDao.insertWithNextVersion(any())).thenReturn(1); + + service.restoreSnapshot(agentId, targetId, currentStateToken(service, currentData)); + + ArgumentCaptor snapshotCaptor = ArgumentCaptor.forClass(AgentSnapshotEntity.class); + verify(snapshotDao).insertWithNextVersion(snapshotCaptor.capture()); + assertEquals("restore", snapshotCaptor.getValue().getSource()); + assertEquals(targetId, snapshotCaptor.getValue().getRestoreFromSnapshotId()); + verify(snapshotDao).deleteOlderThanKeepLimit(agentId, 100); + } + + @Test + void restoreSnapshotContinuesWhenRelationOnlyChangeReportsZeroUpdatedAgentRows() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentDao agentDao = mock(AgentDao.class); + AgentTagDao tagDao = mock(AgentTagDao.class); + AgentPluginMappingService pluginMappingService = mock(AgentPluginMappingService.class); + AgentContextProviderService contextProviderService = mock(AgentContextProviderService.class); + AgentTagService tagService = mock(AgentTagService.class); + CorrectWordFileService correctWordFileService = mock(CorrectWordFileService.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, agentDao, tagDao, null, + pluginMappingService, contextProviderService, tagService, null, null, correctWordFileService); + ReflectionTestUtils.setField(service, "baseDao", snapshotDao); + + String agentId = "agent-id"; + String targetId = "target-id"; + AgentEntity lockedAgent = new AgentEntity(); + lockedAgent.setId(agentId); + lockedAgent.setUserId(7L); + AgentInfoVO currentInfo = snapshotAgentInfo(agentId, 7L, "same-name", "same-summary"); + AgentInfoVO restoredInfo = snapshotAgentInfo(agentId, 7L, "same-name", "same-summary"); + AgentPluginMapping currentMapping = new AgentPluginMapping(); + currentMapping.setPluginId("plugin"); + currentMapping.setParamInfo("{\"description\":\"current\"}"); + currentInfo.setFunctions(List.of(currentMapping)); + AgentPluginMapping restoredMapping = new AgentPluginMapping(); + restoredMapping.setPluginId("plugin"); + restoredMapping.setParamInfo("{\"description\":\"target\"}"); + restoredInfo.setFunctions(List.of(restoredMapping)); + + AgentSnapshotDataDTO currentData = snapshotData("same-name", "same-summary"); + currentData.setFunctions(List.of(functionInfo("plugin", Map.of("description", "current")))); + AgentSnapshotDataDTO targetData = snapshotData("same-name", "same-summary"); + targetData.setFunctions(List.of(functionInfo("plugin", Map.of("description", "target")))); + + when(agentDao.selectByIdForUpdate(agentId)).thenReturn(lockedAgent); + when(snapshotDao.selectById(targetId)).thenReturn(snapshotEntity(targetId, agentId, 2, targetData)); + when(agentDao.selectAgentInfoById(agentId)).thenReturn(currentInfo, restoredInfo); + when(snapshotDao.selectLatestSnapshot(agentId)) + .thenReturn(snapshotEntity("latest-id", agentId, 5, currentData)); + when(contextProviderService.getByAgentId(agentId)).thenReturn(null); + when(correctWordFileService.getAgentCorrectWordFileIds(agentId)).thenReturn(List.of()); + when(tagDao.selectByAgentId(agentId)).thenReturn(List.of()); + when(agentDao.updateSnapshotFields(any())).thenReturn(0); + when(snapshotDao.insertWithNextVersion(any())).thenReturn(1); + + service.restoreSnapshot(agentId, targetId, currentStateToken(service, currentData)); + + verify(pluginMappingService).deleteByAgentId(agentId); + verify(pluginMappingService).saveBatch(argThat(mappings -> { + AgentPluginMapping mapping = mappings.size() == 1 ? mappings.iterator().next() : null; + return mapping != null + && "plugin".equals(mapping.getPluginId()) + && mapping.getParamInfo().contains("target"); + }), eq(IRepository.DEFAULT_BATCH_SIZE)); + verify(snapshotDao).insertWithNextVersion(argThat(snapshot -> "restore".equals(snapshot.getSource()))); + } + + @Test + void restoreSnapshotExplicitlyPersistsNullableFieldsAsNull() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentDao agentDao = mock(AgentDao.class); + AgentTagDao tagDao = mock(AgentTagDao.class); + AgentPluginMappingService pluginMappingService = mock(AgentPluginMappingService.class); + AgentContextProviderService contextProviderService = mock(AgentContextProviderService.class); + AgentTagService tagService = mock(AgentTagService.class); + CorrectWordFileService correctWordFileService = mock(CorrectWordFileService.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, agentDao, tagDao, null, + pluginMappingService, contextProviderService, tagService, null, null, correctWordFileService); + ReflectionTestUtils.setField(service, "baseDao", snapshotDao); + + String agentId = "agent-id"; + String targetId = "target-id"; + AgentEntity lockedAgent = new AgentEntity(); + lockedAgent.setId(agentId); + lockedAgent.setUserId(7L); + lockedAgent.setTtsLanguage("普通话"); + lockedAgent.setTtsVolume(0); + lockedAgent.setTtsRate(0); + lockedAgent.setTtsPitch(0); + lockedAgent.setSlmModelId("slm-id"); + lockedAgent.setVllmModelId("vllm-id"); + lockedAgent.setIntentModelId("intent-id"); + lockedAgent.setSystemPrompt("old prompt"); + + AgentInfoVO currentInfo = snapshotAgentInfo(agentId, 7L, "same-name", "same-summary"); + currentInfo.setTtsLanguage("普通话"); + currentInfo.setTtsVolume(0); + currentInfo.setTtsRate(0); + currentInfo.setTtsPitch(0); + currentInfo.setSlmModelId("slm-id"); + currentInfo.setVllmModelId("vllm-id"); + currentInfo.setIntentModelId("intent-id"); + currentInfo.setSystemPrompt("old prompt"); + AgentInfoVO restoredInfo = snapshotAgentInfo(agentId, 7L, "same-name", "same-summary"); + + AgentSnapshotDataDTO currentData = snapshotData("same-name", "same-summary"); + currentData.setTtsLanguage("普通话"); + currentData.setTtsVolume(0); + currentData.setTtsRate(0); + currentData.setTtsPitch(0); + currentData.setSlmModelId("slm-id"); + currentData.setVllmModelId("vllm-id"); + currentData.setIntentModelId("intent-id"); + currentData.setSystemPrompt("old prompt"); + AgentSnapshotDataDTO targetData = snapshotData("same-name", "same-summary"); + + when(agentDao.selectByIdForUpdate(agentId)).thenReturn(lockedAgent); + when(snapshotDao.selectById(targetId)).thenReturn(snapshotEntity(targetId, agentId, 2, targetData)); + when(agentDao.selectAgentInfoById(agentId)).thenReturn(currentInfo, restoredInfo); + when(snapshotDao.selectLatestSnapshot(agentId)) + .thenReturn(snapshotEntity("latest-id", agentId, 5, currentData)); + when(contextProviderService.getByAgentId(agentId)).thenReturn(null); + when(correctWordFileService.getAgentCorrectWordFileIds(agentId)).thenReturn(List.of()); + when(tagDao.selectByAgentId(agentId)).thenReturn(List.of()); + when(agentDao.updateSnapshotFields(any())).thenReturn(1); + when(snapshotDao.insertWithNextVersion(any())).thenReturn(1); + + service.restoreSnapshot(agentId, targetId, currentStateToken(service, currentData)); + + verify(agentDao).updateSnapshotFields(argThat(agent -> agent.getTtsLanguage() == null + && agent.getTtsVolume() == null + && agent.getTtsRate() == null + && agent.getTtsPitch() == null + && agent.getSlmModelId() == null + && agent.getVllmModelId() == null + && agent.getIntentModelId() == null + && agent.getSystemPrompt() == null + && Long.valueOf(7L).equals(agent.getUserId()))); + ArgumentCaptor snapshotCaptor = ArgumentCaptor.forClass(AgentSnapshotEntity.class); + verify(snapshotDao).insertWithNextVersion(snapshotCaptor.capture()); + AgentSnapshotDataDTO latestData = JsonUtils.parseObject(snapshotCaptor.getValue().getSnapshotData(), + AgentSnapshotDataDTO.class); + assertEquals("restore", snapshotCaptor.getValue().getSource()); + assertNull(latestData.getTtsLanguage()); + assertNull(latestData.getTtsVolume()); + assertNull(latestData.getTtsRate()); + assertNull(latestData.getTtsPitch()); + assertNull(latestData.getSlmModelId()); + assertNull(latestData.getVllmModelId()); + assertNull(latestData.getIntentModelId()); + assertNull(latestData.getSystemPrompt()); + verify(agentDao, org.mockito.Mockito.times(2)).selectAgentInfoById(agentId); + } + + @Test + void restoreSnapshotDoesNotMutateOrWriteHistoryWhenTargetMatchesCurrentState() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentDao agentDao = mock(AgentDao.class); + AgentTagDao tagDao = mock(AgentTagDao.class); + AgentPluginMappingService pluginMappingService = mock(AgentPluginMappingService.class); + AgentContextProviderService contextProviderService = mock(AgentContextProviderService.class); + AgentTagService tagService = mock(AgentTagService.class); + CorrectWordFileService correctWordFileService = mock(CorrectWordFileService.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, agentDao, tagDao, null, + pluginMappingService, contextProviderService, tagService, null, null, correctWordFileService); + ReflectionTestUtils.setField(service, "baseDao", snapshotDao); + + String agentId = "agent-id"; + String targetId = "target-id"; + AgentEntity lockedAgent = new AgentEntity(); + lockedAgent.setId(agentId); + AgentInfoVO currentInfo = snapshotAgentInfo(agentId, 7L, "same-name", "same-summary"); + AgentSnapshotDataDTO currentData = snapshotData("same-name", "same-summary"); + AgentSnapshotEntity target = snapshotEntity(targetId, agentId, 3, currentData); + + when(agentDao.selectByIdForUpdate(agentId)).thenReturn(lockedAgent); + when(snapshotDao.selectById(targetId)).thenReturn(target); + when(agentDao.selectAgentInfoById(agentId)).thenReturn(currentInfo); + when(contextProviderService.getByAgentId(agentId)).thenReturn(null); + when(correctWordFileService.getAgentCorrectWordFileIds(agentId)).thenReturn(List.of()); + when(tagDao.selectByAgentId(agentId)).thenReturn(List.of()); + + service.restoreSnapshot(agentId, targetId, currentStateToken(service, currentData)); + + verify(snapshotDao, never()).selectLatestSnapshot(agentId); + verify(snapshotDao, never()).insertWithNextVersion(any()); + verify(snapshotDao, never()).deleteOlderThanKeepLimit(any(), anyInt()); + verify(agentDao, never()).updateSnapshotFields(any()); + verify(pluginMappingService, never()).deleteByAgentId(any()); + verify(contextProviderService, never()).saveOrUpdateByAgentId(any()); + verify(correctWordFileService, never()).saveAgentCorrectWords(any(), any()); + verify(tagService, never()).saveAgentTags(any(), any(), any()); + } + + @Test + void deleteSnapshotRollsBackForAnyException() throws Exception { + Method method = AgentSnapshotServiceImpl.class.getMethod("deleteSnapshot", String.class, String.class); + + Transactional transactional = method.getAnnotation(Transactional.class); + + assertNotNull(transactional); + assertTrue(List.of(transactional.rollbackFor()).contains(Exception.class)); + } + + @Test + void deleteSnapshotLocksAgentBeforeReadingAndDeletingSnapshot() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentDao agentDao = mock(AgentDao.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, agentDao, null, null, null, null, + null, null, null, null); + ReflectionTestUtils.setField(service, "baseDao", snapshotDao); + + String agentId = "agent-id"; + String snapshotId = "snapshot-id"; + AgentEntity agent = new AgentEntity(); + agent.setId(agentId); + AgentSnapshotEntity snapshot = new AgentSnapshotEntity(); + snapshot.setId(snapshotId); + snapshot.setAgentId(agentId); + snapshot.setVersionNo(2); + + when(agentDao.selectByIdForUpdate(agentId)).thenReturn(agent); + when(snapshotDao.selectById(snapshotId)).thenReturn(snapshot); + when(snapshotDao.selectMaxVersionNo(agentId)).thenReturn(3); + when(snapshotDao.deleteById(snapshotId)).thenReturn(1); + + service.deleteSnapshot(agentId, snapshotId); + + InOrder order = inOrder(agentDao, snapshotDao); + order.verify(agentDao).selectByIdForUpdate(agentId); + order.verify(snapshotDao).selectById(snapshotId); + order.verify(snapshotDao).selectMaxVersionNo(agentId); + order.verify(snapshotDao).deleteById(snapshotId); + } + + @Test + void snapshotInsertAllocatesVersionInSingleSqlStatement() throws Exception { + String xml = normalizeWhitespace(Files.readString(Path.of("src/main/resources/mapper/agent/AgentSnapshotDao.xml"))); + String dao = Files.readString(Path.of("src/main/java/xiaozhi/modules/agent/dao/AgentSnapshotDao.java")); + + assertTrue(dao.contains("insertWithNextVersion")); + assertTrue(xml.contains("")); + assertTrue(xml.contains("INSERT INTO ai_agent_snapshot")); + assertTrue(xml.contains("COALESCE(MAX(version_no), 0) + 1")); + assertFalse(xml.contains("LAST_INSERT_ID")); + assertFalse(xml.contains("ai_agent_snapshot_sequence")); + } + + @Test + void restoreUpdateSqlWritesNullableSnapshotFieldsWithoutOwnershipColumns() throws Exception { + String xml = Files.readString(Path.of("src/main/resources/mapper/agent/AgentDao.xml")); + int updateStart = xml.indexOf(""); + int updateEnd = xml.indexOf("", updateStart); + assertTrue(updateStart >= 0); + assertTrue(updateEnd > updateStart); + String updateSql = normalizeWhitespace(xml.substring(updateStart, updateEnd)); + + for (AgentSnapshotField field : AgentSnapshotField.values()) { + if (!field.isRestorableAgentField()) { + continue; + } + String column = field.getFieldName().replaceAll("([a-z0-9])([A-Z])", "$1_$2") + .toLowerCase(Locale.ROOT); + assertTrue(updateSql.contains(column + " = #{agent." + field.getFieldName() + ","), + () -> "Missing explicit restore assignment for " + field.getFieldName()); + } + assertTrue(updateSql.contains("tts_language = #{agent.ttsLanguage,jdbcType=VARCHAR}")); + assertTrue(updateSql.contains("tts_volume = #{agent.ttsVolume,jdbcType=INTEGER}")); + assertTrue(updateSql.contains("slm_model_id = #{agent.slmModelId,jdbcType=VARCHAR}")); + assertTrue(updateSql.contains("vllm_model_id = #{agent.vllmModelId,jdbcType=VARCHAR}")); + assertTrue(updateSql.contains("intent_model_id = #{agent.intentModelId,jdbcType=VARCHAR}")); + assertTrue(updateSql.contains("system_prompt = #{agent.systemPrompt,jdbcType=LONGVARCHAR}")); + assertTrue(updateSql.contains("summary_memory = #{agent.summaryMemory,jdbcType=LONGVARCHAR}")); + assertFalse(updateSql.contains("user_id =")); + assertFalse(updateSql.contains("creator =")); + assertFalse(updateSql.contains("created_at =")); + } + + @Test + void snapshotMigrationIsMergedIntoSingleChangeLog() throws Exception { + String sql = Files.readString(Path.of("src/main/resources/db/changelog/202607071530.sql")); + String master = Files.readString(Path.of("src/main/resources/db/changelog/db.changelog-master.yaml")); + + assertTrue(sql.contains("restore_from_snapshot_id")); + assertTrue(sql.contains("restore_from_version_no")); + assertTrue(sql.contains("idx_snapshot_user_created_at")); + assertTrue(sql.contains("DEFAULT (JSON_OBJECT())")); + assertTrue(master.contains("202607071530.sql")); + assertFalse(master.contains("202607081150.sql")); + assertFalse(master.contains("202607081230.sql")); + } + + @Test + void legacySnapshotRedactionHasItsOwnResumableSchemaVersionChangeLog() throws Exception { + String sql = Files.readString(Path.of("src/main/resources/db/changelog/202607101200.sql")); + String master = Files.readString(Path.of("src/main/resources/db/changelog/db.changelog-master.yaml")); + String mapper = Files.readString(Path.of("src/main/resources/mapper/agent/AgentSnapshotDao.xml")); + + assertTrue(sql.contains("redaction_version")); + assertTrue(sql.contains("idx_snapshot_redaction_version_id")); + assertTrue(sql.contains("-- rollback")); + assertTrue(master.contains("202607101200.sql")); + assertTrue(mapper.contains("selectLegacyRedactionBatch")); + assertTrue(mapper.contains("redaction_version < #{targetRedactionVersion}")); + assertTrue(mapper.contains("")); + } + + @Test + void selectNextSnapshotLoadsRestoreTraceColumnsWithoutPreviousVersionQuery() throws Exception { + String xml = normalizeWhitespace(Files.readString(Path.of("src/main/resources/mapper/agent/AgentSnapshotDao.xml"))); + String dao = Files.readString(Path.of("src/main/java/xiaozhi/modules/agent/dao/AgentSnapshotDao.java")); + + assertTrue(xml.contains("restore_from_snapshot_id AS restoreFromSnapshotId")); + assertTrue(xml.contains("restore_from_version_no AS restoreFromVersionNo")); + assertTrue(xml.contains("version_no > #{versionNo}")); + assertFalse(xml.contains("selectPreviousSnapshot")); + assertFalse(dao.contains("selectPreviousSnapshot")); + } + + @Test + void retentionPruneSqlKeepsLatestVersions() throws Exception { + String xml = Files.readString(Path.of("src/main/resources/mapper/agent/AgentSnapshotDao.xml")); + + assertTrue(xml.contains("deleteOlderThanKeepLimit")); + assertTrue(xml.contains("ORDER BY version_no DESC")); + assertTrue(xml.contains("LIMIT #{keepLimit}")); + } + + @Test + void agentInfoMapperLoadsFunctionsWithJoinInsteadOfNestedSelect() throws Exception { + String xml = Files.readString(Path.of("src/main/resources/mapper/agent/AgentDao.xml")); + + assertTrue(xml.contains("LEFT JOIN ai_agent_plugin_mapping f ON f.agent_id = a.id")); + assertFalse(xml.contains("selectAgentFunctionsByAgentId")); + assertFalse(xml.contains("select=\"selectAgentFunctions")); + } + + @Test + void toVOIncludesRestoreTraceFields() throws Exception { + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, null, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("toVO", + AgentSnapshotEntity.class, boolean.class); + method.setAccessible(true); + + AgentSnapshotEntity entity = new AgentSnapshotEntity(); + entity.setId("snapshot-id"); + entity.setAgentId("agent-id"); + entity.setVersionNo(3); + entity.setChangedFields("[]"); + entity.setSource("restore"); + entity.setRestoreFromSnapshotId("target-id"); + entity.setRestoreFromVersionNo(1); + + AgentSnapshotVO vo = (AgentSnapshotVO) method.invoke(service, entity, false); + + assertEquals("target-id", vo.getRestoreFromSnapshotId()); + assertEquals(1, vo.getRestoreFromVersionNo()); + } + + @Test + void toVOKeepsStoredEventFieldsStableAcrossDeletedVersionGapAndMetadataChanges() throws Exception { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, null, null, null, null, null, null, + null, null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("toVO", + AgentSnapshotEntity.class, boolean.class); + method.setAccessible(true); + + AgentSnapshotEntity current = new AgentSnapshotEntity(); + current.setId("snapshot-id"); + current.setAgentId("agent-id"); + current.setVersionNo(3); + current.setChangedFields(JsonUtils.toJsonString(List.of("ttsLanguage", "ttsVolume"))); + + AgentSnapshotVO vo = (AgentSnapshotVO) method.invoke(service, current, false); + + assertEquals(List.of("ttsLanguage", "ttsVolume"), vo.getChangedFields()); + verifyNoInteractions(snapshotDao); + } + + @Test + void pageUsesPersistedChangedFieldsWithoutPerRecordQueries() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, null, null, null, null, null, null, + null, null, null); + + AgentSnapshotEntity versionFive = new AgentSnapshotEntity(); + versionFive.setVersionNo(5); + versionFive.setChangedFields(JsonUtils.toJsonString(List.of("agentName"))); + AgentSnapshotEntity versionThree = new AgentSnapshotEntity(); + versionThree.setVersionNo(3); + versionThree.setChangedFields(JsonUtils.toJsonString(List.of("ttsLanguage"))); + Page result = new Page<>(1, 10); + result.setRecords(List.of(versionFive, versionThree)); + result.setTotal(2); + when(snapshotDao.selectPage(any(), any())).thenReturn(result); + + List records = service.page("agent-id", new AgentSnapshotPageDTO()).getList(); + + assertEquals(List.of("agentName"), records.get(0).getChangedFields()); + assertEquals(List.of("ttsLanguage"), records.get(1).getChangedFields()); + verify(snapshotDao).selectPage(any(), any()); + verifyNoMoreInteractions(snapshotDao); + } + + @Test + void pageDoesNotCreateInitialSnapshotWhenAgentHasNoHistory() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentDao agentDao = mock(AgentDao.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, agentDao, null, null, null, + null, null, null, null, null); + + when(snapshotDao.selectPage(any(), any())).thenReturn(new Page(1, 10)); + + service.page("agent-id", new AgentSnapshotPageDTO()); + + verify(agentDao, never()).selectByIdForUpdate(any()); + verify(snapshotDao, never()).selectMaxVersionNo(any()); + verify(snapshotDao, never()).insertWithNextVersion(any()); + verify(snapshotDao, never()).deleteOlderThanKeepLimit(any(), anyInt()); + } + + @Test + void getCurrentVersionNoReturnsPersistedMaxVersion() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, null, null, null, null, + null, null, null, null, null); + + when(snapshotDao.selectMaxVersionNo("agent-id")).thenReturn(7); + + assertEquals(7, service.getCurrentVersionNo("agent-id")); + } + + @Test + void createSnapshotStoresCurrentStateAsInitialVersionWhenHistoryIsEmpty() { + AgentSnapshotDao snapshotDao = mock(AgentSnapshotDao.class); + AgentDao agentDao = mock(AgentDao.class); + AgentTagDao tagDao = mock(AgentTagDao.class); + AgentContextProviderService contextProviderService = mock(AgentContextProviderService.class); + CorrectWordFileService correctWordFileService = mock(CorrectWordFileService.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(snapshotDao, agentDao, tagDao, null, null, + contextProviderService, null, null, null, correctWordFileService); + + AgentEntity lockedAgent = new AgentEntity(); + lockedAgent.setId("agent-id"); + AgentInfoVO agentInfo = new AgentInfoVO(); + agentInfo.setId("agent-id"); + agentInfo.setUserId(7L); + agentInfo.setAgentName("agent"); + when(agentDao.selectByIdForUpdate("agent-id")).thenReturn(lockedAgent); + when(agentDao.selectAgentInfoById("agent-id")).thenReturn(agentInfo); + when(snapshotDao.selectLatestSnapshot("agent-id")).thenReturn(null); + when(snapshotDao.insertWithNextVersion(any())).thenReturn(1); + when(correctWordFileService.getAgentCorrectWordFileIds("agent-id")).thenReturn(List.of()); + when(contextProviderService.getByAgentId("agent-id")).thenReturn(null); + when(tagDao.selectByAgentId("agent-id")).thenReturn(List.of()); + + service.createSnapshot("agent-id", "config"); + + verify(snapshotDao).insertWithNextVersion(argThat(snapshot -> "config".equals(snapshot.getSource()) + && snapshot.getVersionNo() == null + && snapshot.getChangedFields().contains("initial"))); + verify(snapshotDao).deleteOlderThanKeepLimit("agent-id", 100); + } + + @Test + void restoreTagRejectsSoftDeletedSnapshotTagWithoutMutatingGlobalTag() throws Exception { + AgentTagDao tagDao = mock(AgentTagDao.class); + AgentSnapshotServiceImpl service = new AgentSnapshotServiceImpl(null, null, tagDao, null, null, null, null, null, + null, null); + Method method = AgentSnapshotServiceImpl.class.getDeclaredMethod("restoreTag", + AgentSnapshotTagDTO.class, Date.class); + method.setAccessible(true); + + AgentTagEntity deletedTag = new AgentTagEntity(); + deletedTag.setId("deleted-tag-id"); + deletedTag.setTagName("archived"); + deletedTag.setDeleted(1); + when(tagDao.selectById("deleted-tag-id")).thenReturn(deletedTag); + + AgentSnapshotTagDTO snapshotTag = new AgentSnapshotTagDTO(); + snapshotTag.setId("deleted-tag-id"); + snapshotTag.setTagName("archived"); + + InvocationTargetException error = assertThrows(InvocationTargetException.class, + () -> method.invoke(service, snapshotTag, new Date())); + + assertTrue(error.getCause() instanceof RenException); + assertEquals("快照引用的标签已被删除,无法恢复,请先重新创建或选择标签", error.getCause().getMessage()); + verify(tagDao, never()).updateById(any(AgentTagEntity.class)); + verify(tagDao, never()).insert(any(AgentTagEntity.class)); + } + + private AgentInfoVO snapshotAgentInfo(String agentId, Long userId, String agentName, String summaryMemory) { + AgentInfoVO info = new AgentInfoVO(); + info.setId(agentId); + info.setUserId(userId); + info.setAgentName(agentName); + info.setSummaryMemory(summaryMemory); + info.setChatHistoryConf(0); + return info; + } + + private AgentSnapshotDataDTO snapshotData(String agentName, String summaryMemory) { + AgentSnapshotDataDTO data = new AgentSnapshotDataDTO(); + data.setAgentName(agentName); + data.setSummaryMemory(summaryMemory); + data.setChatHistoryConf(0); + return data; + } + + private AgentSnapshotDataDTO buildExtendedSensitiveSnapshot() { + AgentSnapshotDataDTO data = new AgentSnapshotDataDTO(); + AgentUpdateDTO.FunctionInfo function = new AgentUpdateDTO.FunctionInfo(); + function.setPluginId("rag"); + Map params = new LinkedHashMap<>(); + params.put("api_key", "secret-api-key"); + params.put("Cookie", "secret-cookie"); + params.put("Set-Cookie", "secret-set-cookie"); + params.put("Proxy-Authorization", "secret-proxy-authorization"); + params.put("X-Session-ID", "secret-session-id"); + params.put("X-Auth", "secret-auth-header"); + params.put("slackWebhookUrl", + "https://hooks.slack.com/services/T111/B222/secret-slack-path"); + params.put("max_tokens", 32); + function.setParamInfo(params); + + ContextProviderDTO provider = new ContextProviderDTO(); + provider.setUrl("https://discord.com/api/webhooks/123456/secret-discord-path"); + Map headers = new LinkedHashMap<>(); + headers.put("Authorization", "secret-authorization"); + headers.put("Cookie", "secret-context-cookie"); + headers.put("PHPSESSID", "secret-php-session"); + headers.put("X-Session", "secret-x-session"); + headers.put("Accept", "application/json"); + provider.setHeaders(headers); + + data.setFunctions(List.of(function)); + data.setContextProviders(List.of(provider)); + return data; + } + + private AgentUpdateDTO.FunctionInfo functionInfo(String pluginId, Map params) { + AgentUpdateDTO.FunctionInfo function = new AgentUpdateDTO.FunctionInfo(); + function.setPluginId(pluginId); + function.setParamInfo(params); + return function; + } + + private void assertExtendedSecretsAbsent(String json) { + for (String secret : List.of( + "secret-api-key", + "secret-cookie", + "secret-set-cookie", + "secret-proxy-authorization", + "secret-session-id", + "secret-auth-header", + "secret-slack-path", + "secret-discord-path", + "secret-authorization", + "secret-context-cookie", + "secret-php-session", + "secret-x-session")) { + assertFalse(json.contains(secret), () -> "Sensitive value leaked: " + secret); + } + } + + private AgentSnapshotEntity snapshotEntity(String snapshotId, String agentId, Integer versionNo, + AgentSnapshotDataDTO data) { + AgentSnapshotEntity entity = new AgentSnapshotEntity(); + entity.setId(snapshotId); + entity.setAgentId(agentId); + entity.setUserId(7L); + entity.setVersionNo(versionNo); + entity.setSnapshotData(JsonUtils.toJsonString(data)); + entity.setChangedFields("[]"); + return entity; + } + + private AgentSnapshotDataDTO buildSnapshot(String apiKey, String authToken, String description) { + AgentSnapshotDataDTO data = new AgentSnapshotDataDTO(); + + AgentUpdateDTO.FunctionInfo function = new AgentUpdateDTO.FunctionInfo(); + function.setPluginId("rag"); + HashMap params = new HashMap<>(); + params.put("api_key", apiKey); + params.put("description", description); + function.setParamInfo(params); + + ContextProviderDTO provider = new ContextProviderDTO(); + provider.setUrl("https://example.com/context"); + provider.setHeaders(Map.of("Authorization", authToken)); + + data.setFunctions(List.of(function)); + data.setContextProviders(List.of(provider)); + return data; + } + + private AgentSnapshotDataDTO nestedWebhookSnapshot(String secret) { + AgentSnapshotDataDTO data = new AgentSnapshotDataDTO(); + data.setFunctions(List.of(functionInfo("plugin", Map.of( + "webhookConfig", Map.of( + "value", "https://capability.example.com/public/" + secret))))); + return data; + } + + private String currentStateToken(AgentSnapshotServiceImpl service, AgentSnapshotDataDTO data) { + return ReflectionTestUtils.invokeMethod(service, "buildCurrentStateToken", data); + } + + private String normalizeWhitespace(String value) { + return value.replaceAll("\\s+", " ").trim(); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/agent/typehandler/ContextProviderListTypeHandlerTest.java b/main/manager-api/src/test/java/xiaozhi/modules/agent/typehandler/ContextProviderListTypeHandlerTest.java new file mode 100644 index 000000000..95c9b1540 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/agent/typehandler/ContextProviderListTypeHandlerTest.java @@ -0,0 +1,73 @@ +package xiaozhi.modules.agent.typehandler; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.List; + +import org.apache.ibatis.type.TypeHandler; +import org.apache.ibatis.type.TypeHandlerRegistry; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import com.fasterxml.jackson.core.type.TypeReference; + +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.modules.agent.dto.ContextProviderDTO; + +class ContextProviderListTypeHandlerTest { + + private final ContextProviderListTypeHandler handler = new ContextProviderListTypeHandler(); + + @Test + void myBatisCanInstantiateHandlerForListField() { + TypeHandler typeHandler = new TypeHandlerRegistry().getInstance(List.class, + ContextProviderListTypeHandler.class); + + assertInstanceOf(ContextProviderListTypeHandler.class, typeHandler); + } + + @Test + void resultSetDeserializationKeepsContextProviderDtoElementType() throws Exception { + ResultSet resultSet = mock(ResultSet.class); + when(resultSet.getString("context_providers")) + .thenReturn("[{\"url\":\"https://example.com/context\",\"headers\":{\"Authorization\":\"Bearer token\"}}]"); + + List providers = handler.getNullableResult(resultSet, "context_providers"); + + assertEquals(1, providers.size()); + assertInstanceOf(ContextProviderDTO.class, providers.get(0)); + assertEquals("https://example.com/context", providers.get(0).getUrl()); + assertEquals("Bearer token", providers.get(0).getHeaders().get("Authorization")); + } + + @Test + void sqlNullRemainsNull() throws Exception { + ResultSet resultSet = mock(ResultSet.class); + + assertNull(handler.getNullableResult(resultSet, 1)); + } + + @Test + void serializesProviderListAsJson() throws Exception { + ContextProviderDTO provider = new ContextProviderDTO(); + provider.setUrl("https://example.com/context"); + PreparedStatement statement = mock(PreparedStatement.class); + + handler.setNonNullParameter(statement, 1, List.of(provider), null); + + ArgumentCaptor json = ArgumentCaptor.forClass(String.class); + verify(statement).setString(eq(1), json.capture()); + List serialized = JsonUtils.parseObject(json.getValue(), new TypeReference<>() { + }); + assertEquals(1, serialized.size()); + assertEquals("https://example.com/context", serialized.get(0).getUrl()); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/config/service/impl/ConfigServiceImplTest.java b/main/manager-api/src/test/java/xiaozhi/modules/config/service/impl/ConfigServiceImplTest.java new file mode 100644 index 000000000..1e76d4b7a --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/config/service/impl/ConfigServiceImplTest.java @@ -0,0 +1,96 @@ +package xiaozhi.modules.config.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import xiaozhi.common.redis.RedisKeys; +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.modules.agent.dao.AgentVoicePrintDao; +import xiaozhi.modules.agent.service.AgentContextProviderService; +import xiaozhi.modules.agent.service.AgentMcpAccessPointService; +import xiaozhi.modules.agent.service.AgentPluginMappingService; +import xiaozhi.modules.agent.service.AgentService; +import xiaozhi.modules.agent.service.AgentTemplateService; +import xiaozhi.modules.correctword.service.CorrectWordFileService; +import xiaozhi.modules.device.service.DeviceService; +import xiaozhi.modules.model.service.ModelConfigService; +import xiaozhi.modules.sys.dto.SysParamsDTO; +import xiaozhi.modules.sys.service.SysParamsService; +import xiaozhi.modules.timbre.service.TimbreService; +import xiaozhi.modules.voiceclone.service.VoiceCloneService; + +class ConfigServiceImplTest { + + @Test + void cachedServerConfigIsCheckedAsAStringKeyedMapWithoutChangingNestedValues() { + RedisUtils redisUtils = mock(RedisUtils.class); + Map nested = new HashMap<>(); + nested.put("enabled", true); + Map cached = new HashMap<>(); + cached.put("features", nested); + when(redisUtils.get(RedisKeys.getServerConfigKey())).thenReturn(cached); + + ConfigServiceImpl service = newService(mock(SysParamsService.class), redisUtils); + + Map result = service.getConfig(true); + + assertNotSame(cached, result); + assertSame(nested, result.get("features")); + assertEquals(true, ((Map) result.get("features")).get("enabled")); + } + + @Test + void nestedSystemParametersStillShareAndPopulateTheSameConfigBranch() { + SysParamsService sysParamsService = mock(SysParamsService.class); + SysParamsDTO enabled = parameter("server.features.enabled", "true", "boolean"); + SysParamsDTO labels = parameter("server.features.labels", "first;second", "array"); + when(sysParamsService.list(anyMap())).thenReturn(List.of(enabled, labels)); + ConfigServiceImpl service = newService(sysParamsService, mock(RedisUtils.class)); + Map config = new HashMap<>(); + + Object returned = ReflectionTestUtils.invokeMethod(service, "buildConfig", config); + + assertSame(config, returned); + Map server = assertInstanceOf(Map.class, config.get("server")); + Map features = assertInstanceOf(Map.class, server.get("features")); + assertEquals(true, features.get("enabled")); + assertEquals(List.of("first", "second"), features.get("labels")); + } + + private static SysParamsDTO parameter(String code, String value, String type) { + SysParamsDTO parameter = new SysParamsDTO(); + parameter.setParamCode(code); + parameter.setParamValue(value); + parameter.setValueType(type); + return parameter; + } + + private static ConfigServiceImpl newService(SysParamsService sysParamsService, RedisUtils redisUtils) { + return new ConfigServiceImpl( + sysParamsService, + mock(DeviceService.class), + mock(ModelConfigService.class), + mock(AgentService.class), + mock(AgentTemplateService.class), + redisUtils, + mock(TimbreService.class), + mock(AgentPluginMappingService.class), + mock(AgentMcpAccessPointService.class), + mock(AgentContextProviderService.class), + mock(VoiceCloneService.class), + mock(AgentVoicePrintDao.class), + mock(CorrectWordFileService.class)); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/correctword/service/impl/CorrectWordFileServiceImplTest.java b/main/manager-api/src/test/java/xiaozhi/modules/correctword/service/impl/CorrectWordFileServiceImplTest.java new file mode 100644 index 000000000..25fbebea7 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/correctword/service/impl/CorrectWordFileServiceImplTest.java @@ -0,0 +1,148 @@ +package xiaozhi.modules.correctword.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import xiaozhi.modules.agent.dao.AgentCorrectWordMappingDao; +import xiaozhi.modules.agent.entity.AgentCorrectWordMappingEntity; +import xiaozhi.modules.correctword.dao.CorrectWordFileDao; +import xiaozhi.modules.correctword.dao.CorrectWordItemDao; +import xiaozhi.modules.correctword.entity.CorrectWordFileEntity; +import xiaozhi.modules.correctword.entity.CorrectWordItemEntity; +import xiaozhi.modules.correctword.vo.CorrectWordFileVO; +import xiaozhi.modules.correctword.vo.CorrectWordSimpleVO; + +class CorrectWordFileServiceImplTest { + + private static final String AGENT_ID = "agent-1"; + private static final String FILE_ID = "file-1"; + + private final CorrectWordFileDao fileDao = mock(CorrectWordFileDao.class); + private final CorrectWordItemDao itemDao = mock(CorrectWordItemDao.class); + private final AgentCorrectWordMappingDao mappingDao = mock(AgentCorrectWordMappingDao.class); + private final CorrectWordFileServiceImpl service = + new CorrectWordFileServiceImpl(fileDao, itemDao, mappingDao); + + @Test + void getAllItemsByAgentId_returns_empty_list_when_no_mappings() { + when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(Collections.emptyList()); + + List result = service.getAllItemsByAgentId(AGENT_ID); + + assertTrue(result.isEmpty()); + verify(itemDao, never()).selectList(org.mockito.ArgumentMatchers.any()); + } + + @Test + void getAllItemsByAgentId_returns_mapped_items_when_mappings_exist() { + AgentCorrectWordMappingEntity mapping = new AgentCorrectWordMappingEntity(); + mapping.setFileId(FILE_ID); + when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(List.of(mapping)); + + CorrectWordItemEntity item = new CorrectWordItemEntity(); + item.setSourceWord("hello"); + item.setTargetWord("hi"); + when(itemDao.selectList(org.mockito.ArgumentMatchers.any())).thenReturn(List.of(item)); + + List result = service.getAllItemsByAgentId(AGENT_ID); + + assertEquals(1, result.size()); + assertEquals("hello", result.get(0).getSourceWord()); + assertEquals("hi", result.get(0).getTargetWord()); + } + + @Test + void getAllItemsByAgentId_returns_empty_list_when_mappings_are_null() { + when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(null); + + List result = service.getAllItemsByAgentId(AGENT_ID); + + assertNotNull(result); + assertTrue(result.isEmpty()); + } + + @Test + void getAgentCorrectWordFileIds_returns_empty_list_when_no_mappings() { + when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(Collections.emptyList()); + + List result = service.getAgentCorrectWordFileIds(AGENT_ID); + + assertTrue(result.isEmpty()); + } + + @Test + void getAgentCorrectWordFileIds_returns_file_ids_when_mappings_exist() { + AgentCorrectWordMappingEntity m1 = new AgentCorrectWordMappingEntity(); + m1.setFileId("f1"); + AgentCorrectWordMappingEntity m2 = new AgentCorrectWordMappingEntity(); + m2.setFileId("f2"); + when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(List.of(m1, m2)); + + List result = service.getAgentCorrectWordFileIds(AGENT_ID); + + assertEquals(List.of("f1", "f2"), result); + } + + @Test + void getFileContent_returns_null_when_entity_not_found() { + when(fileDao.selectById(FILE_ID)).thenReturn(null); + + CorrectWordFileVO result = service.getFileContent(FILE_ID); + + assertNull(result); + } + + @Test + void getFileContent_returns_vo_when_entity_found() { + CorrectWordFileEntity entity = new CorrectWordFileEntity(); + entity.setId(FILE_ID); + entity.setFileName("dict.txt"); + entity.setWordCount(2); + entity.setContent("hello|hi\nbye|goodbye"); + entity.setCreatedAt(new Date()); + when(fileDao.selectById(FILE_ID)).thenReturn(entity); + + CorrectWordFileVO result = service.getFileContent(FILE_ID); + + assertNotNull(result); + assertEquals(FILE_ID, result.getId()); + assertEquals("dict.txt", result.getFileName()); + assertEquals(2, result.getWordCount().intValue()); + assertEquals(2, result.getContent().size()); + assertEquals("hello|hi", result.getContent().get(0)); + } + + @Test + void deleteMappingsByAgentId_delegates_to_dao() { + service.deleteMappingsByAgentId(AGENT_ID); + + verify(mappingDao).deleteByAgentId(AGENT_ID); + } + + @Test + void batchDeleteFiles_skips_null_and_empty_ids() { + List ids = new ArrayList<>(); + ids.add(null); + ids.add(""); + ids.add(" "); + ids.add(FILE_ID); + + service.batchDeleteFiles(ids); + + verify(fileDao).deleteById(FILE_ID); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/device/DeviceTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/DeviceTest.java index 5a874e533..86ff7854f 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/device/DeviceTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/device/DeviceTest.java @@ -1,7 +1,6 @@ package xiaozhi.modules.device; import java.util.HashMap; -import java.util.UUID; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; @@ -33,7 +32,7 @@ public class DeviceTest { private SysUserService sysUserService; @Test - public void testSaveUser() { + public void testRejectWeakPassword() { SysUserDTO userDTO = new SysUserDTO(); userDTO.setUsername("test"); userDTO.setPassword("TestPassword123!"); @@ -76,4 +75,4 @@ public class DeviceTest { log.info("Test completed"); } -} \ No newline at end of file +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/device/controller/DeviceControllerTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/controller/DeviceControllerTest.java new file mode 100644 index 000000000..a3fa0ad4f --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/device/controller/DeviceControllerTest.java @@ -0,0 +1,78 @@ +package xiaozhi.modules.device.controller; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.common.user.UserDetail; +import xiaozhi.common.utils.MessageUtils; +import xiaozhi.common.utils.Result; +import xiaozhi.modules.device.dto.DeviceUpdateDTO; +import xiaozhi.modules.device.entity.DeviceEntity; +import xiaozhi.modules.device.service.DeviceAddressBookService; +import xiaozhi.modules.device.service.DeviceService; +import xiaozhi.modules.security.user.SecurityUser; +import xiaozhi.modules.sys.service.SysParamsService; + +@DisplayName("设备更新接口回归测试") +class DeviceControllerTest { + + private static final String DEVICE_ID = "device-id"; + private static final long USER_ID = 1L; + + @Test + @DisplayName("数据库未更新时不误报自动升级状态修改成功") + void updateFailureIsReturnedToCaller() { + DeviceService deviceService = mock(DeviceService.class); + DeviceEntity entity = ownedDevice(); + when(deviceService.selectById(DEVICE_ID)).thenReturn(entity); + when(deviceService.updateById(entity)).thenReturn(false); + DeviceController controller = controller(deviceService); + + DeviceUpdateDTO update = new DeviceUpdateDTO(); + update.setAutoUpdate(0); + + try (MockedStatic securityUser = mockStatic(SecurityUser.class); + MockedStatic messageUtils = mockStatic(MessageUtils.class)) { + securityUser.when(SecurityUser::getUser).thenReturn(currentUser()); + messageUtils.when(() -> MessageUtils.getMessage(ErrorCode.UPDATE_DATA_FAILED)) + .thenReturn("Failed to update data"); + + Result result = controller.updateDeviceInfo(DEVICE_ID, update); + + assertEquals(ErrorCode.UPDATE_DATA_FAILED, result.getCode()); + assertEquals(0, entity.getAutoUpdate()); + verify(deviceService).updateById(entity); + } + } + + private DeviceController controller(DeviceService deviceService) { + return new DeviceController( + deviceService, + mock(DeviceAddressBookService.class), + mock(RedisUtils.class), + mock(SysParamsService.class)); + } + + private DeviceEntity ownedDevice() { + DeviceEntity entity = new DeviceEntity(); + entity.setId(DEVICE_ID); + entity.setUserId(USER_ID); + entity.setAutoUpdate(1); + return entity; + } + + private UserDetail currentUser() { + UserDetail user = new UserDetail(); + user.setId(USER_ID); + return user; + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImplTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImplTest.java new file mode 100644 index 000000000..69ae3b6da --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImplTest.java @@ -0,0 +1,46 @@ +package xiaozhi.modules.device.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.modules.device.dao.DeviceAddressBookDao; +import xiaozhi.modules.device.entity.DeviceAddressBookEntity; +import xiaozhi.modules.device.service.DeviceService; +import xiaozhi.modules.sys.service.SysParamsService; + +class DeviceAddressBookServiceImplTest { + + @Test + void newEntryUsesTheDedicatedAddressBookInsertMapping() { + DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class); + RedisUtils redisUtils = mock(RedisUtils.class); + DeviceService deviceService = mock(DeviceService.class); + SysParamsService sysParamsService = mock(SysParamsService.class); + DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl( + addressBookDao, redisUtils, deviceService, sysParamsService); + when(addressBookDao.selectOne(any())).thenReturn(null); + when(addressBookDao.selectList(null)).thenReturn(List.of()); + + service.saveOrUpdate("00:11:22:33:44:55", "00:11:22:33:44:66", "living-room", true); + + ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class); + verify(addressBookDao).insertAddressBook(entityCaptor.capture()); + DeviceAddressBookEntity entity = entityCaptor.getValue(); + assertEquals("00:11:22:33:44:55", entity.getMacAddress()); + assertEquals("00:11:22:33:44:66", entity.getTargetMac()); + assertEquals("living-room", entity.getAlias()); + assertTrue(entity.getHasPermission()); + verify(addressBookDao, never()).insert(any(DeviceAddressBookEntity.class)); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAutoUpdateTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAutoUpdateTest.java new file mode 100644 index 000000000..67a29a6ce --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAutoUpdateTest.java @@ -0,0 +1,104 @@ +package xiaozhi.modules.device.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.aop.framework.ProxyFactory; + +import xiaozhi.common.constant.Constant; +import xiaozhi.modules.device.dto.DeviceReportReqDTO; +import xiaozhi.modules.device.dto.DeviceReportRespDTO; +import xiaozhi.modules.device.entity.DeviceEntity; +import xiaozhi.modules.device.service.OtaService; +import xiaozhi.modules.sys.service.SysParamsService; + +@DisplayName("设备自动升级回归测试") +class DeviceAutoUpdateTest { + + private static final String MAC_ADDRESS = "00:11:22:33:44:55"; + private static final String BOARD_TYPE = "test-board"; + private static final String CURRENT_VERSION = "1.0.0"; + + @Test + @DisplayName("#3299 自动升级关闭时 OTA 响应不包含固件") + void disabledAutoUpdateOmitsFirmware() { + OtaService otaService = mock(OtaService.class); + DeviceServiceImpl service = proxiedService(deviceWithAutoUpdate(0), otaService); + + DeviceReportRespDTO response = service.checkDeviceActive( + MAC_ADDRESS, MAC_ADDRESS, deviceReport()); + + assertNull(response.getFirmware()); + verifyNoInteractions(otaService); + } + + @Test + @DisplayName("自动升级开启时继续执行固件查询") + void enabledAutoUpdateChecksFirmware() { + OtaService otaService = mock(OtaService.class); + when(otaService.getLatestOta(BOARD_TYPE)).thenReturn(null); + DeviceServiceImpl service = proxiedService(deviceWithAutoUpdate(1), otaService); + + DeviceReportRespDTO response = service.checkDeviceActive( + MAC_ADDRESS, MAC_ADDRESS, deviceReport()); + + assertNotNull(response.getFirmware()); + assertEquals(CURRENT_VERSION, response.getFirmware().getVersion()); + assertEquals(Constant.INVALID_FIRMWARE_URL, response.getFirmware().getUrl()); + verify(otaService).getLatestOta(BOARD_TYPE); + } + + private DeviceServiceImpl proxiedService(DeviceEntity device, OtaService otaService) { + SysParamsService sysParamsService = mock(SysParamsService.class); + when(sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true)) + .thenReturn("ws://127.0.0.1:8000/xiaozhi/v1/"); + when(sysParamsService.getValue(Constant.SERVER_AUTH_ENABLED, true)).thenReturn("false"); + when(sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, true)).thenReturn(null); + + DeviceServiceImpl target = new DeviceServiceImpl( + null, null, sysParamsService, null, otaService, null) { + @Override + public DeviceEntity getDeviceByMacAddress(String macAddress) { + return device; + } + + @Override + public void updateDeviceConnectionInfo(String agentId, String deviceId, String appVersion) { + // No-op: connection timestamps are outside this OTA decision test. + } + }; + + ProxyFactory proxyFactory = new ProxyFactory(target); + proxyFactory.setProxyTargetClass(true); + proxyFactory.setExposeProxy(true); + return (DeviceServiceImpl) proxyFactory.getProxy(); + } + + private DeviceEntity deviceWithAutoUpdate(int autoUpdate) { + DeviceEntity device = new DeviceEntity(); + device.setId(MAC_ADDRESS); + device.setMacAddress(MAC_ADDRESS); + device.setBoard(BOARD_TYPE); + device.setAutoUpdate(autoUpdate); + return device; + } + + private DeviceReportReqDTO deviceReport() { + DeviceReportReqDTO.Application application = new DeviceReportReqDTO.Application(); + application.setVersion(CURRENT_VERSION); + DeviceReportReqDTO.BoardInfo board = new DeviceReportReqDTO.BoardInfo(); + board.setType(BOARD_TYPE); + + DeviceReportReqDTO report = new DeviceReportReqDTO(); + report.setApplication(application); + report.setBoard(board); + return report; + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceTimeSerializationTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceTimeSerializationTest.java new file mode 100644 index 000000000..bf2e14835 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceTimeSerializationTest.java @@ -0,0 +1,106 @@ +package xiaozhi.modules.device.service.impl; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Instant; +import java.time.ZoneId; +import java.util.Date; +import java.util.List; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import xiaozhi.modules.device.entity.DeviceEntity; +import xiaozhi.modules.device.vo.UserShowDeviceListVO; +import xiaozhi.modules.security.config.WebMvcConfig; + +@DisplayName("设备时间序列化回归测试") +class DeviceTimeSerializationTest { + + @ParameterizedTest(name = "浏览器时区 {0}") + @ValueSource(strings = { "Asia/Shanghai", "America/Sao_Paulo" }) + @DisplayName("#3280 绑定时间和最后连接时间在任意浏览器时区都表示同一时刻") + void serializedDeviceTimesDescribeTheSameInstantAcrossBrowserTimeZones(String browserTimeZone) { + Instant connectedAt = Instant.parse("2026-07-10T13:21:42Z"); + DeviceEntity entity = new DeviceEntity(); + entity.setCreateDate(Date.from(connectedAt)); + entity.setLastConnectedAt(Date.from(connectedAt)); + + DeviceServiceImpl deviceService = serviceReturning(entity); + UserShowDeviceListVO device = deviceService.getUserDeviceList(1L, "agent-id").getFirst(); + + ObjectMapper objectMapper = new WebMvcConfig().jackson2HttpMessageConverter().getObjectMapper(); + JsonNode payload = objectMapper.valueToTree(device); + Instant createDate = Instant.ofEpochMilli( + Long.parseLong(payload.path("createDateTimestamp").asText())); + Instant lastConnectedAt = Instant.ofEpochMilli( + Long.parseLong(payload.path("lastConnectedAtTimestamp").asText())); + ZoneId browserZone = ZoneId.of(browserTimeZone); + + assertAll( + () -> assertTrue(payload.path("createDateTimestamp").isTextual(), + "Long 时间戳必须遵循现有 JSON 契约序列化为字符串"), + () -> assertTrue(payload.path("lastConnectedAtTimestamp").isTextual(), + "Long 时间戳必须遵循现有 JSON 契约序列化为字符串"), + () -> assertEquals(connectedAt, createDate, + "createDateTimestamp 必须保留源时间点"), + () -> assertEquals(connectedAt, lastConnectedAt, + "lastConnectedAtTimestamp 必须保留源时间点"), + () -> assertEquals(lastConnectedAt.atZone(browserZone).toLocalDateTime(), + createDate.atZone(browserZone).toLocalDateTime(), + "绑定时间和最后连接时间在同一浏览器中必须显示为相同的本地时间"), + () -> assertTrue(payload.path("createDate").isTextual(), + "兼容字段 createDate 必须继续保留")); + } + + @Test + @DisplayName("时间为空时新旧字段均保持 null") + void nullDeviceTimesRemainNull() { + DeviceEntity entity = new DeviceEntity(); + DeviceServiceImpl deviceService = serviceReturning(entity); + + UserShowDeviceListVO device = deviceService.getUserDeviceList(1L, "agent-id").getFirst(); + ObjectMapper objectMapper = new WebMvcConfig().jackson2HttpMessageConverter().getObjectMapper(); + JsonNode payload = objectMapper.valueToTree(device); + + assertAll( + () -> assertTrue(payload.path("createDateTimestamp").isNull()), + () -> assertTrue(payload.path("lastConnectedAtTimestamp").isNull()), + () -> assertTrue(payload.path("createDate").isNull())); + } + + @ParameterizedTest(name = "自动升级状态 {0}") + @ValueSource(ints = { 0, 1 }) + @DisplayName("#3299 设备列表按 autoUpdate 契约返回真实开关状态") + void serializedDeviceContainsAutoUpdateState(int autoUpdate) { + DeviceEntity entity = new DeviceEntity(); + entity.setAutoUpdate(autoUpdate); + DeviceServiceImpl deviceService = serviceReturning(entity); + + UserShowDeviceListVO device = deviceService.getUserDeviceList(1L, "agent-id").getFirst(); + ObjectMapper objectMapper = new WebMvcConfig().jackson2HttpMessageConverter().getObjectMapper(); + JsonNode payload = objectMapper.valueToTree(device); + + assertAll( + () -> assertEquals(autoUpdate, device.getAutoUpdate()), + () -> assertEquals(autoUpdate, payload.path("autoUpdate").asInt()), + () -> assertTrue(payload.path("otaUpgrade").isMissingNode(), + "设备列表不应继续暴露未映射的旧字段 otaUpgrade")); + } + + private DeviceServiceImpl serviceReturning(DeviceEntity entity) { + return new DeviceServiceImpl(null, null, null, null, null, null) { + @Override + public List getUserDevices(Long userId, String agentId) { + return List.of(entity); + } + }; + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/MqttGatewayAuthorizationTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/MqttGatewayAuthorizationTest.java new file mode 100644 index 000000000..c3644b5f7 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/MqttGatewayAuthorizationTest.java @@ -0,0 +1,180 @@ +package xiaozhi.modules.device.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; + +import cn.hutool.crypto.digest.DigestUtil; + +@DisplayName("MQTT Gateway 日期鉴权回归测试") +class MqttGatewayAuthorizationTest { + + private static final String SIGNATURE_KEY = "test-signature-key"; + private static final Instant FIXED_INSTANT = Instant.parse("2026-07-14T00:30:00Z"); + + private HttpServer server; + + @AfterEach + void stopServer() { + if (server != null) { + server.stop(0); + } + } + + @Test + @DisplayName("以 UTC 日期生成当天、前一天和后一天三个候选 token") + void generatesUtcDateCandidates() { + List tokens = MqttGatewayAuthorization.generateDailyTokens(SIGNATURE_KEY, FIXED_INSTANT); + + assertEquals(List.of( + tokenFor("2026-07-14"), + tokenFor("2026-07-13"), + tokenFor("2026-07-15")), tokens); + } + + @ParameterizedTest(name = "Gateway 时区 {0}") + @MethodSource("gatewayTimeZones") + @DisplayName("候选 token 覆盖上海和圣保罗 Gateway 的本地日期") + void coversGatewayLocalDate(String gatewayTimeZone, Instant now, int expectedTokenIndex) { + String gatewayDate = now.atZone(ZoneId.of(gatewayTimeZone)).toLocalDate().toString(); + List tokens = MqttGatewayAuthorization.generateDailyTokens(SIGNATURE_KEY, now); + + assertEquals(tokenFor(gatewayDate), tokens.get(expectedTokenIndex)); + } + + @Test + @DisplayName("仅在 401 时按日期候选重试并保留请求体") + void retriesOnlyAuthenticationFailures() throws IOException { + AtomicInteger requestCount = new AtomicInteger(); + List authorizationHeaders = new ArrayList<>(); + List requestBodies = new ArrayList<>(); + List expectedTokens = MqttGatewayAuthorization.generateDailyTokens(SIGNATURE_KEY, FIXED_INSTANT); + startServer(exchange -> { + int attempt = requestCount.getAndIncrement(); + authorizationHeaders.add(exchange.getRequestHeaders().getFirst("Authorization")); + requestBodies.add(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8)); + if (attempt == 0) { + respond(exchange, 401, "{\"error\":\"unauthorized\"}"); + } else if (attempt == 1) { + respond(exchange, 401, "{\"error\":\"unauthorized\"}"); + } else { + respond(exchange, 200, "{\"online\":true}"); + } + }); + + String requestBody = "{\"clientIds\":[\"device-id\"]}"; + String response = MqttGatewayAuthorization.postJson( + serverUrl(), requestBody, SIGNATURE_KEY, FIXED_INSTANT); + + assertEquals("{\"online\":true}", response); + assertEquals(3, requestCount.get()); + assertEquals(expectedTokens.stream().map(token -> "Bearer " + token).toList(), authorizationHeaders); + assertEquals(List.of(requestBody, requestBody, requestBody), requestBodies); + } + + @ParameterizedTest(name = "HTTP {0}") + @ValueSource(ints = { 403, 500 }) + @DisplayName("非 401 错误不重试且向上抛出") + void doesNotRetryNonAuthenticationFailure(int statusCode) throws IOException { + AtomicInteger requestCount = new AtomicInteger(); + startServer(exchange -> { + requestCount.incrementAndGet(); + exchange.getRequestBody().readAllBytes(); + respond(exchange, statusCode, "{\"error\":\"request rejected\"}"); + }); + + MqttGatewayAuthorization.GatewayRequestException exception = assertThrows( + MqttGatewayAuthorization.GatewayRequestException.class, + () -> MqttGatewayAuthorization.postJson( + serverUrl(), "{}", SIGNATURE_KEY, FIXED_INSTANT)); + + assertEquals(statusCode, exception.statusCode()); + assertEquals(1, requestCount.get()); + } + + @Test + @DisplayName("所有日期候选被拒绝时不把错误响应当作设备离线数据") + void propagatesAuthenticationFailureAfterAllCandidatesAreRejected() throws IOException { + AtomicInteger requestCount = new AtomicInteger(); + startServer(exchange -> { + requestCount.incrementAndGet(); + exchange.getRequestBody().readAllBytes(); + respond(exchange, 401, "{\"error\":\"unauthorized\"}"); + }); + + MqttGatewayAuthorization.GatewayRequestException exception = assertThrows( + MqttGatewayAuthorization.GatewayRequestException.class, + () -> MqttGatewayAuthorization.postJson( + serverUrl(), "{}", SIGNATURE_KEY, FIXED_INSTANT)); + + assertEquals(401, exception.statusCode()); + assertEquals(3, requestCount.get()); + } + + @ParameterizedTest(name = "密钥值 [{0}]") + @NullAndEmptySource + @ValueSource(strings = { " ", "null", " NULL " }) + @DisplayName("缺少或占位签名密钥时在发起 HTTP 请求前失败") + void rejectsMissingSignatureKeyBeforeSendingRequest(String signatureKey) { + MqttGatewayAuthorization.GatewayRequestException exception = assertThrows( + MqttGatewayAuthorization.GatewayRequestException.class, + () -> MqttGatewayAuthorization.postJson( + "http://127.0.0.1:1", "{}", signatureKey, FIXED_INSTANT)); + + assertNull(exception.statusCode()); + } + + private static Stream gatewayTimeZones() { + return Stream.of( + Arguments.of("Asia/Shanghai", Instant.parse("2026-07-13T17:30:00Z"), 2), + Arguments.of("America/Sao_Paulo", Instant.parse("2026-07-14T00:30:00Z"), 1)); + } + + private void startServer(HttpHandler handler) throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/mqtt", handler); + server.start(); + } + + private String serverUrl() { + assertTrue(server != null, "test server must be started"); + return "http://127.0.0.1:" + server.getAddress().getPort() + "/mqtt"; + } + + private static void respond(HttpExchange exchange, int statusCode, String body) throws IOException { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(statusCode, bytes.length); + try (var output = exchange.getResponseBody()) { + output.write(bytes); + } + } + + private static String tokenFor(String date) { + return DigestUtil.sha256Hex(date + SIGNATURE_KEY); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/knowledge/rag/KnowledgeBaseAdapterFactoryTest.java b/main/manager-api/src/test/java/xiaozhi/modules/knowledge/rag/KnowledgeBaseAdapterFactoryTest.java new file mode 100644 index 000000000..4734c61c9 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/knowledge/rag/KnowledgeBaseAdapterFactoryTest.java @@ -0,0 +1,233 @@ +package xiaozhi.modules.knowledge.rag; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mockStatic; + +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.page.PageData; +import xiaozhi.common.utils.MessageUtils; +import xiaozhi.modules.knowledge.dto.KnowledgeFilesDTO; +import xiaozhi.modules.knowledge.dto.dataset.DatasetDTO; +import xiaozhi.modules.knowledge.dto.document.ChunkDTO; +import xiaozhi.modules.knowledge.dto.document.DocumentDTO; +import xiaozhi.modules.knowledge.dto.document.RetrievalDTO; + +class KnowledgeBaseAdapterFactoryTest { + + private static final String REGISTERED_TYPE = "kb-test-registered"; + private static final String UNKNOWN_TYPE = "kb-test-unknown"; + + @BeforeEach + void resetCache() { + KnowledgeBaseAdapterFactory.clearCache(); + } + + @AfterEach + void cleanupCache() { + KnowledgeBaseAdapterFactory.clearCache(); + KnowledgeBaseAdapterFactory.removeCacheByType(REGISTERED_TYPE); + } + + @Test + void getAdapter_returns_non_null_instance_for_registered_type() { + KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class); + + KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(REGISTERED_TYPE); + + assertNotNull(adapter); + assertEquals(REGISTERED_TYPE, adapter.getAdapterType()); + } + + @Test + void getAdapter_returns_cached_instance_for_repeated_calls() { + KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class); + + KnowledgeBaseAdapter first = KnowledgeBaseAdapterFactory.getAdapter(REGISTERED_TYPE); + KnowledgeBaseAdapter second = KnowledgeBaseAdapterFactory.getAdapter(REGISTERED_TYPE); + + assertSame(first, second); + } + + @Test + void getAdapter_throws_RenException_for_unknown_type() { + try (MockedStatic messageUtils = mockStatic(MessageUtils.class)) { + messageUtils.when(() -> MessageUtils.getMessage(anyInt())).thenReturn("mocked message"); + messageUtils.when(() -> MessageUtils.getMessage(anyInt(), any(String[].class))) + .thenReturn("mocked message"); + + RenException ex = assertThrows(RenException.class, + () -> KnowledgeBaseAdapterFactory.getAdapter(UNKNOWN_TYPE)); + + assertEquals(ErrorCode.RAG_ADAPTER_TYPE_NOT_SUPPORTED, ex.getCode()); + } + } + + @Test + void isAdapterTypeRegistered_returns_true_for_registered_types() { + KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class); + + assertTrue(KnowledgeBaseAdapterFactory.isAdapterTypeRegistered(REGISTERED_TYPE)); + assertTrue(KnowledgeBaseAdapterFactory.isAdapterTypeRegistered("ragflow")); + assertFalse(KnowledgeBaseAdapterFactory.isAdapterTypeRegistered(UNKNOWN_TYPE)); + } + + @Test + void getRegisteredAdapterTypes_contains_all_registered_types() { + KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class); + + Set types = KnowledgeBaseAdapterFactory.getRegisteredAdapterTypes(); + + assertTrue(types.contains(REGISTERED_TYPE)); + assertTrue(types.contains("ragflow")); + } + + @Test + void clearCache_empties_cached_instance_count() { + KnowledgeBaseAdapterFactory.registerAdapter(REGISTERED_TYPE, StubAdapter.class); + KnowledgeBaseAdapterFactory.getAdapter(REGISTERED_TYPE); + + KnowledgeBaseAdapterFactory.clearCache(); + Map status = KnowledgeBaseAdapterFactory.getFactoryStatus(); + + assertEquals(0, status.get("cachedAdapterCount")); + } + + /** + * Test stub adapter that satisfies the abstract API surface so the factory's + * reflection-based instantiation works in the unit test. + */ + public static class StubAdapter extends KnowledgeBaseAdapter { + @Override + public String getAdapterType() { + return REGISTERED_TYPE; + } + + @Override + public void initialize(Map config) { + } + + @Override + public boolean validateConfig(Map config) { + return true; + } + + @Override + public PageData getDocumentList(String datasetId, + DocumentDTO.ListReq req) { + return new PageData<>(java.util.Collections.emptyList(), 0); + } + + @Override + public DocumentDTO.InfoVO getDocumentById(String datasetId, String documentId) { + return null; + } + + @Override + public KnowledgeFilesDTO uploadDocument(DocumentDTO.UploadReq req) { + return null; + } + + @Override + public PageData getDocumentListByStatus(String datasetId, + Integer status, Integer page, Integer limit) { + return new PageData<>(java.util.Collections.emptyList(), 0); + } + + @Override + public void deleteDocument(String datasetId, DocumentDTO.BatchIdReq req) { + } + + @Override + public boolean parseDocuments(String datasetId, java.util.List documentIds) { + return true; + } + + @Override + public ChunkDTO.ListVO listChunks(String datasetId, String documentId, + ChunkDTO.ListReq req) { + return null; + } + + @Override + public RetrievalDTO.ResultVO retrievalTest(RetrievalDTO.TestReq req) { + return null; + } + + @Override + public boolean testConnection() { + return true; + } + + @Override + public Map getStatus() { + return java.util.Collections.emptyMap(); + } + + @Override + public Map getSupportedConfig() { + return java.util.Collections.emptyMap(); + } + + @Override + public Map getDefaultConfig() { + return java.util.Collections.emptyMap(); + } + + @Override + public DatasetDTO.InfoVO createDataset(DatasetDTO.CreateReq req) { + return null; + } + + @Override + public DatasetDTO.InfoVO updateDataset(String datasetId, DatasetDTO.UpdateReq req) { + return null; + } + + @Override + public DatasetDTO.BatchOperationVO deleteDataset(DatasetDTO.BatchIdReq req) { + return null; + } + + @Override + public Integer getDocumentCount(String datasetId) { + return 0; + } + + @Override + public DatasetDTO.InfoVO getDatasetInfo(String datasetId) { + return null; + } + + @Override + public void postStream(String endpoint, Object body, Consumer onData) { + } + + @Override + public Object postSearchBotAsk(Map config, Object body, + Consumer onData) { + return null; + } + + @Override + public void postAgentBotCompletion(Map config, String agentId, + Object body, Consumer onData) { + } + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/security/config/ShiroConfigTest.java b/main/manager-api/src/test/java/xiaozhi/modules/security/config/ShiroConfigTest.java new file mode 100644 index 000000000..9b10be110 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/security/config/ShiroConfigTest.java @@ -0,0 +1,60 @@ +package xiaozhi.modules.security.config; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import org.apache.shiro.session.mgt.SessionManager; +import org.apache.shiro.spring.web.ShiroFilterFactoryBean; +import org.apache.shiro.web.mgt.WebSecurityManager; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.annotation.Lazy; +import org.springframework.context.annotation.Role; + +import xiaozhi.modules.security.oauth2.Oauth2Realm; +import xiaozhi.modules.sys.service.SysParamsService; + +class ShiroConfigTest { + + @Test + void beanPostProcessorFactoriesDoNotInstantiateShiroConfigOrBusinessDependenciesEarly() throws Exception { + Method lifecycleFactory = ShiroConfig.class.getDeclaredMethod("lifecycleBeanPostProcessor"); + Method filterFactory = ShiroConfig.class.getDeclaredMethod( + "shirFilter", WebSecurityManager.class, SysParamsService.class); + + assertTrue(Modifier.isStatic(lifecycleFactory.getModifiers())); + assertTrue(BeanPostProcessor.class.isAssignableFrom(ShiroFilterFactoryBean.class)); + assertTrue(Modifier.isStatic(filterFactory.getModifiers())); + Lazy securityManagerLazy = filterFactory.getParameters()[0].getAnnotation(Lazy.class); + Lazy sysParamsServiceLazy = filterFactory.getParameters()[1].getAnnotation(Lazy.class); + assertNotNull(securityManagerLazy); + assertNotNull(sysParamsServiceLazy); + assertTrue(securityManagerLazy.value()); + assertTrue(sysParamsServiceLazy.value()); + } + + @Test + void authorizationAdvisorIsInfrastructureAndDefersItsSecurityManager() throws Exception { + Method advisorFactory = ShiroConfig.class.getDeclaredMethod( + "authorizationAttributeSourceAdvisor", WebSecurityManager.class); + + assertTrue(Modifier.isStatic(advisorFactory.getModifiers())); + Lazy securityManagerLazy = advisorFactory.getParameters()[0].getAnnotation(Lazy.class); + assertNotNull(securityManagerLazy); + assertTrue(securityManagerLazy.value()); + assertEquals(BeanDefinition.ROLE_INFRASTRUCTURE, advisorFactory.getAnnotation(Role.class).value()); + } + + @Test + void securityManagerRetainsTheWebSecurityContractRequiredByShiroFilter() throws Exception { + Method securityManagerFactory = ShiroConfig.class.getDeclaredMethod( + "securityManager", Oauth2Realm.class, SessionManager.class); + + assertEquals(WebSecurityManager.class, securityManagerFactory.getReturnType()); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/sys/loginControllerTest.java b/main/manager-api/src/test/java/xiaozhi/modules/sys/loginControllerTest.java index 1f848eb4f..797ed6712 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/sys/loginControllerTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/sys/loginControllerTest.java @@ -1,5 +1,9 @@ package xiaozhi.modules.sys; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Assertions; import org.springframework.beans.factory.annotation.Autowired; @@ -13,6 +17,7 @@ import xiaozhi.modules.security.controller.LoginController; import xiaozhi.modules.security.dto.LoginDTO; import xiaozhi.modules.security.dto.SmsVerificationDTO; import xiaozhi.modules.sys.dto.RetrievePasswordDTO; +import xiaozhi.modules.sys.service.SysUserService; @Slf4j @SpringBootTest @@ -23,8 +28,13 @@ class loginControllerTest { @Autowired LoginController loginController; + @MockitoBean + SysUserService sysUserService; + @Test public void testRegister() { + when(sysUserService.getAllowUserRegister()).thenReturn(false); + LoginDTO loginDTO = new LoginDTO(); loginDTO.setUsername("test-user"); loginDTO.setPassword("test-password"); diff --git a/main/manager-api/src/test/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImplTest.java b/main/manager-api/src/test/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImplTest.java new file mode 100644 index 000000000..13839690d --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImplTest.java @@ -0,0 +1,35 @@ +package xiaozhi.modules.sys.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import xiaozhi.common.redis.RedisKeys; +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.modules.sys.dao.SysUserDao; +import xiaozhi.modules.sys.vo.SysDictDataItem; + +class SysDictDataServiceImplTest { + + @Test + void cachedDictionaryItemsAreCheckedAndReturnedAsDtos() { + RedisUtils redisUtils = mock(RedisUtils.class); + SysDictDataItem item = new SysDictDataItem(); + item.setName("enabled"); + item.setKey("1"); + List cached = new ArrayList<>(List.of(item)); + when(redisUtils.get(RedisKeys.getDictDataByTypeKey("status"))).thenReturn(cached); + SysDictDataServiceImpl service = new SysDictDataServiceImpl(mock(SysUserDao.class), redisUtils); + + List result = service.getDictDataByType("status"); + + assertNotSame(cached, result); + assertEquals(List.of(item), result); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImplTest.java b/main/manager-api/src/test/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImplTest.java new file mode 100644 index 000000000..cf12ee01e --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImplTest.java @@ -0,0 +1,36 @@ +package xiaozhi.modules.sys.service.impl; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import xiaozhi.common.constant.Constant; +import xiaozhi.modules.agent.service.AgentPluginMappingService; +import xiaozhi.modules.sys.dao.SysParamsDao; +import xiaozhi.modules.sys.redis.SysParamsRedis; + +class SysParamsServiceImplTest { + + @Test + void disablingAddressBookStillDeletesItsSystemPlugin() { + SysParamsRedis sysParamsRedis = mock(SysParamsRedis.class); + AgentPluginMappingService pluginMappingService = mock(AgentPluginMappingService.class); + SysParamsDao sysParamsDao = mock(SysParamsDao.class); + SysParamsServiceImpl service = new SysParamsServiceImpl(sysParamsRedis, pluginMappingService); + ReflectionTestUtils.setField(service, "baseDao", sysParamsDao); + + String currentConfig = "{\"features\":{\"addressBook\":{\"enabled\":true}}}"; + String newConfig = "{\"features\":{\"addressBook\":{\"enabled\":false}}}"; + when(sysParamsDao.getValueByCode(Constant.SYSTEM_WEB_MENU)).thenReturn(currentConfig); + when(sysParamsDao.updateValueByCode(Constant.SYSTEM_WEB_MENU, newConfig)).thenReturn(1); + + service.updateSystemWebMenu(newConfig); + + verify(pluginMappingService).deleteByPluginId("SYSTEM_PLUGIN_CALL_DEVICE"); + verify(sysParamsDao).updateValueByCode(Constant.SYSTEM_WEB_MENU, newConfig); + verify(sysParamsRedis).set(Constant.SYSTEM_WEB_MENU, newConfig); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImplTest.java b/main/manager-api/src/test/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImplTest.java new file mode 100644 index 000000000..985bc8866 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImplTest.java @@ -0,0 +1,131 @@ +package xiaozhi.modules.timbre.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.modules.timbre.dao.TimbreDao; +import xiaozhi.modules.timbre.dto.TimbreDataDTO; +import xiaozhi.modules.timbre.entity.TimbreEntity; +import xiaozhi.modules.timbre.vo.TimbreDetailsVO; +import xiaozhi.modules.voiceclone.dao.VoiceCloneDao; +import xiaozhi.modules.voiceclone.entity.VoiceCloneEntity; + +class TimbreServiceImplTest { + + @Test + void defaultLanguageUsesFirstValidRegularTimbreLanguageWithoutCloneQuery() { + TimbreDao timbreDao = mock(TimbreDao.class); + VoiceCloneDao voiceCloneDao = mock(VoiceCloneDao.class); + TimbreServiceImpl service = new TimbreServiceImpl(timbreDao, voiceCloneDao, mock(RedisUtils.class)); + TimbreEntity timbre = new TimbreEntity(); + timbre.setLanguages(",, ; 普通话;粤语"); + when(timbreDao.selectById("voice-id")).thenReturn(timbre); + + assertEquals("普通话", service.getDefaultLanguageById("voice-id")); + + verify(voiceCloneDao, never()).selectById("voice-id"); + } + + @Test + void defaultLanguageFallsBackToCloneTimbre() { + TimbreDao timbreDao = mock(TimbreDao.class); + VoiceCloneDao voiceCloneDao = mock(VoiceCloneDao.class); + TimbreServiceImpl service = new TimbreServiceImpl(timbreDao, voiceCloneDao, mock(RedisUtils.class)); + VoiceCloneEntity voiceClone = new VoiceCloneEntity(); + voiceClone.setLanguages("、, English,中文"); + when(voiceCloneDao.selectById("clone-id")).thenReturn(voiceClone); + + assertEquals("English", service.getDefaultLanguageById("clone-id")); + } + + @Test + void delimiterOnlyLanguageConfigurationReturnsNull() { + TimbreDao timbreDao = mock(TimbreDao.class); + VoiceCloneDao voiceCloneDao = mock(VoiceCloneDao.class); + TimbreServiceImpl service = new TimbreServiceImpl(timbreDao, voiceCloneDao, mock(RedisUtils.class)); + TimbreEntity timbre = new TimbreEntity(); + timbre.setLanguages(",,、;;;,,"); + when(timbreDao.selectById("voice-id")).thenReturn(timbre); + + assertNull(service.getDefaultLanguageById("voice-id")); + } + + @Test + void updateLeavesSortOutOfTheUpdateWhenRequestOmitsIt() { + TimbreDao timbreDao = mock(TimbreDao.class); + RedisUtils redisUtils = mock(RedisUtils.class); + TimbreServiceImpl service = new TimbreServiceImpl(timbreDao, mock(VoiceCloneDao.class), redisUtils); + ReflectionTestUtils.setField(service, "baseDao", timbreDao); + + TimbreDataDTO dto = validTimbreData(); + service.update("voice-id", dto); + + verify(timbreDao, never()).selectById("voice-id"); + verify(timbreDao).updateById(argThat((TimbreEntity entity) -> + "voice-id".equals(entity.getId()) && entity.getSort() == null)); + verify(redisUtils).delete("timbre:details:voice-id"); + } + + @Test + void updateUsesExplicitSortWithoutLoadingExistingTimbre() { + TimbreDao timbreDao = mock(TimbreDao.class); + TimbreServiceImpl service = new TimbreServiceImpl( + timbreDao, mock(VoiceCloneDao.class), mock(RedisUtils.class)); + ReflectionTestUtils.setField(service, "baseDao", timbreDao); + TimbreDataDTO dto = validTimbreData(); + dto.setSort(0L); + + service.update("voice-id", dto); + + verify(timbreDao, never()).selectById("voice-id"); + verify(timbreDao).updateById(argThat((TimbreEntity entity) -> entity.getSort() == 0L)); + } + + @Test + void saveDefaultsOmittedSortToZero() { + TimbreDao timbreDao = mock(TimbreDao.class); + TimbreServiceImpl service = new TimbreServiceImpl( + timbreDao, mock(VoiceCloneDao.class), mock(RedisUtils.class)); + ReflectionTestUtils.setField(service, "baseDao", timbreDao); + + service.save(validTimbreData()); + + verify(timbreDao).insert(argThat((TimbreEntity entity) -> + "测试音色".equals(entity.getName()) && entity.getSort() == 0L)); + } + + @Test + void getSupportsLegacyRowsWithNullSort() { + TimbreDao timbreDao = mock(TimbreDao.class); + RedisUtils redisUtils = mock(RedisUtils.class); + TimbreServiceImpl service = new TimbreServiceImpl( + timbreDao, mock(VoiceCloneDao.class), redisUtils); + ReflectionTestUtils.setField(service, "baseDao", timbreDao); + TimbreEntity entity = new TimbreEntity(); + entity.setId("voice-id"); + entity.setSort(null); + when(timbreDao.selectById("voice-id")).thenReturn(entity); + + TimbreDetailsVO details = service.get("voice-id"); + + assertNull(details.getSort()); + } + + private TimbreDataDTO validTimbreData() { + TimbreDataDTO dto = new TimbreDataDTO(); + dto.setLanguages("中文"); + dto.setName("测试音色"); + dto.setTtsModelId("TTS_Test"); + dto.setTtsVoice("test-voice"); + return dto; + } +} diff --git a/main/manager-api/src/test/resources/application.yml b/main/manager-api/src/test/resources/application.yml index 099e81941..c33ed1279 100644 --- a/main/manager-api/src/test/resources/application.yml +++ b/main/manager-api/src/test/resources/application.yml @@ -1,4 +1,7 @@ spring: + messages: + encoding: UTF-8 + basename: i18n/messages data: redis: host: localhost @@ -19,4 +22,4 @@ renren: logging: level: xiaozhi.modules.device: DEBUG - org.springframework.data.redis: DEBUG \ No newline at end of file + org.springframework.data.redis: DEBUG diff --git a/main/manager-mobile/package.json b/main/manager-mobile/package.json index 19adec812..0de35e0d3 100644 --- a/main/manager-mobile/package.json +++ b/main/manager-mobile/package.json @@ -69,6 +69,7 @@ "build:quickapp-webview-huawei": "uni build -p quickapp-webview-huawei", "build:quickapp-webview-union": "uni build -p quickapp-webview-union", "type-check": "vue-tsc --noEmit", + "test:snapshot": "node --test src/pages/agent/components/agentSnapshotUtils.test.mjs src/pages/agent/components/agentSnapshotContracts.test.mjs src/pages/agent/components/voicePreviewUtils.test.mjs src/pages/device/deviceTimeUtils.test.mjs", "openapi-ts-request": "openapi-ts", "prepare": "git init && husky", "lint": "eslint", diff --git a/main/manager-mobile/src/api/agent/agent.ts b/main/manager-mobile/src/api/agent/agent.ts index 32b72ad7c..bfaca352a 100644 --- a/main/manager-mobile/src/api/agent/agent.ts +++ b/main/manager-mobile/src/api/agent/agent.ts @@ -2,8 +2,13 @@ import type { Agent, AgentCreateData, AgentDetail, + AgentSnapshot, + AgentSnapshotPageParams, + CorrectWordFile, ModelOption, + PageData, RoleTemplate, + TtsVoice, } from './types' import { http } from '@/http/request/alova' @@ -85,7 +90,7 @@ export function deleteAgent(id: string) { // 获取TTS音色列表 export function getTTSVoices(ttsModelId: string, voiceName: string = '') { - return http.Get<{ id: string, name: string }[]>(`/models/${ttsModelId}/voices`, { + return http.Get(`/models/${ttsModelId}/voices`, { params: { voiceName, }, @@ -100,7 +105,7 @@ export function getTTSVoices(ttsModelId: string, voiceName: string = '') { } // 更新智能体 -export function updateAgent(id: string, data: Partial) { +export function updateAgent(id: string, data: Partial & { tagNames?: string[] }) { return http.Put(`/agent/${id}`, data, { meta: { ignoreAuth: false, @@ -210,7 +215,80 @@ export function updateAgentTags(agentId: string, data) { // 获取所有语言 export function getAllLanguage(modelId: string) { - return http.Get<{ id: string, name: string, languages: string }[]>(`/models/${modelId}/voices`, { + return http.Get(`/models/${modelId}/voices`, { + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +/** + * 获取克隆音色的临时播放ID + * @param cloneId 克隆音色记录ID + */ +export function getVoiceCloneAudioId(cloneId: string) { + return http.Post(`/voiceClone/audio/${cloneId}`, {}, { + meta: { + ignoreAuth: false, + toast: false, + }, + }) +} + +// 获取智能体历史版本列表 +export function getAgentSnapshots(agentId: string, params: AgentSnapshotPageParams) { + return http.Get>(`/agent/${agentId}/snapshots`, { + params, + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 获取智能体历史版本详情 +export function getAgentSnapshot(agentId: string, snapshotId: string) { + return http.Get(`/agent/${agentId}/snapshots/${snapshotId}`, { + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 恢复智能体历史版本 +export function restoreAgentSnapshot(agentId: string, snapshotId: string, currentStateToken: string) { + return http.Post(`/agent/${agentId}/snapshots/${snapshotId}/restore`, { currentStateToken }, { + meta: { + ignoreAuth: false, + toast: false, + }, + }) +} + +// 删除智能体历史版本 +export function deleteAgentSnapshot(agentId: string, snapshotId: string) { + return http.Delete(`/agent/${agentId}/snapshots/${snapshotId}`, { + meta: { + ignoreAuth: false, + toast: false, + }, + }) +} + +// 获取所有替换词文件 +export function getCorrectWordFiles() { + return http.Get('/correct-word/file/select', { meta: { ignoreAuth: false, toast: false, diff --git a/main/manager-mobile/src/api/agent/types.ts b/main/manager-mobile/src/api/agent/types.ts index f04ef3d1c..440f50708 100644 --- a/main/manager-mobile/src/api/agent/types.ts +++ b/main/manager-mobile/src/api/agent/types.ts @@ -44,10 +44,12 @@ export interface AgentDetail { createdAt: string updater: string updatedAt: string - ttsLanguage: string - ttsVolume: number - ttsRate: number - ttsPitch: number + ttsLanguage: string | null + ttsVolume: number | null + ttsRate: number | null + ttsPitch: number | null + currentVersionNo?: number | null + tagNames?: string[] functions: AgentFunction[] contextProviders: Providers[] } @@ -67,6 +69,59 @@ export interface AgentFunction { paramInfo: Record | null } +export interface PageData { + list: T[] + total: number +} + +export interface AgentSnapshotData extends Partial { + correctWordFileIds?: string[] + tagNames?: string[] + tags?: Array<{ + tagName?: string + [key: string]: any + }> + [key: string]: any +} + +export interface AgentSnapshot { + id: string + agentId: string + userId?: string + versionNo: number + changedFields?: string[] + fieldOrder?: string[] + source?: string + restoreFromSnapshotId?: string | null + restoreFromVersionNo?: number | null + currentStateToken?: string + currentSnapshotData?: AgentSnapshotData + creator?: string + createdAt?: string + snapshotData?: AgentSnapshotData + afterSnapshotData?: AgentSnapshotData +} + +export interface AgentSnapshotPageParams { + page?: number + limit?: number + maxVersionNo?: number +} + +export interface CorrectWordFile { + id: string + fileName: string + wordCount?: number +} + +export interface TtsVoice { + id: string + name: string + voiceDemo?: string | null + languages?: string | null + isClone?: boolean | null +} + // 角色模板数据类型 export interface RoleTemplate { id: string @@ -78,6 +133,7 @@ export interface RoleTemplate { vllmModelId: string ttsModelId: string ttsVoiceId: string + ttsLanguage?: string | null memModelId: string intentModelId: string chatHistoryConf: number diff --git a/main/manager-mobile/src/api/device/types.ts b/main/manager-mobile/src/api/device/types.ts index 4b6165c53..8b0de4e1c 100644 --- a/main/manager-mobile/src/api/device/types.ts +++ b/main/manager-mobile/src/api/device/types.ts @@ -7,7 +7,7 @@ export interface Device { id: string userId: string macAddress: string - lastConnectedAt: string + lastConnectedAtTimestamp: string | null autoUpdate: number board: string alias?: string diff --git a/main/manager-mobile/src/i18n/de.ts b/main/manager-mobile/src/i18n/de.ts index 307ff7913..d09593672 100644 --- a/main/manager-mobile/src/i18n/de.ts +++ b/main/manager-mobile/src/i18n/de.ts @@ -1,157 +1,251 @@ // Deutsch Sprachpaket export default { - // TabBar - 'tabBar.home': 'Startseite', - 'tabBar.deviceConfig': 'Netzwerkkonfig', - 'tabBar.settings': 'System', - // Einstellungsseitentitel - 'settings.title': 'Einstellungen', - // Anmeldeseite - 'login.pageTitle': 'Anmelden', - 'login.navigationTitle': 'Anmelden', - 'login.fetchConfigError': 'Konfiguration konnte nicht abgerufen werden:', - 'login.selectLanguage': 'Sprache auswählen', - 'login.selectLanguageTip': 'De', - 'login.welcomeBack': 'Willkommen zurück', - 'login.pleaseLogin': 'Bitte melden Sie sich an', - 'login.enterUsername': 'Bitte Benutzernamen eingeben', - 'login.enterPassword': 'Bitte Passwort eingeben', - 'login.enterCaptcha': 'Bitte Bestätigungscode eingeben', - 'login.loginButton': 'Anmelden', - 'login.loggingIn': 'Wird angemeldet...', - 'login.noAccount': 'Registrieren', - 'login.enterPhone': 'Bitte Handynummer eingeben', - 'login.selectCountry': 'Land/Region auswählen', - 'login.confirm': 'Bestätigen', - 'login.serverSetting': 'Server-Einstellungen', - 'login.requiredUsername': 'Benutzername darf nicht leer sein', - 'login.requiredPassword': 'Passwort darf nicht leer sein', - 'login.requiredCaptcha': 'Bestätigungscode darf nicht leer sein', - 'login.requiredMobile': 'Bitte gültige Handynummer eingeben', - 'login.captchaError': 'Grafischer Bestätigungscode Fehler', - 'login.forgotPassword': 'Passwort vergessen', - 'login.userAgreement': 'Nutzungsbedingungen', - 'login.privacyPolicy': 'Datenschutzrichtlinie', + // TabBar + 'tabBar.home': 'Startseite', + 'tabBar.deviceConfig': 'Netzwerkkonfig', + 'tabBar.settings': 'System', + // Einstellungsseitentitel + 'settings.title': 'Einstellungen', + // Anmeldeseite + 'login.pageTitle': 'Anmelden', + 'login.navigationTitle': 'Anmelden', + 'login.fetchConfigError': 'Konfiguration konnte nicht abgerufen werden:', + 'login.selectLanguage': 'Sprache auswählen', + 'login.selectLanguageTip': 'De', + 'login.welcomeBack': 'Willkommen zurück', + 'login.pleaseLogin': 'Bitte melden Sie sich an', + 'login.enterUsername': 'Bitte Benutzernamen eingeben', + 'login.enterPassword': 'Bitte Passwort eingeben', + 'login.enterCaptcha': 'Bitte Bestätigungscode eingeben', + 'login.loginButton': 'Anmelden', + 'login.loggingIn': 'Wird angemeldet...', + 'login.noAccount': 'Registrieren', + 'login.enterPhone': 'Bitte Handynummer eingeben', + 'login.selectCountry': 'Land/Region auswählen', + 'login.confirm': 'Bestätigen', + 'login.serverSetting': 'Server-Einstellungen', + 'login.requiredUsername': 'Benutzername darf nicht leer sein', + 'login.requiredPassword': 'Passwort darf nicht leer sein', + 'login.requiredCaptcha': 'Bestätigungscode darf nicht leer sein', + 'login.requiredMobile': 'Bitte gültige Handynummer eingeben', + 'login.captchaError': 'Grafischer Bestätigungscode Fehler', + 'login.forgotPassword': 'Passwort vergessen', + 'login.userAgreement': 'Nutzungsbedingungen', + 'login.privacyPolicy': 'Datenschutzrichtlinie', - // Registrierungsseite - 'register.pageTitle': 'Registrieren', - 'register.createAccount': 'Konto erstellen', - 'register.enterUsername': 'Bitte Benutzernamen eingeben', - 'register.enterPassword': 'Bitte Passwort eingeben', - 'register.confirmPassword': 'Bitte Passwort bestätigen', - 'register.enterPhone': 'Bitte Handynummer eingeben', - 'register.enterCode': 'Bitte Bestätigungscode eingeben', - 'register.getCode': 'Code erhalten', - 'register.agreeTerms': 'Ich habe gelesen und stimme zu', - 'register.terms': 'Nutzungsbedingungen', - 'register.privacy': 'Datenschutzrichtlinie', - 'register.registerButton': 'Registrieren', - 'register.registering': 'Wird registriert...', - 'register.haveAccount': 'Bereits ein Konto?', - 'register.loginNow': 'Jetzt anmelden', - 'register.selectCountry': 'Land/Region auswählen', - 'register.confirm': 'Bestätigen', - 'register.captchaSendSuccess': 'Bestätigungscode erfolgreich gesendet', + // Registrierungsseite + 'register.pageTitle': 'Registrieren', + 'register.createAccount': 'Konto erstellen', + 'register.enterUsername': 'Bitte Benutzernamen eingeben', + 'register.enterPassword': 'Bitte Passwort eingeben', + 'register.confirmPassword': 'Bitte Passwort bestätigen', + 'register.enterPhone': 'Bitte Handynummer eingeben', + 'register.enterCode': 'Bitte Bestätigungscode eingeben', + 'register.getCode': 'Code erhalten', + 'register.agreeTerms': 'Ich habe gelesen und stimme zu', + 'register.terms': 'Nutzungsbedingungen', + 'register.privacy': 'Datenschutzrichtlinie', + 'register.registerButton': 'Registrieren', + 'register.registering': 'Wird registriert...', + 'register.haveAccount': 'Bereits ein Konto?', + 'register.loginNow': 'Jetzt anmelden', + 'register.selectCountry': 'Land/Region auswählen', + 'register.confirm': 'Bestätigen', + 'register.captchaSendSuccess': 'Bestätigungscode erfolgreich gesendet', - // Startseite - 'home.pageTitle': 'Startseite', - 'home.createAgent': 'Agent erstellen', - 'home.agentName': 'Agent', - 'home.modelInfo': 'Modell-Info', - 'home.lastActive': 'Zuletzt aktiv', - 'home.greeting': 'Hallo Jarvis', - 'home.subtitle': 'Lassen Sie uns', - 'home.wonderfulDay': 'einen wunderbaren Tag haben!', - 'home.emptyState': 'Keine Agenten verfügbar', - 'home.deviceManagement': 'Geräteverwaltung', - 'home.lastConversation': 'Letzte Konversation:', - 'home.delete': 'Löschen', - 'home.createFirstAgent': 'Klicken Sie auf die + Schaltfläche unten rechts, um Ihren ersten Agenten zu erstellen', - 'home.dialogTitle': 'Agent erstellen', - 'home.inputPlaceholder': 'z.B. Kundenservice-Assistent, Sprachassistent, Wissens-F&A', - 'home.createError': 'Der Name muss zwischen 1 und 64 Zeichen lang sein.', - 'home.createNow': 'Jetzt erstellen', - 'home.justNow': 'Gerade eben', - 'home.minutesAgo': 'Minuten her', - 'home.hoursAgo': 'Stunden her', - 'home.daysAgo': 'Tage her', - 'home.languageModel': 'LLM', - 'home.voiceModel': 'TTS', + // Startseite + 'home.pageTitle': 'Startseite', + 'home.createAgent': 'Agent erstellen', + 'home.agentName': 'Agent', + 'home.modelInfo': 'Modell-Info', + 'home.lastActive': 'Zuletzt aktiv', + 'home.greeting': 'Hallo Jarvis', + 'home.subtitle': 'Lassen Sie uns', + 'home.wonderfulDay': 'einen wunderbaren Tag haben!', + 'home.emptyState': 'Keine Agenten verfügbar', + 'home.deviceManagement': 'Geräteverwaltung', + 'home.lastConversation': 'Letzte Konversation:', + 'home.delete': 'Löschen', + 'home.createFirstAgent': 'Klicken Sie auf die + Schaltfläche unten rechts, um Ihren ersten Agenten zu erstellen', + 'home.dialogTitle': 'Agent erstellen', + 'home.inputPlaceholder': 'z.B. Kundenservice-Assistent, Sprachassistent, Wissens-F&A', + 'home.createError': 'Der Name muss zwischen 1 und 64 Zeichen lang sein.', + 'home.createNow': 'Jetzt erstellen', + 'home.deleteConfirmTitle': 'Agent löschen', + 'home.confirmDeleteAgent': 'Das Löschen kann nicht rückgängig gemacht werden. Geben Sie den Agentennamen "{agentName}" ein, um zu bestätigen.', + 'home.deleteAgentNamePlaceholder': 'Agentennamen eingeben', + 'home.deleteAgentNameMismatch': 'Der Agentenname stimmt nicht überein', + 'home.deleteAgentPasteForbidden': 'Bitte geben Sie den Agentennamen manuell ein. Einfügen ist nicht erlaubt.', + 'home.deleteAgentMissingInfo': 'Agenteninformationen konnten nicht bestätigt werden. Bitte aktualisieren und erneut versuchen.', + 'home.deleteAgentSuccess': 'Agent erfolgreich gelöscht', + 'home.justNow': 'Gerade eben', + 'home.minutesAgo': 'Minuten her', + 'home.hoursAgo': 'Stunden her', + 'home.daysAgo': 'Tage her', + 'home.languageModel': 'LLM', + 'home.voiceModel': 'TTS', - // Agentenseite - 'agent.pageTitle': 'Agent', - 'agent.roleConfig': 'Rollenkonfiguration', - 'agent.deviceManagement': 'Geräteverwaltung', - 'agent.chatHistory': 'Chat-Verlauf', - 'agent.voiceprintManagement': 'Stimmabdruckverwaltung', - 'agent.editTitle': 'Agent bearbeiten', - 'agent.toolsTitle': 'Bearbeiten', - 'agent.voiceActivityDetection': 'Sprachaktivitätserkennung', - 'agent.speechRecognition': 'Spracherkennung', - 'agent.largeLanguageModel': 'Großes Sprachmodell', - 'agent.save': 'Speichern', - 'agent.cancel': 'Abbrechen', - // Agenten-Bearbeitungsseite - 'agent.basicInfo': 'Grundinformationen', - 'agent.agentName': 'Agentenname', - 'agent.inputAgentName': 'Bitte Agenten-Namen eingeben', - 'agent.roleMode': 'Rollenmodus', - 'agent.agentTag': 'Smart Body-Etiketten', - 'agent.addAgentTag': 'Tags hinzufügen', - 'agent.inputAgentTag': 'Bitte Smart Body-Etiketten eingeben', - 'agent.contextProvider': 'Kontext', - 'agent.contextProviderSuccess': '{count} Quellen erfolgreich hinzugefügt.', - 'agent.contextProviderDocLink': 'Wie man Kontextquellen bereitstellt', - 'agent.editContextProvider': 'Quelle bearbeiten', - 'agent.roleDescription': 'Rollenbeschreibung', - 'agent.inputRoleDescription': 'Bitte Rollenbeschreibung eingeben', - 'agent.modelConfig': 'Modellkonfiguration', - 'agent.vad': 'Sprachaktivitätserkennung', - 'agent.asr': 'Spracherkennung', - 'agent.llm': 'Hauptsprachenmodell', - 'agent.slm': 'Kleine Parametermodelle', - 'agent.vllm': 'Vision-Sprachmodell', - 'agent.intent': 'Absichtserkennung', - 'agent.memory': 'Speicher', - 'agent.voiceSettings': 'Stimmeinstellungen', - 'agent.tts': 'Text-zu-Sprache', - 'agent.voiceprint': 'Agenten-Stimme', - 'agent.plugins': 'Plugins', - 'agent.editFunctions': 'Bearbeiten', - 'agent.historyMemory': 'Verlaufsspeicher', - 'agent.memoryContent': 'Speicherinhalt', - 'agent.saving': 'Wird gespeichert...', - 'agent.saveSuccess': 'Erfolgreich gespeichert', - 'agent.saveFail': 'Speichern fehlgeschlagen', - 'agent.loadFail': 'Laden fehlgeschlagen', - 'agent.pleaseInputAgentName': 'Bitte Agenten-Namen eingeben', - 'agent.pleaseInputRoleDescription': 'Bitte Rollenbeschreibung eingeben', - 'agent.pleaseSelect': 'Bitte auswählen', - 'agent.reportText': 'Text melden', - 'agent.reportTextVoice': 'Text + Sprache melden', - 'agent.reportMode': 'Meldemodus', - 'agent.language': 'Unterhaltungssprache', - 'agent.languageConfig': 'Sprachgeschwindigkeit & Tonhöhe', - 'agent.ttsVolume': 'Lautstärke', - 'agent.ttsRate': 'Sprechtempo', - 'agent.ttsPitch': 'Tonhöhe', - 'agent.volumeHint': '-100=min, 0=Standard, 100=max', - 'agent.speedHint': '-100=langsamst, 0=Standard, 100=schnellst', - 'agent.pitchHint': '-100=tiefst, 0=Standard, 100=höchst', + // Agentenseite + 'agent.pageTitle': 'Agent', + 'agent.roleConfig': 'Rollenkonfiguration', + 'agent.deviceManagement': 'Geräteverwaltung', + 'agent.chatHistory': 'Chat-Verlauf', + 'agent.voiceprintManagement': 'Stimmabdruckverwaltung', + 'agent.editTitle': 'Agent bearbeiten', + 'agent.toolsTitle': 'Bearbeiten', + 'agent.voiceActivityDetection': 'Sprachaktivitätserkennung', + 'agent.speechRecognition': 'Spracherkennung', + 'agent.largeLanguageModel': 'Großes Sprachmodell', + 'agent.save': 'Speichern', + 'agent.cancel': 'Abbrechen', + // Agenten-Bearbeitungsseite + 'agent.basicInfo': 'Grundinformationen', + 'agent.agentName': 'Agentenname', + 'agent.inputAgentName': 'Bitte Agenten-Namen eingeben', + 'agent.roleMode': 'Rollenmodus', + 'agent.agentTag': 'Smart Body-Etiketten', + 'agent.addAgentTag': 'Tags hinzufügen', + 'agent.inputAgentTag': 'Bitte Smart Body-Etiketten eingeben', + 'agent.contextProvider': 'Kontext', + 'agent.contextProviderSuccess': '{count} Quellen erfolgreich hinzugefügt.', + 'agent.contextProviderDocLink': 'Wie man Kontextquellen bereitstellt', + 'agent.editContextProvider': 'Quelle bearbeiten', + 'agent.roleDescription': 'Rollenbeschreibung', + 'agent.inputRoleDescription': 'Bitte Rollenbeschreibung eingeben', + 'agent.modelConfig': 'Modellkonfiguration', + 'agent.vad': 'Sprachaktivitätserkennung', + 'agent.asr': 'Spracherkennung', + 'agent.llm': 'Hauptsprachenmodell', + 'agent.slm': 'Kleine Parametermodelle', + 'agent.vllm': 'Vision-Sprachmodell', + 'agent.intent': 'Absichtserkennung', + 'agent.memory': 'Speicher', + 'agent.voiceSettings': 'Stimmeinstellungen', + 'agent.tts': 'Text-zu-Sprache', + 'agent.voiceprint': 'Agenten-Stimme', + 'agent.plugins': 'Plugins', + 'agent.editFunctions': 'Bearbeiten', + 'agent.historyMemory': 'Verlaufsspeicher', + 'agent.memoryContent': 'Speicherinhalt', + 'agent.saving': 'Wird gespeichert...', + 'agent.saveSuccess': 'Erfolgreich gespeichert', + 'agent.saveFail': 'Speichern fehlgeschlagen', + 'agent.ttsOptionsLoadFailed': 'Die Sprachoptionen konnten nicht geladen werden. Die vorherigen Einstellungen wurden beibehalten.', + 'agent.loadFail': 'Laden fehlgeschlagen', + 'agent.pleaseInputAgentName': 'Bitte Agenten-Namen eingeben', + 'agent.pleaseInputRoleDescription': 'Bitte Rollenbeschreibung eingeben', + 'agent.pleaseSelect': 'Bitte auswählen', + 'agent.reportText': 'Text melden', + 'agent.reportTextVoice': 'Text + Sprache melden', + 'agent.reportMode': 'Meldemodus', + 'agent.language': 'Unterhaltungssprache', + 'agent.languageConfig': 'Sprachgeschwindigkeit & Tonhöhe', + 'agent.ttsVolume': 'Lautstärke', + 'agent.ttsRate': 'Sprechtempo', + 'agent.ttsPitch': 'Tonhöhe', + 'agent.volumeHint': '-100=min, 0=Standard, 100=max', + 'agent.speedHint': '-100=langsamst, 0=Standard, 100=schnellst', + 'agent.pitchHint': '-100=tiefst, 0=Standard, 100=höchst', - // Context provider dialog related - 'contextProviderDialog.title': 'Quelle bearbeiten', - 'contextProviderDialog.noContextApi': 'Keine Kontext-API', - 'contextProviderDialog.add': 'Hinzufügen', - 'contextProviderDialog.apiUrl': 'API-URL', - 'contextProviderDialog.apiUrlPlaceholder': 'http://api.example.com/data', - 'contextProviderDialog.requestHeaders': 'Anfrage-Header', - 'contextProviderDialog.headerKeyPlaceholder': 'Schlüssel', - 'contextProviderDialog.headerValuePlaceholder': 'Wert', - 'contextProviderDialog.noHeaders': 'Keine Headers', - 'contextProviderDialog.addHeader': 'Header hinzufügen', - 'contextProviderDialog.cancel': 'Abbrechen', - 'contextProviderDialog.confirm': 'Bestätigen', + // Agent-Versionsverlauf + 'agentSnapshot.title': 'Versionsverlauf', + 'agentSnapshot.empty': 'Noch keine Versionen', + 'agentSnapshot.emptyTip': 'Gespeicherte Konfigurationen erscheinen hier', + 'agentSnapshot.version': 'Version', + 'agentSnapshot.createdAt': 'Gespeichert am', + 'agentSnapshot.source': 'Quelle', + 'agentSnapshot.changedFields': 'Änderungen', + 'agentSnapshot.view': 'Ansehen', + 'agentSnapshot.restore': 'Wiederherstellen', + 'agentSnapshot.delete': 'Löschen', + 'agentSnapshot.loadMore': 'Mehr laden', + 'agentSnapshot.detailTitle': 'Änderungsdetails', + 'agentSnapshot.restorePreviewTitle': 'Wiederherstellungsvorschau', + 'agentSnapshot.confirmRestore': 'Wiederherstellung bestätigen', + 'agentSnapshot.currentVersion': 'Neuester Snapshot', + 'agentSnapshot.beforeChange': 'Vorher', + 'agentSnapshot.afterChange': 'Nachher', + 'agentSnapshot.beforeRestore': 'Vor der Wiederherstellung', + 'agentSnapshot.afterRestore': 'Nach der Wiederherstellung', + 'agentSnapshot.configValue': 'Konfigurationswert', + 'agentSnapshot.emptyValue': 'Keine', + 'agentSnapshot.secretRedacted': 'Geheimnis verborgen', + 'agentSnapshot.redactedValueChanged': 'Der Wert ist ausgeblendet, wurde aber geändert', + 'agentSnapshot.noChangedContent': 'Keine anzeigbaren Änderungen', + 'agentSnapshot.recordedChange': 'Bei der Aufzeichnung geändert', + 'agentSnapshot.noRestoreNeeded': 'Die aktuelle Konfiguration entspricht bereits dieser Version', + 'agentSnapshot.unsavedChangesTitle': 'Nicht gespeicherte Änderungen', + 'agentSnapshot.unsavedChangesWarning': 'Beim Fortfahren werden die nicht gespeicherten Änderungen auf dieser Seite verworfen.', + 'agentSnapshot.discardAndRestore': 'Verwerfen und wiederherstellen', + 'agentSnapshot.restoreConfirm': 'Version #{version} wiederherstellen? Die aktuelle Konfiguration bleibt im Verlauf erhalten.', + 'agentSnapshot.restoreMemoryWarning': 'Beim Wiederherstellen einer Version ohne Speicher wird der Chatverlauf dieses Agenten gelöscht. Bitte Risiko bestätigen.', + 'agentSnapshot.restoreChatHistoryDestructiveWarning': 'Diese Wiederherstellung löscht den vorhandenen Chatverlauf dieses Agenten dauerhaft. Der Chatverlauf ist nicht in Konfigurations-Snapshots enthalten und kann nicht über den Versionsverlauf wiederhergestellt werden.', + 'agentSnapshot.restoreSuccess': 'Version wurde wiederhergestellt', + 'agentSnapshot.restoreFailed': 'Version konnte nicht wiederhergestellt werden', + 'agentSnapshot.reloadAfterRestorePending': 'Die wiederhergestellte Konfiguration und die Tags werden neu geladen. Speichern ist bis zum Abschluss deaktiviert.', + 'agentSnapshot.reloadAfterRestoreFailed': 'Die wiederhergestellte Konfiguration oder die Tags konnten nicht neu geladen werden. Speichern bleibt deaktiviert, damit veraltete Daten die Wiederherstellung nicht überschreiben. Bitte erneut versuchen.', + 'agentSnapshot.retryReload': 'Neu laden', + 'agentSnapshot.mutationBusy': 'Die Konfiguration wird gespeichert oder neu geladen. Bitte warten Sie, bevor Sie den Versionsverlauf öffnen oder eine Wiederherstellung starten.', + 'agentSnapshot.deleteConfirm': 'Version #{version} löschen? Dies kann nicht rückgängig gemacht werden.', + 'agentSnapshot.deleteSuccess': 'Version gelöscht', + 'agentSnapshot.deleteFailed': 'Version konnte nicht gelöscht werden', + 'agentSnapshot.fetchFailed': 'Versionsverlauf konnte nicht abgerufen werden', + 'agentSnapshot.detailFailed': 'Versionsdetails konnten nicht abgerufen werden', + 'agentSnapshot.correctWordCount': '{count} Ersatzwörter', + 'agentSnapshot.source.config': 'Konfiguration gespeichert', + 'agentSnapshot.source.current': 'Aktuelle Konfiguration', + 'agentSnapshot.source.restore': 'Wiederhergestellt', + 'agentSnapshot.source.initial': 'Initialversion', + 'agentSnapshot.field.initial': 'Initialer Snapshot', + 'agentSnapshot.field.agentCode': 'Agent-Code', + 'agentSnapshot.field.agentName': 'Spitzname', + 'agentSnapshot.field.asrModelId': 'Spracherkennung', + 'agentSnapshot.field.vadModelId': 'Sprachaktivitätserkennung', + 'agentSnapshot.field.llmModelId': 'Hauptsprachmodell', + 'agentSnapshot.field.slmModelId': 'Kleines Sprachmodell', + 'agentSnapshot.field.vllmModelId': 'Vision-Modell', + 'agentSnapshot.field.ttsModelId': 'Text-zu-Sprache', + 'agentSnapshot.field.ttsVoiceId': 'Stimme', + 'agentSnapshot.field.ttsLanguage': 'Sprache', + 'agentSnapshot.field.ttsVolume': 'Lautstärke', + 'agentSnapshot.field.ttsRate': 'Geschwindigkeit', + 'agentSnapshot.field.ttsPitch': 'Tonhöhe', + 'agentSnapshot.field.memModelId': 'Speichermodus', + 'agentSnapshot.field.intentModelId': 'Absichtserkennung', + 'agentSnapshot.field.chatHistoryConf': 'Chatverlauf-Konfiguration', + 'agentSnapshot.field.systemPrompt': 'Rollenbeschreibung', + 'agentSnapshot.field.summaryMemory': 'Speicher', + 'agentSnapshot.field.langCode': 'Sprachcode', + 'agentSnapshot.field.language': 'Interaktionssprache', + 'agentSnapshot.field.sort': 'Sortierung', + 'agentSnapshot.field.functions': 'Plugins', + 'agentSnapshot.field.contextProviders': 'Kontextquellen', + 'agentSnapshot.field.correctWordFileIds': 'Ersatzwörter', + 'agentSnapshot.field.tagNames': 'Agent-Labels', + 'agentSnapshot.chatHistoryConf.none': 'Chatverlauf nicht aufzeichnen', + 'agentSnapshot.chatHistoryConf.text': 'Text melden', + 'agentSnapshot.chatHistoryConf.textVoice': 'Text und Sprache melden', + 'agentSnapshot.model.Memory_nomem': 'Kein Speicher', + 'agentSnapshot.model.Memory_mem_local_short': 'Lokaler Kurzzeitspeicher', + 'agentSnapshot.model.Memory_mem0ai': 'Mem0AI-Speicher', + 'agentSnapshot.model.Memory_mem_report_only': 'Nur melden', + 'agentSnapshot.model.Intent_nointent': 'Keine Absichtserkennung', + 'agentSnapshot.model.Intent_intent_llm': 'Externe LLM-Absichtserkennung', + 'agentSnapshot.model.Intent_function_call': 'LLM-Funktionsaufruf', + + // Context provider dialog related + 'contextProviderDialog.title': 'Quelle bearbeiten', + 'contextProviderDialog.noContextApi': 'Keine Kontext-API', + 'contextProviderDialog.add': 'Hinzufügen', + 'contextProviderDialog.apiUrl': 'API-URL', + 'contextProviderDialog.apiUrlPlaceholder': 'http://api.example.com/data', + 'contextProviderDialog.requestHeaders': 'Anfrage-Header', + 'contextProviderDialog.headerKeyPlaceholder': 'Schlüssel', + 'contextProviderDialog.headerValuePlaceholder': 'Wert', + 'contextProviderDialog.noHeaders': 'Keine Headers', + 'contextProviderDialog.addHeader': 'Header hinzufügen', + 'contextProviderDialog.cancel': 'Abbrechen', + 'contextProviderDialog.confirm': 'Bestätigen', // Manual add device dialog related 'manualAddDeviceDialog.title': 'Manuell Gerät hinzufügen', @@ -172,222 +266,222 @@ export default { 'manualAddDeviceDialog.addFailed': 'Hinzufügen fehlgeschlagen', 'manualAddDeviceDialog.bindWithCode': 'Mit 6-stelligem Code binden', - // Chat-Verlauf Seite - 'chatHistory.getChatSessions': 'Chat-Sitzungsliste abrufen', - 'chatHistory.noSelectedAgent': 'Kein Agent ausgewählt', - 'chatHistory.getChatSessionsFailed': 'Chat-Sitzungsliste konnte nicht abgerufen werden:', - 'chatHistory.unknownTime': 'Unbekannte Zeit', - 'chatHistory.justNow': 'Gerade eben', - 'chatHistory.minutesAgo': 'Vor {minutes} Minuten', - 'chatHistory.hoursAgo': 'Vor {hours} Stunden', - 'chatHistory.daysAgo': 'Vor {days} Tagen', - 'chatHistory.conversationRecord': 'Konversationsaufzeichnung', - 'chatHistory.totalChats': 'Insgesamt {count} Chats', - 'chatHistory.loading': 'Lädt...', - 'chatHistory.noMoreData': 'Keine weiteren Daten', - 'chatHistory.noChatRecords': 'Keine Chat-Aufzeichnungen', - 'chatHistory.chatRecordsDescription': 'Konversationsaufzeichnungen mit Agenten werden hier angezeigt', - // Chat-Verlauf Detailseite - 'chatHistory.pageTitle': 'Chat-Details', - 'chatHistory.assistantName': 'Intelligenter Assistent', - 'chatHistory.userName': 'Benutzer', - 'chatHistory.aiAssistantName': 'KI-Assistent', - 'chatHistory.loadFailed': 'Chat-Verlauf konnte nicht geladen werden', - 'chatHistory.parameterError': 'Seitenparameter Fehler', - 'chatHistory.invalidAudioId': 'Ungültige Audio-ID', - 'chatHistory.audioPlayFailed': 'Audio-Wiedergabe fehlgeschlagen', - 'chatHistory.playAudioFailed': 'Audio konnte nicht abgespielt werden', + // Chat-Verlauf Seite + 'chatHistory.getChatSessions': 'Chat-Sitzungsliste abrufen', + 'chatHistory.noSelectedAgent': 'Kein Agent ausgewählt', + 'chatHistory.getChatSessionsFailed': 'Chat-Sitzungsliste konnte nicht abgerufen werden:', + 'chatHistory.unknownTime': 'Unbekannte Zeit', + 'chatHistory.justNow': 'Gerade eben', + 'chatHistory.minutesAgo': 'Vor {minutes} Minuten', + 'chatHistory.hoursAgo': 'Vor {hours} Stunden', + 'chatHistory.daysAgo': 'Vor {days} Tagen', + 'chatHistory.conversationRecord': 'Konversationsaufzeichnung', + 'chatHistory.totalChats': 'Insgesamt {count} Chats', + 'chatHistory.loading': 'Lädt...', + 'chatHistory.noMoreData': 'Keine weiteren Daten', + 'chatHistory.noChatRecords': 'Keine Chat-Aufzeichnungen', + 'chatHistory.chatRecordsDescription': 'Konversationsaufzeichnungen mit Agenten werden hier angezeigt', + // Chat-Verlauf Detailseite + 'chatHistory.pageTitle': 'Chat-Details', + 'chatHistory.assistantName': 'Intelligenter Assistent', + 'chatHistory.userName': 'Benutzer', + 'chatHistory.aiAssistantName': 'KI-Assistent', + 'chatHistory.loadFailed': 'Chat-Verlauf konnte nicht geladen werden', + 'chatHistory.parameterError': 'Seitenparameter Fehler', + 'chatHistory.invalidAudioId': 'Ungültige Audio-ID', + 'chatHistory.audioPlayFailed': 'Audio-Wiedergabe fehlgeschlagen', + 'chatHistory.playAudioFailed': 'Audio konnte nicht abgespielt werden', - // Geräteverwaltungsseite - 'device.pageTitle': 'Geräteverwaltung', - 'device.noDevices': 'Keine Geräte verfügbar', - 'device.macAddress': 'MAC-Adresse', - 'device.firmwareVersion': 'Firmware-Version', - 'device.lastConnected': 'Letzte Konversation', - 'device.otaUpdate': 'OTA-Update', - 'device.unbind': 'Entbinden', - 'device.confirmUnbind': 'Bestätigen', - 'device.bindDevice': 'Neues Gerät binden', - 'device.deviceType': 'Gerätetyp', - 'device.loading': 'Lädt...', - 'device.neverConnected': 'Nie verbunden', - 'device.justNow': 'Gerade eben', - 'device.minutesAgo': 'Vor {minutes} Minuten', - 'device.hoursAgo': 'Vor {hours} Stunden', - 'device.daysAgo': 'Vor {days} Tagen', - 'device.otaAutoUpdateEnabled': 'OTA Auto-Update aktiviert', - 'device.otaAutoUpdateDisabled': 'OTA Auto-Update deaktiviert', - 'device.operationFailed': 'Operation fehlgeschlagen, bitte erneut versuchen', - 'device.deviceUnbound': 'Gerät entbunden', - 'device.unbindFailed': 'Entbinden fehlgeschlagen, bitte erneut versuchen', - 'device.unbindDevice': 'Gerät entbinden', - 'device.confirmUnbindDevice': 'Sind Sie sicher, dass Sie Gerät "{macAddress}" entbinden möchten?', - 'device.cancel': 'Abbrechen', - 'device.noDevice': 'Kein Gerät', - 'device.pleaseSelectAgent': 'Bitte wählen Sie zuerst einen Agenten aus', - 'device.deviceBindSuccess': 'Gerät erfolgreich gebunden!', - 'device.bindFailed': 'Binden fehlgeschlagen, bitte prüfen Sie ob der Bestätigungscode korrekt ist', - 'device.enterDeviceCode': 'Bitte Geräte-Bestätigungscode eingeben', - 'device.bindNow': 'Jetzt binden', - 'device.lastConnection': 'Letzte Verbindung', - 'device.clickToBindFirstDevice': 'Klicken Sie auf die + Schaltfläche unten rechts, um Ihr erstes Gerät zu binden', + // Geräteverwaltungsseite + 'device.pageTitle': 'Geräteverwaltung', + 'device.noDevices': 'Keine Geräte verfügbar', + 'device.macAddress': 'MAC-Adresse', + 'device.firmwareVersion': 'Firmware-Version', + 'device.lastConnected': 'Letzte Konversation', + 'device.otaUpdate': 'OTA-Update', + 'device.unbind': 'Entbinden', + 'device.confirmUnbind': 'Bestätigen', + 'device.bindDevice': 'Neues Gerät binden', + 'device.deviceType': 'Gerätetyp', + 'device.loading': 'Lädt...', + 'device.neverConnected': 'Nie verbunden', + 'device.justNow': 'Gerade eben', + 'device.minutesAgo': 'Vor {minutes} Minuten', + 'device.hoursAgo': 'Vor {hours} Stunden', + 'device.daysAgo': 'Vor {days} Tagen', + 'device.otaAutoUpdateEnabled': 'OTA Auto-Update aktiviert', + 'device.otaAutoUpdateDisabled': 'OTA Auto-Update deaktiviert', + 'device.operationFailed': 'Operation fehlgeschlagen, bitte erneut versuchen', + 'device.deviceUnbound': 'Gerät entbunden', + 'device.unbindFailed': 'Entbinden fehlgeschlagen, bitte erneut versuchen', + 'device.unbindDevice': 'Gerät entbinden', + 'device.confirmUnbindDevice': 'Sind Sie sicher, dass Sie Gerät "{macAddress}" entbinden möchten?', + 'device.cancel': 'Abbrechen', + 'device.noDevice': 'Kein Gerät', + 'device.pleaseSelectAgent': 'Bitte wählen Sie zuerst einen Agenten aus', + 'device.deviceBindSuccess': 'Gerät erfolgreich gebunden!', + 'device.bindFailed': 'Binden fehlgeschlagen, bitte prüfen Sie ob der Bestätigungscode korrekt ist', + 'device.enterDeviceCode': 'Bitte Geräte-Bestätigungscode eingeben', + 'device.bindNow': 'Jetzt binden', + 'device.lastConnection': 'Letzte Verbindung', + 'device.clickToBindFirstDevice': 'Klicken Sie auf die + Schaltfläche unten rechts, um Ihr erstes Gerät zu binden', - // Allgemein - 'common.success': 'Erfolg', - 'common.fail': 'Fehlgeschlagen', - 'common.loading': 'Lädt...', - 'common.confirm': 'Bestätigen', - 'common.cancel': 'Abbrechen', - 'common.delete': 'Löschen', - 'common.edit': 'Bearbeiten', - 'common.add': 'Hinzufügen', - 'common.pleaseSelect': 'Bitte auswählen', - 'common.unknownError': 'Unbekannter Fehler', - 'common.networkError': 'Netzwerkfehler', + // Allgemein + 'common.success': 'Erfolg', + 'common.fail': 'Fehlgeschlagen', + 'common.loading': 'Lädt...', + 'common.confirm': 'Bestätigen', + 'common.cancel': 'Abbrechen', + 'common.delete': 'Löschen', + 'common.edit': 'Bearbeiten', + 'common.add': 'Hinzufügen', + 'common.pleaseSelect': 'Bitte auswählen', + 'common.unknownError': 'Unbekannter Fehler', + 'common.networkError': 'Netzwerkfehler', - // Passwort-Wiederherstellungsseite - 'retrievePassword.title': 'Passwort zurücksetzen', - 'retrievePassword.subtitle': 'Stellen Sie Ihr Kontopasswort über Handynummer wieder her', - 'retrievePassword.mobileRequired': 'Bitte Handynummer eingeben', - 'retrievePassword.inputCorrectMobile': 'Bitte gültige Handynummer eingeben', - 'retrievePassword.captchaRequired': 'Bitte grafischen Bestätigungscode eingeben', - 'retrievePassword.mobileCaptchaRequired': 'Bitte SMS-Bestätigungscode eingeben', - 'retrievePassword.newPasswordRequired': 'Bitte neues Passwort eingeben', - 'retrievePassword.confirmNewPasswordRequired': 'Bitte neues Passwort bestätigen', - 'retrievePassword.passwordsNotMatch': 'Passwörter stimmen nicht überein', - 'retrievePassword.mobilePlaceholder': 'Bitte Handynummer eingeben', - 'retrievePassword.captchaPlaceholder': 'Bitte grafischen Bestätigungscode eingeben', - 'retrievePassword.mobileCaptchaPlaceholder': 'Bitte SMS-Bestätigungscode eingeben', - 'retrievePassword.newPasswordPlaceholder': 'Bitte neues Passwort eingeben', - 'retrievePassword.confirmNewPasswordPlaceholder': 'Bitte neues Passwort bestätigen', - 'retrievePassword.getMobileCaptcha': 'Code erhalten', - 'retrievePassword.captchaSendSuccess': 'Bestätigungscode erfolgreich gesendet', - 'retrievePassword.passwordUpdateSuccess': 'Passwort erfolgreich zurückgesetzt', - 'retrievePassword.resetButton': 'Passwort zurücksetzen', - 'retrievePassword.goToLogin': 'Zurück zur Anmeldung', + // Passwort-Wiederherstellungsseite + 'retrievePassword.title': 'Passwort zurücksetzen', + 'retrievePassword.subtitle': 'Stellen Sie Ihr Kontopasswort über Handynummer wieder her', + 'retrievePassword.mobileRequired': 'Bitte Handynummer eingeben', + 'retrievePassword.inputCorrectMobile': 'Bitte gültige Handynummer eingeben', + 'retrievePassword.captchaRequired': 'Bitte grafischen Bestätigungscode eingeben', + 'retrievePassword.mobileCaptchaRequired': 'Bitte SMS-Bestätigungscode eingeben', + 'retrievePassword.newPasswordRequired': 'Bitte neues Passwort eingeben', + 'retrievePassword.confirmNewPasswordRequired': 'Bitte neues Passwort bestätigen', + 'retrievePassword.passwordsNotMatch': 'Passwörter stimmen nicht überein', + 'retrievePassword.mobilePlaceholder': 'Bitte Handynummer eingeben', + 'retrievePassword.captchaPlaceholder': 'Bitte grafischen Bestätigungscode eingeben', + 'retrievePassword.mobileCaptchaPlaceholder': 'Bitte SMS-Bestätigungscode eingeben', + 'retrievePassword.newPasswordPlaceholder': 'Bitte neues Passwort eingeben', + 'retrievePassword.confirmNewPasswordPlaceholder': 'Bitte neues Passwort bestätigen', + 'retrievePassword.getMobileCaptcha': 'Code erhalten', + 'retrievePassword.captchaSendSuccess': 'Bestätigungscode erfolgreich gesendet', + 'retrievePassword.passwordUpdateSuccess': 'Passwort erfolgreich zurückgesetzt', + 'retrievePassword.resetButton': 'Passwort zurücksetzen', + 'retrievePassword.goToLogin': 'Zurück zur Anmeldung', - // SM2-Verschlüsselungsbezogene Fehlermeldungen - 'sm2.publicKeyNotConfigured': 'SM2 öffentlicher Schlüssel nicht konfiguriert, bitte Administrator kontaktieren', - 'sm2.encryptionFailed': 'Passwortverschlüsselung fehlgeschlagen', - 'sm2.keyGenerationFailed': 'Schlüsselpaar-Generierung fehlgeschlagen', - 'sm2.invalidPublicKey': 'Ungültiges öffentliches Schlüsselformat', - 'sm2.encryptionError': 'Fehler bei der Verschlüsselung aufgetreten', - 'sm2.publicKeyRetry': 'Öffentlichen Schlüssel erneut abrufen...', - 'sm2.publicKeyRetryFailed': 'Wiederholter Abruf des öffentlichen Schlüssels fehlgeschlagen', + // SM2-Verschlüsselungsbezogene Fehlermeldungen + 'sm2.publicKeyNotConfigured': 'SM2 öffentlicher Schlüssel nicht konfiguriert, bitte Administrator kontaktieren', + 'sm2.encryptionFailed': 'Passwortverschlüsselung fehlgeschlagen', + 'sm2.keyGenerationFailed': 'Schlüsselpaar-Generierung fehlgeschlagen', + 'sm2.invalidPublicKey': 'Ungültiges öffentliches Schlüsselformat', + 'sm2.encryptionError': 'Fehler bei der Verschlüsselung aufgetreten', + 'sm2.publicKeyRetry': 'Öffentlichen Schlüssel erneut abrufen...', + 'sm2.publicKeyRetryFailed': 'Wiederholter Abruf des öffentlichen Schlüssels fehlgeschlagen', - // Stimmabdruckseite - 'voiceprint.noSelectedAgent': 'Kein Agent ausgewählt', - 'voiceprint.pleaseSelectAgent': 'Bitte wählen Sie zuerst einen Agenten aus', - 'voiceprint.fetchHistoryFailed': 'Chat-Verlauf konnte nicht abgerufen werden', - 'voiceprint.clickToSelectVector': 'Klicken zum Auswählen des Stimmabdruck-Vektors', - 'voiceprint.pleaseInputName': 'Bitte Namen eingeben', - 'voiceprint.pleaseSelectVector': 'Bitte Stimmabdruck-Vektor auswählen', - 'voiceprint.addSuccess': 'Erfolgreich hinzugefügt', - 'voiceprint.addFailed': 'Hinzufügen des Sprechers fehlgeschlagen', - 'voiceprint.editSuccess': 'Erfolgreich bearbeitet', - 'voiceprint.editFailed': 'Bearbeiten des Sprechers fehlgeschlagen', - 'voiceprint.deleteConfirmMsg': 'Sind Sie sicher, dass Sie diesen Sprecher löschen möchten?', - 'voiceprint.deleteConfirmTitle': 'Löschen bestätigen', - 'voiceprint.deleteSuccess': 'Erfolgreich gelöscht', - 'voiceprint.loading': 'Lädt...', - 'voiceprint.delete': 'Löschen', - 'voiceprint.emptyTitle': 'Keine Stimmabdruck-Daten', - 'voiceprint.emptyDesc': 'Klicken Sie auf die + Schaltfläche unten rechts, um Ihren ersten Sprecher hinzuzufügen', - 'voiceprint.addSpeaker': 'Sprecher hinzufügen', - 'voiceprint.voiceVector': 'Stimmabdruck-Vektor', - 'voiceprint.name': 'Name', - 'voiceprint.description': 'Beschreibung', - 'voiceprint.pleaseInputDescription': 'Bitte Beschreibung eingeben', - 'voiceprint.cancel': 'Abbrechen', - 'voiceprint.save': 'Speichern', - 'voiceprint.editSpeaker': 'Sprecher bearbeiten', - 'voiceprint.selectVector': 'Stimmabdruck-Vektor auswählen', - 'voiceprint.voiceprintInterfaceNotConfigured': 'Stimmabdruck-Schnittstelle nicht konfiguriert', + // Stimmabdruckseite + 'voiceprint.noSelectedAgent': 'Kein Agent ausgewählt', + 'voiceprint.pleaseSelectAgent': 'Bitte wählen Sie zuerst einen Agenten aus', + 'voiceprint.fetchHistoryFailed': 'Chat-Verlauf konnte nicht abgerufen werden', + 'voiceprint.clickToSelectVector': 'Klicken zum Auswählen des Stimmabdruck-Vektors', + 'voiceprint.pleaseInputName': 'Bitte Namen eingeben', + 'voiceprint.pleaseSelectVector': 'Bitte Stimmabdruck-Vektor auswählen', + 'voiceprint.addSuccess': 'Erfolgreich hinzugefügt', + 'voiceprint.addFailed': 'Hinzufügen des Sprechers fehlgeschlagen', + 'voiceprint.editSuccess': 'Erfolgreich bearbeitet', + 'voiceprint.editFailed': 'Bearbeiten des Sprechers fehlgeschlagen', + 'voiceprint.deleteConfirmMsg': 'Sind Sie sicher, dass Sie diesen Sprecher löschen möchten?', + 'voiceprint.deleteConfirmTitle': 'Löschen bestätigen', + 'voiceprint.deleteSuccess': 'Erfolgreich gelöscht', + 'voiceprint.loading': 'Lädt...', + 'voiceprint.delete': 'Löschen', + 'voiceprint.emptyTitle': 'Keine Stimmabdruck-Daten', + 'voiceprint.emptyDesc': 'Klicken Sie auf die + Schaltfläche unten rechts, um Ihren ersten Sprecher hinzuzufügen', + 'voiceprint.addSpeaker': 'Sprecher hinzufügen', + 'voiceprint.voiceVector': 'Stimmabdruck-Vektor', + 'voiceprint.name': 'Name', + 'voiceprint.description': 'Beschreibung', + 'voiceprint.pleaseInputDescription': 'Bitte Beschreibung eingeben', + 'voiceprint.cancel': 'Abbrechen', + 'voiceprint.save': 'Speichern', + 'voiceprint.editSpeaker': 'Sprecher bearbeiten', + 'voiceprint.selectVector': 'Stimmabdruck-Vektor auswählen', + 'voiceprint.voiceprintInterfaceNotConfigured': 'Stimmabdruck-Schnittstelle nicht konfiguriert', - // Einstellungsseite - 'settings.pageTitle': 'Einstellungen', - 'settings.navigationTitle': 'Einstellungen', - 'settings.networkSettings': 'Netzwerkeinstellungen', - 'settings.serverApiUrl': 'Server-API-URL', - 'settings.validServerUrl': 'Bitte gültige Serveradresse eingeben (beginnt mit http oder https und endet mit /xiaozhi)', - 'settings.saveSettings': 'Einstellungen speichern', - 'settings.resetDefault': 'Auf Standard zurücksetzen', - 'settings.restartApp': 'App neu starten', - 'settings.restartNow': 'Jetzt neu starten', - 'settings.restartLater': 'Später', - // Über uns - 'settings.aboutApp': 'Über XiaoZhi Konsole', - 'settings.aboutContent': 'XiaoZhi Konsole\n\nEine plattformübergreifende mobile Management-App, erstellt mit Vue.js 3 + uni-app, bietet Geräteverwaltung, Agentenkonfiguration und andere Funktionen für xiaozhi ESP32 Smart Hardware.\n\n© 2025 xiaozhi-esp32-server {version}', - 'settings.restartSuccess': 'Gespeichert, Sie können die App später manuell neu starten', - 'settings.serverUrlSavedAndCacheCleared': 'Server-URL gespeichert und Cache geleert', - 'settings.resetToDefaultAndCacheCleared': 'Auf Standard zurückgesetzt und Cache geleert', - 'settings.resetSuccess': 'Zurücksetzen erfolgreich', - 'settings.enterServerUrl': 'Bitte Server-URL eingeben', - 'settings.clearCacheFailed': 'Cache konnte nicht geleert werden', - 'settings.cacheManagement': 'Cache-Verwaltung', - 'settings.totalCacheSize': 'Gesamte Cache-Größe', - 'settings.appDataSize': 'Gesamte App-Datengröße', - 'settings.cacheClear': 'Cache leeren', - 'settings.clearAllCache': 'Alle Cache-Daten löschen', - 'settings.clearCache': 'Cache leeren', - 'settings.modifyWillClearCache': 'Änderungen werden Cache leeren', - 'settings.appInfo': 'App-Info', - 'settings.aboutUs': 'Über uns', - 'settings.appVersion': 'App-Version & Team-Info', - 'settings.confirmClear': 'Löschen bestätigen', - 'settings.confirmClearMessage': 'Sind Sie sicher, dass Sie den gesamten Cache löschen möchten? Dies löscht alle Daten einschließlich Anmeldestatus und erfordert erneute Anmeldung.', - 'settings.cacheCleared': 'Cache erfolgreich geleert, leite zur Anmeldeseite weiter', - 'settings.languageSettings': 'Spracheinstellungen', - 'settings.language': 'Sprache', - 'settings.selectLanguage': 'Sprache auswählen', - 'settings.languageChanged': 'Sprache erfolgreich geändert', + // Einstellungsseite + 'settings.pageTitle': 'Einstellungen', + 'settings.navigationTitle': 'Einstellungen', + 'settings.networkSettings': 'Netzwerkeinstellungen', + 'settings.serverApiUrl': 'Server-API-URL', + 'settings.validServerUrl': 'Bitte gültige Serveradresse eingeben (beginnt mit http oder https und endet mit /xiaozhi)', + 'settings.saveSettings': 'Einstellungen speichern', + 'settings.resetDefault': 'Auf Standard zurücksetzen', + 'settings.restartApp': 'App neu starten', + 'settings.restartNow': 'Jetzt neu starten', + 'settings.restartLater': 'Später', + // Über uns + 'settings.aboutApp': 'Über XiaoZhi Konsole', + 'settings.aboutContent': 'XiaoZhi Konsole\n\nEine plattformübergreifende mobile Management-App, erstellt mit Vue.js 3 + uni-app, bietet Geräteverwaltung, Agentenkonfiguration und andere Funktionen für xiaozhi ESP32 Smart Hardware.\n\n© 2025 xiaozhi-esp32-server {version}', + 'settings.restartSuccess': 'Gespeichert, Sie können die App später manuell neu starten', + 'settings.serverUrlSavedAndCacheCleared': 'Server-URL gespeichert und Cache geleert', + 'settings.resetToDefaultAndCacheCleared': 'Auf Standard zurückgesetzt und Cache geleert', + 'settings.resetSuccess': 'Zurücksetzen erfolgreich', + 'settings.enterServerUrl': 'Bitte Server-URL eingeben', + 'settings.clearCacheFailed': 'Cache konnte nicht geleert werden', + 'settings.cacheManagement': 'Cache-Verwaltung', + 'settings.totalCacheSize': 'Gesamte Cache-Größe', + 'settings.appDataSize': 'Gesamte App-Datengröße', + 'settings.cacheClear': 'Cache leeren', + 'settings.clearAllCache': 'Alle Cache-Daten löschen', + 'settings.clearCache': 'Cache leeren', + 'settings.modifyWillClearCache': 'Änderungen werden Cache leeren', + 'settings.appInfo': 'App-Info', + 'settings.aboutUs': 'Über uns', + 'settings.appVersion': 'App-Version & Team-Info', + 'settings.confirmClear': 'Löschen bestätigen', + 'settings.confirmClearMessage': 'Sind Sie sicher, dass Sie den gesamten Cache löschen möchten? Dies löscht alle Daten einschließlich Anmeldestatus und erfordert erneute Anmeldung.', + 'settings.cacheCleared': 'Cache erfolgreich geleert, leite zur Anmeldeseite weiter', + 'settings.languageSettings': 'Spracheinstellungen', + 'settings.language': 'Sprache', + 'settings.selectLanguage': 'Sprache auswählen', + 'settings.languageChanged': 'Sprache erfolgreich geändert', - // Nachrichten - 'message.loginSuccess': 'Anmeldung erfolgreich!', - 'message.loginFail': 'Anmeldung fehlgeschlagen', - 'message.registerSuccess': 'Registrierung erfolgreich', - 'message.registerFail': 'Registrierung fehlgeschlagen', - 'message.saveSuccess': 'Erfolgreich gespeichert', - 'message.saveFail': 'Speichern fehlgeschlagen', - 'message.deleteSuccess': 'Erfolgreich gelöscht', - 'message.deleteFail': 'Löschen fehlgeschlagen', - 'message.bindSuccess': 'Binden erfolgreich', - 'message.bindFail': 'Binden fehlgeschlagen', - 'message.unbindSuccess': 'Entbinden erfolgreich', - 'message.unbindFail': 'Entbinden fehlgeschlagen', - 'message.networkError': 'Netzwerkfehler, bitte Verbindung prüfen', - 'message.serverError': 'Serverfehler, bitte später erneut versuchen', - 'message.invalidAddress': 'Die Adresse kann ungültig sein. Bitte überprüfen Sie, ob der Server gestartet ist oder ob die Netzwerkverbindung funktioniert. Es kann auch sein, dass die Anfrage aufgrund eines Problems mit dem HTTPS-Protokoll nicht gesendet werden kann.', - 'message.languageChanged': 'Sprache geändert', - 'message.passwordError': 'Konto oder Passwort Fehler', - 'message.phoneRegistered': 'Diese Handynummer wurde bereits registriert', + // Nachrichten + 'message.loginSuccess': 'Anmeldung erfolgreich!', + 'message.loginFail': 'Anmeldung fehlgeschlagen', + 'message.registerSuccess': 'Registrierung erfolgreich', + 'message.registerFail': 'Registrierung fehlgeschlagen', + 'message.saveSuccess': 'Erfolgreich gespeichert', + 'message.saveFail': 'Speichern fehlgeschlagen', + 'message.deleteSuccess': 'Erfolgreich gelöscht', + 'message.deleteFail': 'Löschen fehlgeschlagen', + 'message.bindSuccess': 'Binden erfolgreich', + 'message.bindFail': 'Binden fehlgeschlagen', + 'message.unbindSuccess': 'Entbinden erfolgreich', + 'message.unbindFail': 'Entbinden fehlgeschlagen', + 'message.networkError': 'Netzwerkfehler, bitte Verbindung prüfen', + 'message.serverError': 'Serverfehler, bitte später erneut versuchen', + 'message.invalidAddress': 'Die Adresse kann ungültig sein. Bitte überprüfen Sie, ob der Server gestartet ist oder ob die Netzwerkverbindung funktioniert. Es kann auch sein, dass die Anfrage aufgrund eines Problems mit dem HTTPS-Protokoll nicht gesendet werden kann.', + 'message.languageChanged': 'Sprache geändert', + 'message.passwordError': 'Konto oder Passwort Fehler', + 'message.phoneRegistered': 'Diese Handynummer wurde bereits registriert', - // Agenten-Werkzeuge Seite - 'agent.tools.pageTitle': 'Agenten-Werkzeuge', - 'agent.tools.unselected': 'Nicht ausgewählt', - 'agent.tools.selected': 'Ausgewählt', - 'agent.tools.noMorePlugins': 'Keine weiteren Plugins', - 'agent.tools.pleaseSelectPlugin': 'Bitte Plugin-Funktion auswählen', - 'agent.tools.builtInPlugins': 'Eingebaute Plugins', - 'agent.tools.mcpAccessPoint': 'MCP-Zugangspunkt', - 'agent.tools.copy': 'Kopieren', - 'agent.tools.noTools': 'Keine Werkzeuge verfügbar', - 'agent.tools.parameterConfig': 'Konfig', - 'agent.tools.noParamsNeeded': 'Keine Parameter benötigt', - 'agent.tools.pleaseInput': 'Bitte eingeben', - 'agent.tools.inputOneItemPerLine': 'Ein Element pro Zeile eingeben', - 'agent.tools.pleaseInputValidJson': 'Bitte gültiges JSON-Format eingeben', - 'agent.tools.enableFunction': 'Funktion aktivieren', - 'agent.tools.toggleFunction': 'Diese Funktion ein- oder ausschalten', - 'agent.tools.jsonFormatError': 'JSON-Format Fehler', - 'agent.tools.noMcpAddressToCopy': 'Keine MCP-Adresse zum Kopieren', - 'agent.tools.mcpAddressCopied': 'MCP-Adresse in Zwischenablage kopiert', - 'agent.tools.copyFailed': 'Kopieren fehlgeschlagen, bitte erneut versuchen', - 'agent.tools.defaultValue': 'Standardwert', - 'agent.tools.notSelected': 'Nicht ausgewählt', - 'agent.tools.clickToConfigure': 'Klicken zum Konfigurieren', - 'agent.tools.mcpEndpoint': 'MCP-Endpunkt', - 'agent.tools.eachLineOneItem': 'Ein Element pro Zeile eingeben', + // Agenten-Werkzeuge Seite + 'agent.tools.pageTitle': 'Agenten-Werkzeuge', + 'agent.tools.unselected': 'Nicht ausgewählt', + 'agent.tools.selected': 'Ausgewählt', + 'agent.tools.noMorePlugins': 'Keine weiteren Plugins', + 'agent.tools.pleaseSelectPlugin': 'Bitte Plugin-Funktion auswählen', + 'agent.tools.builtInPlugins': 'Eingebaute Plugins', + 'agent.tools.mcpAccessPoint': 'MCP-Zugangspunkt', + 'agent.tools.copy': 'Kopieren', + 'agent.tools.noTools': 'Keine Werkzeuge verfügbar', + 'agent.tools.parameterConfig': 'Konfig', + 'agent.tools.noParamsNeeded': 'Keine Parameter benötigt', + 'agent.tools.pleaseInput': 'Bitte eingeben', + 'agent.tools.inputOneItemPerLine': 'Ein Element pro Zeile eingeben', + 'agent.tools.pleaseInputValidJson': 'Bitte gültiges JSON-Format eingeben', + 'agent.tools.enableFunction': 'Funktion aktivieren', + 'agent.tools.toggleFunction': 'Diese Funktion ein- oder ausschalten', + 'agent.tools.jsonFormatError': 'JSON-Format Fehler', + 'agent.tools.noMcpAddressToCopy': 'Keine MCP-Adresse zum Kopieren', + 'agent.tools.mcpAddressCopied': 'MCP-Adresse in Zwischenablage kopiert', + 'agent.tools.copyFailed': 'Kopieren fehlgeschlagen, bitte erneut versuchen', + 'agent.tools.defaultValue': 'Standardwert', + 'agent.tools.notSelected': 'Nicht ausgewählt', + 'agent.tools.clickToConfigure': 'Klicken zum Konfigurieren', + 'agent.tools.mcpEndpoint': 'MCP-Endpunkt', + 'agent.tools.eachLineOneItem': 'Ein Element pro Zeile eingeben', // Gerätekonfigurationsseite 'deviceConfig.pageTitle': 'Gerätekonfiguration', @@ -497,8 +591,8 @@ export default { 'deviceConfig.audioPlaybackError': 'Audio-Wiedergabe-Fehler', 'deviceConfig.playbackFailed': 'Wiedergabe fehlgeschlagen', - // Voiceprint page - 'voiceprint.audioNotExist': 'Audio existiert nicht', - 'voiceprint.getAudioFailed': 'Audio konnte nicht abgerufen werden', - 'voiceprint.audioPlayFailed': 'Audio-Wiedergabe fehlgeschlagen', + // Voiceprint page + 'voiceprint.audioNotExist': 'Audio existiert nicht', + 'voiceprint.getAudioFailed': 'Audio konnte nicht abgerufen werden', + 'voiceprint.audioPlayFailed': 'Audio-Wiedergabe fehlgeschlagen', } diff --git a/main/manager-mobile/src/i18n/en.ts b/main/manager-mobile/src/i18n/en.ts index 5b0276eed..d23e9ac09 100644 --- a/main/manager-mobile/src/i18n/en.ts +++ b/main/manager-mobile/src/i18n/en.ts @@ -71,6 +71,13 @@ export default { 'home.inputPlaceholder': 'e.g. Customer Service Assistant, Voice Assistant, Knowledge Q&A', 'home.createError': 'The name length must be between 1 and 64 characters', 'home.createNow': 'Create Now', + 'home.deleteConfirmTitle': 'Delete Agent', + 'home.confirmDeleteAgent': 'Deletion cannot be undone. Type the agent name "{agentName}" to confirm.', + 'home.deleteAgentNamePlaceholder': 'Enter agent name', + 'home.deleteAgentNameMismatch': 'The agent name does not match', + 'home.deleteAgentPasteForbidden': 'Please type the agent name manually. Pasting is not allowed.', + 'home.deleteAgentMissingInfo': 'Unable to confirm agent information. Please refresh and try again.', + 'home.deleteAgentSuccess': 'Agent deleted successfully', 'home.justNow': 'Just now', 'home.minutesAgo': 'minutes ago', 'home.hoursAgo': 'hours ago', @@ -123,6 +130,7 @@ export default { 'agent.saving': 'Saving...', 'agent.saveSuccess': 'Save successful', 'agent.saveFail': 'Save failed', + 'agent.ttsOptionsLoadFailed': 'Voice options could not be loaded. The previous voice settings were kept.', 'agent.loadFail': 'Load failed', 'agent.pleaseInputAgentName': 'Please input agent name', 'agent.pleaseInputRoleDescription': 'Please input role description', @@ -139,6 +147,92 @@ export default { 'agent.speedHint': '-100=Slower, 0=Standard, 100=Faster', 'agent.pitchHint': '-100=Lowest, 0=Standard, 100=Highest', + // Agent snapshots + 'agentSnapshot.title': 'Version History', + 'agentSnapshot.empty': 'No versions yet', + 'agentSnapshot.emptyTip': 'Saved configs will appear here', + 'agentSnapshot.version': 'Version', + 'agentSnapshot.createdAt': 'Saved At', + 'agentSnapshot.source': 'Source', + 'agentSnapshot.changedFields': 'Changes', + 'agentSnapshot.view': 'View', + 'agentSnapshot.restore': 'Restore', + 'agentSnapshot.delete': 'Delete', + 'agentSnapshot.loadMore': 'Load More', + 'agentSnapshot.detailTitle': 'Change Details', + 'agentSnapshot.restorePreviewTitle': 'Restore Preview', + 'agentSnapshot.confirmRestore': 'Confirm Restore', + 'agentSnapshot.currentVersion': 'Latest Snapshot', + 'agentSnapshot.beforeChange': 'Before', + 'agentSnapshot.afterChange': 'After', + 'agentSnapshot.beforeRestore': 'Before Restore', + 'agentSnapshot.afterRestore': 'After Restore', + 'agentSnapshot.configValue': 'Config Value', + 'agentSnapshot.emptyValue': 'None', + 'agentSnapshot.secretRedacted': 'Secret hidden', + 'agentSnapshot.redactedValueChanged': 'The value is hidden, but it did change', + 'agentSnapshot.noChangedContent': 'No displayable changes', + 'agentSnapshot.recordedChange': 'Changed when recorded', + 'agentSnapshot.noRestoreNeeded': 'The current configuration already matches this version', + 'agentSnapshot.unsavedChangesTitle': 'Unsaved changes', + 'agentSnapshot.unsavedChangesWarning': 'Continuing will discard the unsaved changes on this page.', + 'agentSnapshot.discardAndRestore': 'Discard and restore', + 'agentSnapshot.restoreConfirm': 'Restore to version #{version}? The current configuration will remain available in history.', + 'agentSnapshot.restoreMemoryWarning': 'Restoring to a no-memory version will clear this agent\'s chat history. Please confirm the risk.', + 'agentSnapshot.restoreChatHistoryDestructiveWarning': 'This restore will permanently delete this agent\'s existing chat history. Chat history is not included in configuration snapshots and cannot be recovered from version history.', + 'agentSnapshot.restoreSuccess': 'Version restored', + 'agentSnapshot.restoreFailed': 'Failed to restore version', + 'agentSnapshot.reloadAfterRestorePending': 'Reloading the restored configuration and tags. Saving is disabled until this completes.', + 'agentSnapshot.reloadAfterRestoreFailed': 'The restored configuration or tags could not be reloaded. Saving remains disabled to prevent stale data from overwriting the restore. Please retry.', + 'agentSnapshot.retryReload': 'Reload', + 'agentSnapshot.mutationBusy': 'The configuration is being saved or reloaded. Wait for it to finish before opening version history or restoring.', + 'agentSnapshot.deleteConfirm': 'Delete version #{version}? This cannot be undone.', + 'agentSnapshot.deleteSuccess': 'Version deleted', + 'agentSnapshot.deleteFailed': 'Failed to delete version', + 'agentSnapshot.fetchFailed': 'Failed to fetch versions', + 'agentSnapshot.detailFailed': 'Failed to fetch version details', + 'agentSnapshot.correctWordCount': '{count} replacement words', + 'agentSnapshot.source.config': 'Config Save', + 'agentSnapshot.source.current': 'Current Config', + 'agentSnapshot.source.restore': 'Restored', + 'agentSnapshot.source.initial': 'Initial Version', + 'agentSnapshot.field.initial': 'Initial Snapshot', + 'agentSnapshot.field.agentCode': 'Agent Code', + 'agentSnapshot.field.agentName': 'Nickname', + 'agentSnapshot.field.asrModelId': 'Speech Recognition', + 'agentSnapshot.field.vadModelId': 'Voice Activity Detection', + 'agentSnapshot.field.llmModelId': 'Main Language Model', + 'agentSnapshot.field.slmModelId': 'Small Language Model', + 'agentSnapshot.field.vllmModelId': 'Vision Model', + 'agentSnapshot.field.ttsModelId': 'Text-to-Speech', + 'agentSnapshot.field.ttsVoiceId': 'Voice', + 'agentSnapshot.field.ttsLanguage': 'Language', + 'agentSnapshot.field.ttsVolume': 'Volume', + 'agentSnapshot.field.ttsRate': 'Speed', + 'agentSnapshot.field.ttsPitch': 'Pitch', + 'agentSnapshot.field.memModelId': 'Memory Mode', + 'agentSnapshot.field.intentModelId': 'Intent Recognition', + 'agentSnapshot.field.chatHistoryConf': 'Chat History Config', + 'agentSnapshot.field.systemPrompt': 'Role Description', + 'agentSnapshot.field.summaryMemory': 'Memory', + 'agentSnapshot.field.langCode': 'Language Code', + 'agentSnapshot.field.language': 'Interaction Language', + 'agentSnapshot.field.sort': 'Sort', + 'agentSnapshot.field.functions': 'Plugins', + 'agentSnapshot.field.contextProviders': 'Context Sources', + 'agentSnapshot.field.correctWordFileIds': 'Replacement Words', + 'agentSnapshot.field.tagNames': 'Agent Tags', + 'agentSnapshot.chatHistoryConf.none': 'Do not record chat history', + 'agentSnapshot.chatHistoryConf.text': 'Report text', + 'agentSnapshot.chatHistoryConf.textVoice': 'Report text and voice', + 'agentSnapshot.model.Memory_nomem': 'No memory', + 'agentSnapshot.model.Memory_mem_local_short': 'Local short memory', + 'agentSnapshot.model.Memory_mem0ai': 'Mem0AI memory', + 'agentSnapshot.model.Memory_mem_report_only': 'Report only', + 'agentSnapshot.model.Intent_nointent': 'No intent recognition', + 'agentSnapshot.model.Intent_intent_llm': 'External LLM intent recognition', + 'agentSnapshot.model.Intent_function_call': 'LLM function calling', + // Context provider dialog related 'contextProviderDialog.title': 'Edit Source', 'contextProviderDialog.noContextApi': 'No Context API', diff --git a/main/manager-mobile/src/i18n/index.ts b/main/manager-mobile/src/i18n/index.ts index 9f527b483..e5abfcd16 100644 --- a/main/manager-mobile/src/i18n/index.ts +++ b/main/manager-mobile/src/i18n/index.ts @@ -1,6 +1,6 @@ +import type { Language } from '@/store/lang' import { ref } from 'vue' import { useLangStore } from '@/store/lang' -import type { Language } from '@/store/lang' // Import translation files import en from './en' @@ -38,7 +38,7 @@ export function t(key: string, params?: Record): string // Direct lookup for flat keys if (langMessages && typeof langMessages === 'object' && key in langMessages) { - let value = langMessages[key] + const value = langMessages[key] if (typeof value === 'string') { // Apply parameter replacements if (params) { diff --git a/main/manager-mobile/src/i18n/pt_BR.ts b/main/manager-mobile/src/i18n/pt_BR.ts index 9ad9904be..e20d1d6b5 100644 --- a/main/manager-mobile/src/i18n/pt_BR.ts +++ b/main/manager-mobile/src/i18n/pt_BR.ts @@ -29,9 +29,9 @@ export default { 'login.requiredCaptcha': 'O código de verificação não pode estar vazio', 'login.requiredMobile': 'Por favor, insira um número de telefone válido', 'login.captchaError': 'Erro no código de verificação gráfico', - 'login.forgotPassword': 'Esqueceu a Senha', - 'login.userAgreement': 'Termos de Uso', - 'login.privacyPolicy': 'Política de Privacidade', + 'login.forgotPassword': 'Esqueceu a Senha', + 'login.userAgreement': 'Termos de Uso', + 'login.privacyPolicy': 'Política de Privacidade', // Register page 'register.pageTitle': 'Cadastro', @@ -71,6 +71,13 @@ export default { 'home.inputPlaceholder': 'ex: Assistente de Atendimento, Assistente de Voz, Perguntas e Respostas', 'home.createError': 'O comprimento do nome deve estar entre 1 e 64 caracteres', 'home.createNow': 'Criar Agora', + 'home.deleteConfirmTitle': 'Excluir Agente', + 'home.confirmDeleteAgent': 'A exclusão não pode ser desfeita. Digite o nome do agente "{agentName}" para confirmar.', + 'home.deleteAgentNamePlaceholder': 'Digite o nome do agente', + 'home.deleteAgentNameMismatch': 'O nome do agente não corresponde', + 'home.deleteAgentPasteForbidden': 'Digite o nome do agente manualmente. Colar não é permitido.', + 'home.deleteAgentMissingInfo': 'Não foi possível confirmar as informações do agente. Atualize a página e tente novamente.', + 'home.deleteAgentSuccess': 'Agente excluído com sucesso', 'home.justNow': 'Agora mesmo', 'home.minutesAgo': 'minutos atrás', 'home.hoursAgo': 'horas atrás', @@ -123,6 +130,7 @@ export default { 'agent.saving': 'Salvando...', 'agent.saveSuccess': 'Salvo com sucesso', 'agent.saveFail': 'Falha ao salvar', + 'agent.ttsOptionsLoadFailed': 'Não foi possível carregar as opções de voz. As configurações anteriores foram mantidas.', 'agent.loadFail': 'Falha ao carregar', 'agent.pleaseInputAgentName': 'Por favor, insira o nome do agente', 'agent.pleaseInputRoleDescription': 'Por favor, insira a descrição do papel', @@ -139,6 +147,92 @@ export default { 'agent.speedHint': '-100=Slower, 0=Standard, 100=Faster', 'agent.pitchHint': '-100=Lowest, 0=Standard, 100=Highest', + // Histórico de versões do agente + 'agentSnapshot.title': 'Histórico de Versões', + 'agentSnapshot.empty': 'Ainda sem versões', + 'agentSnapshot.emptyTip': 'Configurações salvas aparecerão aqui', + 'agentSnapshot.version': 'Versão', + 'agentSnapshot.createdAt': 'Salvo em', + 'agentSnapshot.source': 'Origem', + 'agentSnapshot.changedFields': 'Alterações', + 'agentSnapshot.view': 'Ver', + 'agentSnapshot.restore': 'Restaurar', + 'agentSnapshot.delete': 'Excluir', + 'agentSnapshot.loadMore': 'Carregar Mais', + 'agentSnapshot.detailTitle': 'Detalhes da Alteração', + 'agentSnapshot.restorePreviewTitle': 'Prévia da Restauração', + 'agentSnapshot.confirmRestore': 'Confirmar Restauração', + 'agentSnapshot.currentVersion': 'Snapshot mais recente', + 'agentSnapshot.beforeChange': 'Antes', + 'agentSnapshot.afterChange': 'Depois', + 'agentSnapshot.beforeRestore': 'Antes da Restauração', + 'agentSnapshot.afterRestore': 'Depois da Restauração', + 'agentSnapshot.configValue': 'Valor da Configuração', + 'agentSnapshot.emptyValue': 'Nenhum', + 'agentSnapshot.secretRedacted': 'Segredo oculto', + 'agentSnapshot.redactedValueChanged': 'O valor está oculto, mas foi alterado', + 'agentSnapshot.noChangedContent': 'Nenhuma alteração exibível', + 'agentSnapshot.recordedChange': 'Alterado quando registrado', + 'agentSnapshot.noRestoreNeeded': 'A configuração atual já corresponde a esta versão', + 'agentSnapshot.unsavedChangesTitle': 'Alterações não salvas', + 'agentSnapshot.unsavedChangesWarning': 'Continuar descartará as alterações não salvas desta página.', + 'agentSnapshot.discardAndRestore': 'Descartar e restaurar', + 'agentSnapshot.restoreConfirm': 'Restaurar para a versão #{version}? A configuração atual continuará disponível no histórico.', + 'agentSnapshot.restoreMemoryWarning': 'Restaurar para uma versão sem memória limpará o histórico de chat deste agente. Confirme o risco.', + 'agentSnapshot.restoreChatHistoryDestructiveWarning': 'Esta restauração excluirá permanentemente o histórico de chat existente deste agente. O histórico de chat não faz parte dos snapshots de configuração e não pode ser recuperado pelo histórico de versões.', + 'agentSnapshot.restoreSuccess': 'Versão restaurada', + 'agentSnapshot.restoreFailed': 'Falha ao restaurar versão', + 'agentSnapshot.reloadAfterRestorePending': 'Recarregando a configuração e as tags restauradas. Não é possível salvar até a conclusão.', + 'agentSnapshot.reloadAfterRestoreFailed': 'Não foi possível recarregar a configuração ou as tags restauradas. O salvamento permanece desativado para impedir que dados antigos sobrescrevam a restauração. Tente novamente.', + 'agentSnapshot.retryReload': 'Recarregar', + 'agentSnapshot.mutationBusy': 'A configuração está sendo salva ou recarregada. Aguarde a conclusão antes de abrir o histórico de versões ou restaurar.', + 'agentSnapshot.deleteConfirm': 'Excluir versão #{version}? Esta ação não pode ser desfeita.', + 'agentSnapshot.deleteSuccess': 'Versão excluída', + 'agentSnapshot.deleteFailed': 'Falha ao excluir versão', + 'agentSnapshot.fetchFailed': 'Falha ao buscar versões', + 'agentSnapshot.detailFailed': 'Falha ao buscar detalhes da versão', + 'agentSnapshot.correctWordCount': '{count} palavras de substituição', + 'agentSnapshot.source.config': 'Configuração Salva', + 'agentSnapshot.source.current': 'Configuração Atual', + 'agentSnapshot.source.restore': 'Restaurado', + 'agentSnapshot.source.initial': 'Versão Inicial', + 'agentSnapshot.field.initial': 'Snapshot Inicial', + 'agentSnapshot.field.agentCode': 'Código do Agente', + 'agentSnapshot.field.agentName': 'Apelido', + 'agentSnapshot.field.asrModelId': 'Reconhecimento de Fala', + 'agentSnapshot.field.vadModelId': 'Detecção de Voz', + 'agentSnapshot.field.llmModelId': 'Modelo Principal', + 'agentSnapshot.field.slmModelId': 'Modelo Pequeno', + 'agentSnapshot.field.vllmModelId': 'Modelo Visual', + 'agentSnapshot.field.ttsModelId': 'Texto para Fala', + 'agentSnapshot.field.ttsVoiceId': 'Voz', + 'agentSnapshot.field.ttsLanguage': 'Idioma', + 'agentSnapshot.field.ttsVolume': 'Volume', + 'agentSnapshot.field.ttsRate': 'Velocidade', + 'agentSnapshot.field.ttsPitch': 'Tonalidade', + 'agentSnapshot.field.memModelId': 'Modo de Memória', + 'agentSnapshot.field.intentModelId': 'Reconhecimento de Intenção', + 'agentSnapshot.field.chatHistoryConf': 'Configuração do Histórico', + 'agentSnapshot.field.systemPrompt': 'Descrição do Papel', + 'agentSnapshot.field.summaryMemory': 'Memória', + 'agentSnapshot.field.langCode': 'Código do Idioma', + 'agentSnapshot.field.language': 'Idioma de Interação', + 'agentSnapshot.field.sort': 'Ordenação', + 'agentSnapshot.field.functions': 'Plugins', + 'agentSnapshot.field.contextProviders': 'Fontes de Contexto', + 'agentSnapshot.field.correctWordFileIds': 'Palavras de Substituição', + 'agentSnapshot.field.tagNames': 'Tags do Agente', + 'agentSnapshot.chatHistoryConf.none': 'Não registrar histórico de chat', + 'agentSnapshot.chatHistoryConf.text': 'Reportar texto', + 'agentSnapshot.chatHistoryConf.textVoice': 'Reportar texto e voz', + 'agentSnapshot.model.Memory_nomem': 'Sem memória', + 'agentSnapshot.model.Memory_mem_local_short': 'Memória curta local', + 'agentSnapshot.model.Memory_mem0ai': 'Memória Mem0AI', + 'agentSnapshot.model.Memory_mem_report_only': 'Apenas reportar', + 'agentSnapshot.model.Intent_nointent': 'Sem reconhecimento de intenção', + 'agentSnapshot.model.Intent_intent_llm': 'Reconhecimento por LLM externo', + 'agentSnapshot.model.Intent_function_call': 'Chamada de função por LLM', + // Diálogo de provedor de contexto 'contextProviderDialog.title': 'Editar Fonte', 'contextProviderDialog.noContextApi': 'Sem API de Contexto', diff --git a/main/manager-mobile/src/i18n/vi.ts b/main/manager-mobile/src/i18n/vi.ts index c8ff79e6a..b12328889 100644 --- a/main/manager-mobile/src/i18n/vi.ts +++ b/main/manager-mobile/src/i18n/vi.ts @@ -1,157 +1,251 @@ // Gói ngôn ngữ tiếng Việt export default { - // TabBar - 'tabBar.home': 'Trang chủ', - 'tabBar.deviceConfig': 'Cấu hình mạng', - 'tabBar.settings': 'Hệ thống', - // Tiêu đề trang cài đặt - 'settings.title': 'Cài đặt', - // Trang đăng nhập - 'login.pageTitle': 'Đăng nhập', - 'login.navigationTitle': 'Đăng nhập', - 'login.fetchConfigError': 'Không thể tải cấu hình:', - 'login.selectLanguage': 'Chọn ngôn ngữ', - 'login.selectLanguageTip': 'Vi', - 'login.welcomeBack': 'Chào mừng trở lại', - 'login.pleaseLogin': 'Vui lòng đăng nhập vào tài khoản của bạn', - 'login.enterUsername': 'Vui lòng nhập tên đăng nhập', - 'login.enterPassword': 'Vui lòng nhập mật khẩu', - 'login.enterCaptcha': 'Vui lòng nhập mã xác minh', - 'login.loginButton': 'Đăng nhập', - 'login.loggingIn': 'Đang đăng nhập...', - 'login.noAccount': 'Đăng ký', - 'login.enterPhone': 'Vui lòng nhập số điện thoại', - 'login.selectCountry': 'Chọn quốc gia/vùng', - 'login.confirm': 'Xác nhận', - 'login.serverSetting': 'Cài đặt máy chủ', - 'login.requiredUsername': 'Tên đăng nhập không thể để trống', - 'login.requiredPassword': 'Mật khẩu không thể để trống', - 'login.requiredCaptcha': 'Mã xác minh không thể để trống', - 'login.requiredMobile': 'Vui lòng nhập số điện thoại hợp lệ', - 'login.captchaError': 'Lỗi mã xác minh đồ họa', - 'login.forgotPassword': 'Quên mật khẩu', - 'login.userAgreement': 'Thỏa thuận người dùng', - 'login.privacyPolicy': 'Chính sách bảo mật', + // TabBar + 'tabBar.home': 'Trang chủ', + 'tabBar.deviceConfig': 'Cấu hình mạng', + 'tabBar.settings': 'Hệ thống', + // Tiêu đề trang cài đặt + 'settings.title': 'Cài đặt', + // Trang đăng nhập + 'login.pageTitle': 'Đăng nhập', + 'login.navigationTitle': 'Đăng nhập', + 'login.fetchConfigError': 'Không thể tải cấu hình:', + 'login.selectLanguage': 'Chọn ngôn ngữ', + 'login.selectLanguageTip': 'Vi', + 'login.welcomeBack': 'Chào mừng trở lại', + 'login.pleaseLogin': 'Vui lòng đăng nhập vào tài khoản của bạn', + 'login.enterUsername': 'Vui lòng nhập tên đăng nhập', + 'login.enterPassword': 'Vui lòng nhập mật khẩu', + 'login.enterCaptcha': 'Vui lòng nhập mã xác minh', + 'login.loginButton': 'Đăng nhập', + 'login.loggingIn': 'Đang đăng nhập...', + 'login.noAccount': 'Đăng ký', + 'login.enterPhone': 'Vui lòng nhập số điện thoại', + 'login.selectCountry': 'Chọn quốc gia/vùng', + 'login.confirm': 'Xác nhận', + 'login.serverSetting': 'Cài đặt máy chủ', + 'login.requiredUsername': 'Tên đăng nhập không thể để trống', + 'login.requiredPassword': 'Mật khẩu không thể để trống', + 'login.requiredCaptcha': 'Mã xác minh không thể để trống', + 'login.requiredMobile': 'Vui lòng nhập số điện thoại hợp lệ', + 'login.captchaError': 'Lỗi mã xác minh đồ họa', + 'login.forgotPassword': 'Quên mật khẩu', + 'login.userAgreement': 'Thỏa thuận người dùng', + 'login.privacyPolicy': 'Chính sách bảo mật', - // Trang đăng ký - 'register.pageTitle': 'Đăng ký', - 'register.createAccount': 'Tạo tài khoản', - 'register.enterUsername': 'Vui lòng nhập tên đăng nhập', - 'register.enterPassword': 'Vui lòng nhập mật khẩu', - 'register.confirmPassword': 'Vui lòng xác nhận mật khẩu', - 'register.enterPhone': 'Vui lòng nhập số điện thoại', - 'register.enterCode': 'Vui lòng nhập mã xác minh', - 'register.getCode': 'Lấy mã', - 'register.agreeTerms': 'Tôi đã đọc và đồng ý với', - 'register.terms': 'Thỏa thuận người dùng', - 'register.privacy': 'Chính sách bảo mật', - 'register.registerButton': 'Đăng ký', - 'register.registering': 'Đang đăng ký...', - 'register.haveAccount': 'Đã có tài khoản?', - 'register.loginNow': 'Đăng nhập ngay', - 'register.selectCountry': 'Chọn quốc gia/vùng', - 'register.confirm': 'Xác nhận', - 'register.captchaSendSuccess': 'Đã gửi mã xác minh thành công', + // Trang đăng ký + 'register.pageTitle': 'Đăng ký', + 'register.createAccount': 'Tạo tài khoản', + 'register.enterUsername': 'Vui lòng nhập tên đăng nhập', + 'register.enterPassword': 'Vui lòng nhập mật khẩu', + 'register.confirmPassword': 'Vui lòng xác nhận mật khẩu', + 'register.enterPhone': 'Vui lòng nhập số điện thoại', + 'register.enterCode': 'Vui lòng nhập mã xác minh', + 'register.getCode': 'Lấy mã', + 'register.agreeTerms': 'Tôi đã đọc và đồng ý với', + 'register.terms': 'Thỏa thuận người dùng', + 'register.privacy': 'Chính sách bảo mật', + 'register.registerButton': 'Đăng ký', + 'register.registering': 'Đang đăng ký...', + 'register.haveAccount': 'Đã có tài khoản?', + 'register.loginNow': 'Đăng nhập ngay', + 'register.selectCountry': 'Chọn quốc gia/vùng', + 'register.confirm': 'Xác nhận', + 'register.captchaSendSuccess': 'Đã gửi mã xác minh thành công', - // Trang chủ - 'home.pageTitle': 'Trang chủ', - 'home.createAgent': 'Tạo đại lý', - 'home.agentName': 'Đại lý', - 'home.modelInfo': 'Thông tin mô hình', - 'home.lastActive': 'Hoạt động lần cuối', - 'home.greeting': 'Xin chào Jarvis', - 'home.subtitle': 'Hãy cùng có', - 'home.wonderfulDay': 'một ngày tuyệt vời!', - 'home.emptyState': 'Không có đại lý nào', - 'home.deviceManagement': 'Quản lý thiết bị', - 'home.lastConversation': 'Cuộc trò chuyện cuối:', - 'home.delete': 'Xóa', - 'home.createFirstAgent': 'Nhấp vào nút + ở góc dưới bên phải để tạo đại lý đầu tiên của bạn', - 'home.dialogTitle': 'Tạo đại lý', - 'home.inputPlaceholder': 'ví dụ: Trợ lý chăm sóc khách hàng, Trợ lý giọng nói, Hỏi đáp kiến thức', - 'home.createError': 'Độ dài tên phải từ 1 đến 64 ký tự', - 'home.createNow': 'Tạo ngay', - 'home.justNow': 'Vừa xong', - 'home.minutesAgo': 'phút trước', - 'home.hoursAgo': 'giờ trước', - 'home.daysAgo': 'ngày trước', - 'home.languageModel': 'LLM', - 'home.voiceModel': 'TTS', + // Trang chủ + 'home.pageTitle': 'Trang chủ', + 'home.createAgent': 'Tạo đại lý', + 'home.agentName': 'Đại lý', + 'home.modelInfo': 'Thông tin mô hình', + 'home.lastActive': 'Hoạt động lần cuối', + 'home.greeting': 'Xin chào Jarvis', + 'home.subtitle': 'Hãy cùng có', + 'home.wonderfulDay': 'một ngày tuyệt vời!', + 'home.emptyState': 'Không có đại lý nào', + 'home.deviceManagement': 'Quản lý thiết bị', + 'home.lastConversation': 'Cuộc trò chuyện cuối:', + 'home.delete': 'Xóa', + 'home.createFirstAgent': 'Nhấp vào nút + ở góc dưới bên phải để tạo đại lý đầu tiên của bạn', + 'home.dialogTitle': 'Tạo đại lý', + 'home.inputPlaceholder': 'ví dụ: Trợ lý chăm sóc khách hàng, Trợ lý giọng nói, Hỏi đáp kiến thức', + 'home.createError': 'Độ dài tên phải từ 1 đến 64 ký tự', + 'home.createNow': 'Tạo ngay', + 'home.deleteConfirmTitle': 'Xóa đại lý', + 'home.confirmDeleteAgent': 'Không thể hoàn tác sau khi xóa. Nhập tên đại lý "{agentName}" để xác nhận.', + 'home.deleteAgentNamePlaceholder': 'Nhập tên đại lý', + 'home.deleteAgentNameMismatch': 'Tên đại lý không khớp', + 'home.deleteAgentPasteForbidden': 'Vui lòng nhập thủ công tên đại lý. Không được dán.', + 'home.deleteAgentMissingInfo': 'Không thể xác nhận thông tin đại lý. Vui lòng tải lại rồi thử lại.', + 'home.deleteAgentSuccess': 'Đã xóa đại lý thành công', + 'home.justNow': 'Vừa xong', + 'home.minutesAgo': 'phút trước', + 'home.hoursAgo': 'giờ trước', + 'home.daysAgo': 'ngày trước', + 'home.languageModel': 'LLM', + 'home.voiceModel': 'TTS', - // Trang đại lý - 'agent.pageTitle': 'Đại lý', - 'agent.roleConfig': 'Cấu hình vai trò', - 'agent.deviceManagement': 'Quản lý thiết bị', - 'agent.chatHistory': 'Lịch sử trò chuyện', - 'agent.voiceprintManagement': 'Quản lý dấu giọng nói', - 'agent.editTitle': 'Chỉnh sửa đại lý', - 'agent.toolsTitle': 'Chỉnh sửa tính năng', - 'agent.voiceActivityDetection': 'Phát hiện hoạt động giọng nói', - 'agent.speechRecognition': 'Nhận dạng giọng nói', - 'agent.largeLanguageModel': 'Mô hình ngôn ngữ lớn', - 'agent.save': 'Lưu', - 'agent.cancel': 'Hủy', - // Trang chỉnh sửa đại lý - 'agent.basicInfo': 'Thông tin cơ bản', - 'agent.agentName': 'Tên đại lý', - 'agent.inputAgentName': 'Vui lòng nhập tên đại lý', - 'agent.roleMode': 'Chế độ vai trò', - 'agent.agentTag': 'Nhãn cơ thể thông minh', - 'agent.addAgentTag': 'Thêm thẻ', - 'agent.inputAgentTag': 'Vui lòng nhập thẻ cơ thể thông minh', - 'agent.contextProvider': 'Bối cảnh', - 'agent.contextProviderSuccess': 'Đã thêm thành công {count} nguồn.', - 'agent.contextProviderDocLink': 'Cách triển khai nguồn ngữ cảnh', - 'agent.editContextProvider': 'Chỉnh sửa nguồn', - 'agent.roleDescription': 'Mô tả vai trò', - 'agent.inputRoleDescription': 'Vui lòng nhập mô tả vai trò', - 'agent.modelConfig': 'Cấu hình mô hình', - 'agent.vad': 'Phát hiện hoạt động giọng nói', - 'agent.asr': 'Nhận dạng giọng nói', - 'agent.llm': 'Mô hình ngôn ngữ chính', - 'agent.slm': 'Mô hình tham số nhỏ', - 'agent.vllm': 'Mô hình ngôn ngữ thị giác', - 'agent.intent': 'Nhận dạng ý định', - 'agent.memory': 'Bộ nhớ', - 'agent.voiceSettings': 'Cài đặt giọng nói', - 'agent.tts': 'Văn bản thành giọng nói', - 'agent.voiceprint': 'Giọng nói đại lý', - 'agent.plugins': 'Plugin', - 'agent.editFunctions': 'Chỉnh sửa tính năng', - 'agent.historyMemory': 'Bộ nhớ lịch sử', - 'agent.memoryContent': 'Nội dung bộ nhớ', - 'agent.saving': 'Đang lưu...', - 'agent.saveSuccess': 'Lưu thành công', - 'agent.saveFail': 'Lưu thất bại', - 'agent.loadFail': 'Tải thất bại', - 'agent.pleaseInputAgentName': 'Vui lòng nhập tên đại lý', - 'agent.pleaseInputRoleDescription': 'Vui lòng nhập mô tả vai trò', - 'agent.pleaseSelect': 'Vui lòng chọn', - 'agent.reportText': 'Gửi văn bản', - 'agent.reportTextVoice': 'Gửi văn bản+giọng nói', - 'agent.reportMode': 'Chế độ gửi', - 'agent.language': 'Ngôn ngữ', - 'agent.languageConfig': 'Giọng nói', - 'agent.ttsVolume': 'Âm lượng', - 'agent.ttsRate': 'Tốc độ', - 'agent.ttsPitch': 'Tone', - 'agent.volumeHint': '-100=Minimum, 0=Standard, 100=Maximum', - 'agent.speedHint': '-100=Slowest, 0=Standard, 100=Fastest', - 'agent.pitchHint': '-100=Lowest, 0=Standard, 100=Highest', + // Trang đại lý + 'agent.pageTitle': 'Đại lý', + 'agent.roleConfig': 'Cấu hình vai trò', + 'agent.deviceManagement': 'Quản lý thiết bị', + 'agent.chatHistory': 'Lịch sử trò chuyện', + 'agent.voiceprintManagement': 'Quản lý dấu giọng nói', + 'agent.editTitle': 'Chỉnh sửa đại lý', + 'agent.toolsTitle': 'Chỉnh sửa tính năng', + 'agent.voiceActivityDetection': 'Phát hiện hoạt động giọng nói', + 'agent.speechRecognition': 'Nhận dạng giọng nói', + 'agent.largeLanguageModel': 'Mô hình ngôn ngữ lớn', + 'agent.save': 'Lưu', + 'agent.cancel': 'Hủy', + // Trang chỉnh sửa đại lý + 'agent.basicInfo': 'Thông tin cơ bản', + 'agent.agentName': 'Tên đại lý', + 'agent.inputAgentName': 'Vui lòng nhập tên đại lý', + 'agent.roleMode': 'Chế độ vai trò', + 'agent.agentTag': 'Nhãn cơ thể thông minh', + 'agent.addAgentTag': 'Thêm thẻ', + 'agent.inputAgentTag': 'Vui lòng nhập thẻ cơ thể thông minh', + 'agent.contextProvider': 'Bối cảnh', + 'agent.contextProviderSuccess': 'Đã thêm thành công {count} nguồn.', + 'agent.contextProviderDocLink': 'Cách triển khai nguồn ngữ cảnh', + 'agent.editContextProvider': 'Chỉnh sửa nguồn', + 'agent.roleDescription': 'Mô tả vai trò', + 'agent.inputRoleDescription': 'Vui lòng nhập mô tả vai trò', + 'agent.modelConfig': 'Cấu hình mô hình', + 'agent.vad': 'Phát hiện hoạt động giọng nói', + 'agent.asr': 'Nhận dạng giọng nói', + 'agent.llm': 'Mô hình ngôn ngữ chính', + 'agent.slm': 'Mô hình tham số nhỏ', + 'agent.vllm': 'Mô hình ngôn ngữ thị giác', + 'agent.intent': 'Nhận dạng ý định', + 'agent.memory': 'Bộ nhớ', + 'agent.voiceSettings': 'Cài đặt giọng nói', + 'agent.tts': 'Văn bản thành giọng nói', + 'agent.voiceprint': 'Giọng nói đại lý', + 'agent.plugins': 'Plugin', + 'agent.editFunctions': 'Chỉnh sửa tính năng', + 'agent.historyMemory': 'Bộ nhớ lịch sử', + 'agent.memoryContent': 'Nội dung bộ nhớ', + 'agent.saving': 'Đang lưu...', + 'agent.saveSuccess': 'Lưu thành công', + 'agent.saveFail': 'Lưu thất bại', + 'agent.ttsOptionsLoadFailed': 'Không thể tải tùy chọn giọng nói. Cấu hình giọng nói trước đó đã được giữ lại.', + 'agent.loadFail': 'Tải thất bại', + 'agent.pleaseInputAgentName': 'Vui lòng nhập tên đại lý', + 'agent.pleaseInputRoleDescription': 'Vui lòng nhập mô tả vai trò', + 'agent.pleaseSelect': 'Vui lòng chọn', + 'agent.reportText': 'Gửi văn bản', + 'agent.reportTextVoice': 'Gửi văn bản+giọng nói', + 'agent.reportMode': 'Chế độ gửi', + 'agent.language': 'Ngôn ngữ', + 'agent.languageConfig': 'Giọng nói', + 'agent.ttsVolume': 'Âm lượng', + 'agent.ttsRate': 'Tốc độ', + 'agent.ttsPitch': 'Tone', + 'agent.volumeHint': '-100=Minimum, 0=Standard, 100=Maximum', + 'agent.speedHint': '-100=Slowest, 0=Standard, 100=Fastest', + 'agent.pitchHint': '-100=Lowest, 0=Standard, 100=Highest', - // Context provider dialog related - 'contextProviderDialog.title': 'Chỉnh sửa nguồn', - 'contextProviderDialog.noContextApi': 'Không có API ngữ cảnh', - 'contextProviderDialog.add': 'Thêm', - 'contextProviderDialog.apiUrl': 'Địa chỉ API', - 'contextProviderDialog.apiUrlPlaceholder': 'http://api.example.com/data', - 'contextProviderDialog.requestHeaders': 'Header yêu cầu', - 'contextProviderDialog.headerKeyPlaceholder': 'Khóa', - 'contextProviderDialog.headerValuePlaceholder': 'Giá trị', - 'contextProviderDialog.noHeaders': 'Không có Headers', - 'contextProviderDialog.addHeader': 'Thêm Header', - 'contextProviderDialog.cancel': 'Hủy bỏ', - 'contextProviderDialog.confirm': 'Xác nhận', + // Lịch sử phiên bản đại lý + 'agentSnapshot.title': 'Lịch sử phiên bản', + 'agentSnapshot.empty': 'Chưa có phiên bản', + 'agentSnapshot.emptyTip': 'Cấu hình đã lưu sẽ xuất hiện ở đây', + 'agentSnapshot.version': 'Phiên bản', + 'agentSnapshot.createdAt': 'Thời gian lưu', + 'agentSnapshot.source': 'Nguồn', + 'agentSnapshot.changedFields': 'Thay đổi', + 'agentSnapshot.view': 'Xem', + 'agentSnapshot.restore': 'Khôi phục', + 'agentSnapshot.delete': 'Xóa', + 'agentSnapshot.loadMore': 'Tải thêm', + 'agentSnapshot.detailTitle': 'Chi tiết thay đổi', + 'agentSnapshot.restorePreviewTitle': 'Xem trước khôi phục', + 'agentSnapshot.confirmRestore': 'Xác nhận khôi phục', + 'agentSnapshot.currentVersion': 'Ảnh chụp mới nhất', + 'agentSnapshot.beforeChange': 'Trước', + 'agentSnapshot.afterChange': 'Sau', + 'agentSnapshot.beforeRestore': 'Trước khôi phục', + 'agentSnapshot.afterRestore': 'Sau khôi phục', + 'agentSnapshot.configValue': 'Giá trị cấu hình', + 'agentSnapshot.emptyValue': 'Không có', + 'agentSnapshot.secretRedacted': 'Đã ẩn khóa bí mật', + 'agentSnapshot.redactedValueChanged': 'Giá trị đã được ẩn nhưng thực sự đã thay đổi', + 'agentSnapshot.noChangedContent': 'Không có thay đổi để hiển thị', + 'agentSnapshot.recordedChange': 'Đã thay đổi khi ghi nhận', + 'agentSnapshot.noRestoreNeeded': 'Cấu hình hiện tại đã khớp với phiên bản này', + 'agentSnapshot.unsavedChangesTitle': 'Có thay đổi chưa lưu', + 'agentSnapshot.unsavedChangesWarning': 'Tiếp tục sẽ hủy các thay đổi chưa lưu trên trang này.', + 'agentSnapshot.discardAndRestore': 'Hủy thay đổi và khôi phục', + 'agentSnapshot.restoreConfirm': 'Khôi phục về phiên bản #{version}? Cấu hình hiện tại sẽ vẫn có trong lịch sử.', + 'agentSnapshot.restoreMemoryWarning': 'Khôi phục về phiên bản không có bộ nhớ sẽ xóa lịch sử trò chuyện của đại lý này. Vui lòng xác nhận rủi ro.', + 'agentSnapshot.restoreChatHistoryDestructiveWarning': 'Thao tác khôi phục này sẽ xóa vĩnh viễn lịch sử trò chuyện hiện có của tác nhân. Lịch sử trò chuyện không nằm trong bản chụp cấu hình và không thể khôi phục từ lịch sử phiên bản.', + 'agentSnapshot.restoreSuccess': 'Đã khôi phục phiên bản', + 'agentSnapshot.restoreFailed': 'Khôi phục phiên bản thất bại', + 'agentSnapshot.reloadAfterRestorePending': 'Đang tải lại cấu hình và thẻ đã khôi phục. Không thể lưu cho đến khi hoàn tất.', + 'agentSnapshot.reloadAfterRestoreFailed': 'Không thể tải lại cấu hình hoặc thẻ đã khôi phục. Chức năng lưu vẫn bị tắt để tránh dữ liệu cũ ghi đè kết quả khôi phục. Vui lòng thử lại.', + 'agentSnapshot.retryReload': 'Tải lại', + 'agentSnapshot.mutationBusy': 'Cấu hình đang được lưu hoặc tải lại. Hãy đợi hoàn tất trước khi mở lịch sử phiên bản hoặc khôi phục.', + 'agentSnapshot.deleteConfirm': 'Xóa phiên bản #{version}? Không thể hoàn tác thao tác này.', + 'agentSnapshot.deleteSuccess': 'Đã xóa phiên bản', + 'agentSnapshot.deleteFailed': 'Xóa phiên bản thất bại', + 'agentSnapshot.fetchFailed': 'Lấy lịch sử phiên bản thất bại', + 'agentSnapshot.detailFailed': 'Lấy chi tiết phiên bản thất bại', + 'agentSnapshot.correctWordCount': '{count} từ thay thế', + 'agentSnapshot.source.config': 'Lưu cấu hình', + 'agentSnapshot.source.current': 'Cấu hình hiện tại', + 'agentSnapshot.source.restore': 'Đã khôi phục', + 'agentSnapshot.source.initial': 'Phiên bản khởi tạo', + 'agentSnapshot.field.initial': 'Ảnh chụp ban đầu', + 'agentSnapshot.field.agentCode': 'Mã đại lý', + 'agentSnapshot.field.agentName': 'Biệt danh', + 'agentSnapshot.field.asrModelId': 'Nhận dạng giọng nói', + 'agentSnapshot.field.vadModelId': 'Phát hiện hoạt động giọng nói', + 'agentSnapshot.field.llmModelId': 'Mô hình ngôn ngữ chính', + 'agentSnapshot.field.slmModelId': 'Mô hình ngôn ngữ nhỏ', + 'agentSnapshot.field.vllmModelId': 'Mô hình thị giác', + 'agentSnapshot.field.ttsModelId': 'Tổng hợp giọng nói', + 'agentSnapshot.field.ttsVoiceId': 'Giọng', + 'agentSnapshot.field.ttsLanguage': 'Ngôn ngữ', + 'agentSnapshot.field.ttsVolume': 'Âm lượng', + 'agentSnapshot.field.ttsRate': 'Tốc độ', + 'agentSnapshot.field.ttsPitch': 'Tone', + 'agentSnapshot.field.memModelId': 'Chế độ bộ nhớ', + 'agentSnapshot.field.intentModelId': 'Nhận dạng ý định', + 'agentSnapshot.field.chatHistoryConf': 'Cấu hình lịch sử chat', + 'agentSnapshot.field.systemPrompt': 'Mô tả vai trò', + 'agentSnapshot.field.summaryMemory': 'Bộ nhớ', + 'agentSnapshot.field.langCode': 'Mã ngôn ngữ', + 'agentSnapshot.field.language': 'Ngôn ngữ tương tác', + 'agentSnapshot.field.sort': 'Sắp xếp', + 'agentSnapshot.field.functions': 'Plugin', + 'agentSnapshot.field.contextProviders': 'Nguồn ngữ cảnh', + 'agentSnapshot.field.correctWordFileIds': 'Từ thay thế', + 'agentSnapshot.field.tagNames': 'Nhãn đại lý', + 'agentSnapshot.chatHistoryConf.none': 'Không ghi lịch sử chat', + 'agentSnapshot.chatHistoryConf.text': 'Gửi văn bản', + 'agentSnapshot.chatHistoryConf.textVoice': 'Gửi văn bản và giọng nói', + 'agentSnapshot.model.Memory_nomem': 'Không có bộ nhớ', + 'agentSnapshot.model.Memory_mem_local_short': 'Bộ nhớ ngắn hạn cục bộ', + 'agentSnapshot.model.Memory_mem0ai': 'Bộ nhớ Mem0AI', + 'agentSnapshot.model.Memory_mem_report_only': 'Chỉ gửi báo cáo', + 'agentSnapshot.model.Intent_nointent': 'Không nhận dạng ý định', + 'agentSnapshot.model.Intent_intent_llm': 'Nhận dạng ý định LLM ngoài', + 'agentSnapshot.model.Intent_function_call': 'Gọi hàm bằng LLM', + + // Context provider dialog related + 'contextProviderDialog.title': 'Chỉnh sửa nguồn', + 'contextProviderDialog.noContextApi': 'Không có API ngữ cảnh', + 'contextProviderDialog.add': 'Thêm', + 'contextProviderDialog.apiUrl': 'Địa chỉ API', + 'contextProviderDialog.apiUrlPlaceholder': 'http://api.example.com/data', + 'contextProviderDialog.requestHeaders': 'Header yêu cầu', + 'contextProviderDialog.headerKeyPlaceholder': 'Khóa', + 'contextProviderDialog.headerValuePlaceholder': 'Giá trị', + 'contextProviderDialog.noHeaders': 'Không có Headers', + 'contextProviderDialog.addHeader': 'Thêm Header', + 'contextProviderDialog.cancel': 'Hủy bỏ', + 'contextProviderDialog.confirm': 'Xác nhận', // Manual add device dialog related 'manualAddDeviceDialog.title': 'Thêm thiết bị thủ công', @@ -172,222 +266,222 @@ export default { 'manualAddDeviceDialog.addFailed': 'Thêm thất bại', 'manualAddDeviceDialog.bindWithCode': 'Liên kết bằng mã xác minh 6 chữ số', - // Trang lịch sử trò chuyện - 'chatHistory.getChatSessions': 'Lấy danh sách phiên trò chuyện', - 'chatHistory.noSelectedAgent': 'Chưa chọn đại lý', - 'chatHistory.getChatSessionsFailed': 'Không thể lấy danh sách phiên trò chuyện:', - 'chatHistory.unknownTime': 'Thời gian không xác định', - 'chatHistory.justNow': 'Vừa xong', - 'chatHistory.minutesAgo': '{minutes} phút trước', - 'chatHistory.hoursAgo': '{hours} giờ trước', - 'chatHistory.daysAgo': '{days} ngày trước', - 'chatHistory.conversationRecord': 'Bản ghi trò chuyện', - 'chatHistory.totalChats': 'Tổng cộng {count} cuộc trò chuyện', - 'chatHistory.loading': 'Đang tải...', - 'chatHistory.noMoreData': 'Không còn dữ liệu', - 'chatHistory.noChatRecords': 'Không có bản ghi trò chuyện', - 'chatHistory.chatRecordsDescription': 'Bản ghi trò chuyện với đại lý sẽ hiển thị ở đây', - // Trang chi tiết lịch sử trò chuyện - 'chatHistory.pageTitle': 'Chi tiết trò chuyện', - 'chatHistory.assistantName': 'Trợ lý thông minh', - 'chatHistory.userName': 'Người dùng', - 'chatHistory.aiAssistantName': 'Trợ lý AI', - 'chatHistory.loadFailed': 'Không thể tải lịch sử trò chuyện', - 'chatHistory.parameterError': 'Lỗi tham số trang', - 'chatHistory.invalidAudioId': 'ID âm thanh không hợp lệ', - 'chatHistory.audioPlayFailed': 'Phát âm thanh thất bại', - 'chatHistory.playAudioFailed': 'Không thể phát âm thanh', + // Trang lịch sử trò chuyện + 'chatHistory.getChatSessions': 'Lấy danh sách phiên trò chuyện', + 'chatHistory.noSelectedAgent': 'Chưa chọn đại lý', + 'chatHistory.getChatSessionsFailed': 'Không thể lấy danh sách phiên trò chuyện:', + 'chatHistory.unknownTime': 'Thời gian không xác định', + 'chatHistory.justNow': 'Vừa xong', + 'chatHistory.minutesAgo': '{minutes} phút trước', + 'chatHistory.hoursAgo': '{hours} giờ trước', + 'chatHistory.daysAgo': '{days} ngày trước', + 'chatHistory.conversationRecord': 'Bản ghi trò chuyện', + 'chatHistory.totalChats': 'Tổng cộng {count} cuộc trò chuyện', + 'chatHistory.loading': 'Đang tải...', + 'chatHistory.noMoreData': 'Không còn dữ liệu', + 'chatHistory.noChatRecords': 'Không có bản ghi trò chuyện', + 'chatHistory.chatRecordsDescription': 'Bản ghi trò chuyện với đại lý sẽ hiển thị ở đây', + // Trang chi tiết lịch sử trò chuyện + 'chatHistory.pageTitle': 'Chi tiết trò chuyện', + 'chatHistory.assistantName': 'Trợ lý thông minh', + 'chatHistory.userName': 'Người dùng', + 'chatHistory.aiAssistantName': 'Trợ lý AI', + 'chatHistory.loadFailed': 'Không thể tải lịch sử trò chuyện', + 'chatHistory.parameterError': 'Lỗi tham số trang', + 'chatHistory.invalidAudioId': 'ID âm thanh không hợp lệ', + 'chatHistory.audioPlayFailed': 'Phát âm thanh thất bại', + 'chatHistory.playAudioFailed': 'Không thể phát âm thanh', - // Trang quản lý thiết bị - 'device.pageTitle': 'Quản lý thiết bị', - 'device.noDevices': 'Không có thiết bị nào', - 'device.macAddress': 'Địa chỉ MAC', - 'device.firmwareVersion': 'Phiên bản firmware', - 'device.lastConnected': 'Cuộc trò chuyện cuối', - 'device.otaUpdate': 'Cập nhật OTA', - 'device.unbind': 'Hủy liên kết', - 'device.confirmUnbind': 'Xác nhận', - 'device.bindDevice': 'Liên kết thiết bị mới', - 'device.deviceType': 'Loại thiết bị', - 'device.loading': 'Đang tải...', - 'device.neverConnected': 'Chưa kết nối', - 'device.justNow': 'Vừa xong', - 'device.minutesAgo': '{minutes} phút trước', - 'device.hoursAgo': '{hours} giờ trước', - 'device.daysAgo': '{days} ngày trước', - 'device.otaAutoUpdateEnabled': 'Đã bật cập nhật OTA tự động', - 'device.otaAutoUpdateDisabled': 'Đã tắt cập nhật OTA tự động', - 'device.operationFailed': 'Thao tác thất bại, vui lòng thử lại', - 'device.deviceUnbound': 'Đã hủy liên kết thiết bị', - 'device.unbindFailed': 'Hủy liên kết thất bại, vui lòng thử lại', - 'device.unbindDevice': 'Hủy liên kết thiết bị', - 'device.confirmUnbindDevice': 'Bạn có chắc chắn muốn hủy liên kết thiết bị "{macAddress}"?', - 'device.cancel': 'Hủy', - 'device.noDevice': 'Không có thiết bị', - 'device.pleaseSelectAgent': 'Vui lòng chọn một đại lý trước', - 'device.deviceBindSuccess': 'Liên kết thiết bị thành công!', - 'device.bindFailed': 'Liên kết thất bại, vui lòng kiểm tra mã xác minh có đúng không', - 'device.enterDeviceCode': 'Vui lòng nhập mã xác minh thiết bị', - 'device.bindNow': 'Liên kết ngay', - 'device.lastConnection': 'Kết nối cuối', - 'device.clickToBindFirstDevice': 'Nhấp vào nút + ở góc dưới bên phải để liên kết thiết bị đầu tiên của bạn', + // Trang quản lý thiết bị + 'device.pageTitle': 'Quản lý thiết bị', + 'device.noDevices': 'Không có thiết bị nào', + 'device.macAddress': 'Địa chỉ MAC', + 'device.firmwareVersion': 'Phiên bản firmware', + 'device.lastConnected': 'Cuộc trò chuyện cuối', + 'device.otaUpdate': 'Cập nhật OTA', + 'device.unbind': 'Hủy liên kết', + 'device.confirmUnbind': 'Xác nhận', + 'device.bindDevice': 'Liên kết thiết bị mới', + 'device.deviceType': 'Loại thiết bị', + 'device.loading': 'Đang tải...', + 'device.neverConnected': 'Chưa kết nối', + 'device.justNow': 'Vừa xong', + 'device.minutesAgo': '{minutes} phút trước', + 'device.hoursAgo': '{hours} giờ trước', + 'device.daysAgo': '{days} ngày trước', + 'device.otaAutoUpdateEnabled': 'Đã bật cập nhật OTA tự động', + 'device.otaAutoUpdateDisabled': 'Đã tắt cập nhật OTA tự động', + 'device.operationFailed': 'Thao tác thất bại, vui lòng thử lại', + 'device.deviceUnbound': 'Đã hủy liên kết thiết bị', + 'device.unbindFailed': 'Hủy liên kết thất bại, vui lòng thử lại', + 'device.unbindDevice': 'Hủy liên kết thiết bị', + 'device.confirmUnbindDevice': 'Bạn có chắc chắn muốn hủy liên kết thiết bị "{macAddress}"?', + 'device.cancel': 'Hủy', + 'device.noDevice': 'Không có thiết bị', + 'device.pleaseSelectAgent': 'Vui lòng chọn một đại lý trước', + 'device.deviceBindSuccess': 'Liên kết thiết bị thành công!', + 'device.bindFailed': 'Liên kết thất bại, vui lòng kiểm tra mã xác minh có đúng không', + 'device.enterDeviceCode': 'Vui lòng nhập mã xác minh thiết bị', + 'device.bindNow': 'Liên kết ngay', + 'device.lastConnection': 'Kết nối cuối', + 'device.clickToBindFirstDevice': 'Nhấp vào nút + ở góc dưới bên phải để liên kết thiết bị đầu tiên của bạn', - // Chung - 'common.success': 'Thành công', - 'common.fail': 'Thất bại', - 'common.loading': 'Đang tải...', - 'common.confirm': 'Xác nhận', - 'common.cancel': 'Hủy', - 'common.delete': 'Xóa', - 'common.edit': 'Chỉnh sửa', - 'common.add': 'Thêm', - 'common.pleaseSelect': 'Vui lòng chọn', - 'common.unknownError': 'Lỗi không xác định', - 'common.networkError': 'Lỗi mạng', + // Chung + 'common.success': 'Thành công', + 'common.fail': 'Thất bại', + 'common.loading': 'Đang tải...', + 'common.confirm': 'Xác nhận', + 'common.cancel': 'Hủy', + 'common.delete': 'Xóa', + 'common.edit': 'Chỉnh sửa', + 'common.add': 'Thêm', + 'common.pleaseSelect': 'Vui lòng chọn', + 'common.unknownError': 'Lỗi không xác định', + 'common.networkError': 'Lỗi mạng', - // Trang khôi phục mật khẩu - 'retrievePassword.title': 'Đặt lại mật khẩu', - 'retrievePassword.subtitle': 'Khôi phục mật khẩu tài khoản qua số điện thoại', - 'retrievePassword.mobileRequired': 'Vui lòng nhập số điện thoại', - 'retrievePassword.inputCorrectMobile': 'Vui lòng nhập số điện thoại hợp lệ', - 'retrievePassword.captchaRequired': 'Vui lòng nhập mã xác minh đồ họa', - 'retrievePassword.mobileCaptchaRequired': 'Vui lòng nhập mã xác minh SMS', - 'retrievePassword.newPasswordRequired': 'Vui lòng nhập mật khẩu mới', - 'retrievePassword.confirmNewPasswordRequired': 'Vui lòng xác nhận mật khẩu mới', - 'retrievePassword.passwordsNotMatch': 'Mật khẩu không khớp', - 'retrievePassword.mobilePlaceholder': 'Vui lòng nhập số điện thoại', - 'retrievePassword.captchaPlaceholder': 'Vui lòng nhập mã xác minh đồ họa', - 'retrievePassword.mobileCaptchaPlaceholder': 'Vui lòng nhập mã xác minh SMS', - 'retrievePassword.newPasswordPlaceholder': 'Vui lòng nhập mật khẩu mới', - 'retrievePassword.confirmNewPasswordPlaceholder': 'Vui lòng xác nhận mật khẩu mới', - 'retrievePassword.getMobileCaptcha': 'Lấy mã', - 'retrievePassword.captchaSendSuccess': 'Đã gửi mã xác minh thành công', - 'retrievePassword.passwordUpdateSuccess': 'Đặt lại mật khẩu thành công', - 'retrievePassword.resetButton': 'Đặt lại mật khẩu', - 'retrievePassword.goToLogin': 'Quay lại đăng nhập', + // Trang khôi phục mật khẩu + 'retrievePassword.title': 'Đặt lại mật khẩu', + 'retrievePassword.subtitle': 'Khôi phục mật khẩu tài khoản qua số điện thoại', + 'retrievePassword.mobileRequired': 'Vui lòng nhập số điện thoại', + 'retrievePassword.inputCorrectMobile': 'Vui lòng nhập số điện thoại hợp lệ', + 'retrievePassword.captchaRequired': 'Vui lòng nhập mã xác minh đồ họa', + 'retrievePassword.mobileCaptchaRequired': 'Vui lòng nhập mã xác minh SMS', + 'retrievePassword.newPasswordRequired': 'Vui lòng nhập mật khẩu mới', + 'retrievePassword.confirmNewPasswordRequired': 'Vui lòng xác nhận mật khẩu mới', + 'retrievePassword.passwordsNotMatch': 'Mật khẩu không khớp', + 'retrievePassword.mobilePlaceholder': 'Vui lòng nhập số điện thoại', + 'retrievePassword.captchaPlaceholder': 'Vui lòng nhập mã xác minh đồ họa', + 'retrievePassword.mobileCaptchaPlaceholder': 'Vui lòng nhập mã xác minh SMS', + 'retrievePassword.newPasswordPlaceholder': 'Vui lòng nhập mật khẩu mới', + 'retrievePassword.confirmNewPasswordPlaceholder': 'Vui lòng xác nhận mật khẩu mới', + 'retrievePassword.getMobileCaptcha': 'Lấy mã', + 'retrievePassword.captchaSendSuccess': 'Đã gửi mã xác minh thành công', + 'retrievePassword.passwordUpdateSuccess': 'Đặt lại mật khẩu thành công', + 'retrievePassword.resetButton': 'Đặt lại mật khẩu', + 'retrievePassword.goToLogin': 'Quay lại đăng nhập', - // Thông báo lỗi liên quan đến mã hóa SM2 - 'sm2.publicKeyNotConfigured': 'Khóa công khai SM2 chưa được cấu hình, vui lòng liên hệ quản trị viên', - 'sm2.encryptionFailed': 'Mã hóa mật khẩu thất bại', - 'sm2.keyGenerationFailed': 'Tạo cặp khóa thất bại', - 'sm2.invalidPublicKey': 'Định dạng khóa công khai không hợp lệ', - 'sm2.encryptionError': 'Đã xảy ra lỗi khi mã hóa', - 'sm2.publicKeyRetry': 'Đang thử lấy lại khóa công khai...', - 'sm2.publicKeyRetryFailed': 'Thử lấy lại khóa công khai thất bại', + // Thông báo lỗi liên quan đến mã hóa SM2 + 'sm2.publicKeyNotConfigured': 'Khóa công khai SM2 chưa được cấu hình, vui lòng liên hệ quản trị viên', + 'sm2.encryptionFailed': 'Mã hóa mật khẩu thất bại', + 'sm2.keyGenerationFailed': 'Tạo cặp khóa thất bại', + 'sm2.invalidPublicKey': 'Định dạng khóa công khai không hợp lệ', + 'sm2.encryptionError': 'Đã xảy ra lỗi khi mã hóa', + 'sm2.publicKeyRetry': 'Đang thử lấy lại khóa công khai...', + 'sm2.publicKeyRetryFailed': 'Thử lấy lại khóa công khai thất bại', - // Trang dấu giọng nói - 'voiceprint.noSelectedAgent': 'Chưa chọn đại lý', - 'voiceprint.pleaseSelectAgent': 'Vui lòng chọn một đại lý trước', - 'voiceprint.fetchHistoryFailed': 'Không thể tải lịch sử trò chuyện', - 'voiceprint.clickToSelectVector': 'Nhấp để chọn vector dấu giọng nói', - 'voiceprint.pleaseInputName': 'Vui lòng nhập tên', - 'voiceprint.pleaseSelectVector': 'Vui lòng chọn vector dấu giọng nói', - 'voiceprint.addSuccess': 'Thêm thành công', - 'voiceprint.addFailed': 'Thêm người nói thất bại', - 'voiceprint.editSuccess': 'Chỉnh sửa thành công', - 'voiceprint.editFailed': 'Chỉnh sửa người nói thất bại', - 'voiceprint.deleteConfirmMsg': 'Bạn có chắc chắn muốn xóa người nói này?', - 'voiceprint.deleteConfirmTitle': 'Xác nhận xóa', - 'voiceprint.deleteSuccess': 'Xóa thành công', - 'voiceprint.loading': 'Đang tải...', - 'voiceprint.delete': 'Xóa', - 'voiceprint.emptyTitle': 'Không có dữ liệu dấu giọng nói', - 'voiceprint.emptyDesc': 'Nhấp vào nút + ở góc dưới bên phải để thêm người nói đầu tiên của bạn', - 'voiceprint.addSpeaker': 'Thêm người nói', - 'voiceprint.voiceVector': 'Vector dấu giọng nói', - 'voiceprint.name': 'Tên', - 'voiceprint.description': 'Mô tả', - 'voiceprint.pleaseInputDescription': 'Vui lòng nhập mô tả', - 'voiceprint.cancel': 'Hủy', - 'voiceprint.save': 'Lưu', - 'voiceprint.editSpeaker': 'Chỉnh sửa người nói', - 'voiceprint.selectVector': 'Chọn vector dấu giọng nói', - 'voiceprint.voiceprintInterfaceNotConfigured': 'Giao diện dấu giọng nói chưa được cấu hình', + // Trang dấu giọng nói + 'voiceprint.noSelectedAgent': 'Chưa chọn đại lý', + 'voiceprint.pleaseSelectAgent': 'Vui lòng chọn một đại lý trước', + 'voiceprint.fetchHistoryFailed': 'Không thể tải lịch sử trò chuyện', + 'voiceprint.clickToSelectVector': 'Nhấp để chọn vector dấu giọng nói', + 'voiceprint.pleaseInputName': 'Vui lòng nhập tên', + 'voiceprint.pleaseSelectVector': 'Vui lòng chọn vector dấu giọng nói', + 'voiceprint.addSuccess': 'Thêm thành công', + 'voiceprint.addFailed': 'Thêm người nói thất bại', + 'voiceprint.editSuccess': 'Chỉnh sửa thành công', + 'voiceprint.editFailed': 'Chỉnh sửa người nói thất bại', + 'voiceprint.deleteConfirmMsg': 'Bạn có chắc chắn muốn xóa người nói này?', + 'voiceprint.deleteConfirmTitle': 'Xác nhận xóa', + 'voiceprint.deleteSuccess': 'Xóa thành công', + 'voiceprint.loading': 'Đang tải...', + 'voiceprint.delete': 'Xóa', + 'voiceprint.emptyTitle': 'Không có dữ liệu dấu giọng nói', + 'voiceprint.emptyDesc': 'Nhấp vào nút + ở góc dưới bên phải để thêm người nói đầu tiên của bạn', + 'voiceprint.addSpeaker': 'Thêm người nói', + 'voiceprint.voiceVector': 'Vector dấu giọng nói', + 'voiceprint.name': 'Tên', + 'voiceprint.description': 'Mô tả', + 'voiceprint.pleaseInputDescription': 'Vui lòng nhập mô tả', + 'voiceprint.cancel': 'Hủy', + 'voiceprint.save': 'Lưu', + 'voiceprint.editSpeaker': 'Chỉnh sửa người nói', + 'voiceprint.selectVector': 'Chọn vector dấu giọng nói', + 'voiceprint.voiceprintInterfaceNotConfigured': 'Giao diện dấu giọng nói chưa được cấu hình', - // Trang cài đặt - 'settings.pageTitle': 'Cài đặt', - 'settings.navigationTitle': 'Cài đặt', - 'settings.networkSettings': 'Cài đặt mạng', - 'settings.serverApiUrl': 'URL API máy chủ', - 'settings.validServerUrl': 'Vui lòng nhập địa chỉ máy chủ hợp lệ (bắt đầu bằng http hoặc https và kết thúc bằng /xiaozhi)', - 'settings.saveSettings': 'Lưu cài đặt', - 'settings.resetDefault': 'Đặt lại mặc định', - 'settings.restartApp': 'Khởi động lại ứng dụng', - 'settings.restartNow': 'Khởi động lại ngay', - 'settings.restartLater': 'Để sau', - // Về chúng tôi - 'settings.aboutApp': 'Về Bảng điều khiển XiaoZhi', - 'settings.aboutContent': 'Bảng điều khiển XiaoZhi\n\nỨng dụng quản lý di động đa nền tảng được xây dựng với Vue.js 3 + uni-app, cung cấp quản lý thiết bị, cấu hình đại lý và các chức năng khác cho phần cứng thông minh xiaozhi ESP32.\n\n© 2025 xiaozhi-esp32-server {version}', - 'settings.restartSuccess': 'Đã lưu, bạn có thể tự khởi động lại ứng dụng sau', - 'settings.serverUrlSavedAndCacheCleared': 'Đã lưu URL máy chủ và xóa bộ nhớ cache', - 'settings.resetToDefaultAndCacheCleared': 'Đã đặt lại mặc định và xóa bộ nhớ cache', - 'settings.resetSuccess': 'Đặt lại thành công', - 'settings.enterServerUrl': 'Vui lòng nhập URL máy chủ', - 'settings.clearCacheFailed': 'Không thể xóa bộ nhớ cache', - 'settings.cacheManagement': 'Quản lý bộ nhớ cache', - 'settings.totalCacheSize': 'Tổng kích thước bộ nhớ cache', - 'settings.appDataSize': 'Tổng kích thước dữ liệu ứng dụng', - 'settings.cacheClear': 'Xóa bộ nhớ cache', - 'settings.clearAllCache': 'Xóa tất cả dữ liệu bộ nhớ cache', - 'settings.clearCache': 'Xóa bộ nhớ cache', - 'settings.modifyWillClearCache': 'Thay đổi sẽ xóa bộ nhớ cache', - 'settings.appInfo': 'Thông tin ứng dụng', - 'settings.aboutUs': 'Về chúng tôi', - 'settings.appVersion': 'Phiên bản ứng dụng & Thông tin nhóm', - 'settings.confirmClear': 'Xác nhận xóa', - 'settings.confirmClearMessage': 'Bạn có chắc chắn muốn xóa toàn bộ bộ nhớ cache? Điều này sẽ xóa tất cả dữ liệu bao gồm trạng thái đăng nhập và yêu cầu đăng nhập lại.', - 'settings.cacheCleared': 'Đã xóa bộ nhớ cache thành công, đang chuyển hướng đến trang đăng nhập', - 'settings.languageSettings': 'Cài đặt ngôn ngữ', - 'settings.language': 'Ngôn ngữ', - 'settings.selectLanguage': 'Chọn ngôn ngữ', - 'settings.languageChanged': 'Đã thay đổi ngôn ngữ thành công', + // Trang cài đặt + 'settings.pageTitle': 'Cài đặt', + 'settings.navigationTitle': 'Cài đặt', + 'settings.networkSettings': 'Cài đặt mạng', + 'settings.serverApiUrl': 'URL API máy chủ', + 'settings.validServerUrl': 'Vui lòng nhập địa chỉ máy chủ hợp lệ (bắt đầu bằng http hoặc https và kết thúc bằng /xiaozhi)', + 'settings.saveSettings': 'Lưu cài đặt', + 'settings.resetDefault': 'Đặt lại mặc định', + 'settings.restartApp': 'Khởi động lại ứng dụng', + 'settings.restartNow': 'Khởi động lại ngay', + 'settings.restartLater': 'Để sau', + // Về chúng tôi + 'settings.aboutApp': 'Về Bảng điều khiển XiaoZhi', + 'settings.aboutContent': 'Bảng điều khiển XiaoZhi\n\nỨng dụng quản lý di động đa nền tảng được xây dựng với Vue.js 3 + uni-app, cung cấp quản lý thiết bị, cấu hình đại lý và các chức năng khác cho phần cứng thông minh xiaozhi ESP32.\n\n© 2025 xiaozhi-esp32-server {version}', + 'settings.restartSuccess': 'Đã lưu, bạn có thể tự khởi động lại ứng dụng sau', + 'settings.serverUrlSavedAndCacheCleared': 'Đã lưu URL máy chủ và xóa bộ nhớ cache', + 'settings.resetToDefaultAndCacheCleared': 'Đã đặt lại mặc định và xóa bộ nhớ cache', + 'settings.resetSuccess': 'Đặt lại thành công', + 'settings.enterServerUrl': 'Vui lòng nhập URL máy chủ', + 'settings.clearCacheFailed': 'Không thể xóa bộ nhớ cache', + 'settings.cacheManagement': 'Quản lý bộ nhớ cache', + 'settings.totalCacheSize': 'Tổng kích thước bộ nhớ cache', + 'settings.appDataSize': 'Tổng kích thước dữ liệu ứng dụng', + 'settings.cacheClear': 'Xóa bộ nhớ cache', + 'settings.clearAllCache': 'Xóa tất cả dữ liệu bộ nhớ cache', + 'settings.clearCache': 'Xóa bộ nhớ cache', + 'settings.modifyWillClearCache': 'Thay đổi sẽ xóa bộ nhớ cache', + 'settings.appInfo': 'Thông tin ứng dụng', + 'settings.aboutUs': 'Về chúng tôi', + 'settings.appVersion': 'Phiên bản ứng dụng & Thông tin nhóm', + 'settings.confirmClear': 'Xác nhận xóa', + 'settings.confirmClearMessage': 'Bạn có chắc chắn muốn xóa toàn bộ bộ nhớ cache? Điều này sẽ xóa tất cả dữ liệu bao gồm trạng thái đăng nhập và yêu cầu đăng nhập lại.', + 'settings.cacheCleared': 'Đã xóa bộ nhớ cache thành công, đang chuyển hướng đến trang đăng nhập', + 'settings.languageSettings': 'Cài đặt ngôn ngữ', + 'settings.language': 'Ngôn ngữ', + 'settings.selectLanguage': 'Chọn ngôn ngữ', + 'settings.languageChanged': 'Đã thay đổi ngôn ngữ thành công', - // Thông báo - 'message.loginSuccess': 'Đăng nhập thành công!', - 'message.loginFail': 'Đăng nhập thất bại', - 'message.registerSuccess': 'Đăng ký thành công', - 'message.registerFail': 'Đăng ký thất bại', - 'message.saveSuccess': 'Lưu thành công', - 'message.saveFail': 'Lưu thất bại', - 'message.deleteSuccess': 'Xóa thành công', - 'message.deleteFail': 'Xóa thất bại', - 'message.bindSuccess': 'Liên kết thành công', - 'message.bindFail': 'Liên kết thất bại', - 'message.unbindSuccess': 'Hủy liên kết thành công', - 'message.unbindFail': 'Hủy liên kết thất bại', - 'message.networkError': 'Lỗi mạng, vui lòng kiểm tra kết nối', - 'message.serverError': 'Lỗi máy chủ, vui lòng thử lại sau', - 'message.invalidAddress': 'Địa chỉ có thể không hợp lệ. Vui lòng kiểm tra xem máy chủ đã khởi động hay kết nối mạng chưa; Có thể không gửi được yêu cầu do lỗi giao thức HTTPS', - 'message.languageChanged': 'Đã thay đổi ngôn ngữ', - 'message.passwordError': 'Lỗi tài khoản hoặc mật khẩu', - 'message.phoneRegistered': 'Số điện thoại này đã được đăng ký', + // Thông báo + 'message.loginSuccess': 'Đăng nhập thành công!', + 'message.loginFail': 'Đăng nhập thất bại', + 'message.registerSuccess': 'Đăng ký thành công', + 'message.registerFail': 'Đăng ký thất bại', + 'message.saveSuccess': 'Lưu thành công', + 'message.saveFail': 'Lưu thất bại', + 'message.deleteSuccess': 'Xóa thành công', + 'message.deleteFail': 'Xóa thất bại', + 'message.bindSuccess': 'Liên kết thành công', + 'message.bindFail': 'Liên kết thất bại', + 'message.unbindSuccess': 'Hủy liên kết thành công', + 'message.unbindFail': 'Hủy liên kết thất bại', + 'message.networkError': 'Lỗi mạng, vui lòng kiểm tra kết nối', + 'message.serverError': 'Lỗi máy chủ, vui lòng thử lại sau', + 'message.invalidAddress': 'Địa chỉ có thể không hợp lệ. Vui lòng kiểm tra xem máy chủ đã khởi động hay kết nối mạng chưa; Có thể không gửi được yêu cầu do lỗi giao thức HTTPS', + 'message.languageChanged': 'Đã thay đổi ngôn ngữ', + 'message.passwordError': 'Lỗi tài khoản hoặc mật khẩu', + 'message.phoneRegistered': 'Số điện thoại này đã được đăng ký', - // Trang công cụ đại lý - 'agent.tools.pageTitle': 'Công cụ đại lý', - 'agent.tools.unselected': 'Chưa chọn', - 'agent.tools.selected': 'Đã chọn', - 'agent.tools.noMorePlugins': 'Không còn plugin', - 'agent.tools.pleaseSelectPlugin': 'Vui lòng chọn chức năng plugin', - 'agent.tools.builtInPlugins': 'Plugin tích hợp', - 'agent.tools.mcpAccessPoint': 'Điểm truy cập MCP', - 'agent.tools.copy': 'Sao chép', - 'agent.tools.noTools': 'Không có công cụ nào', - 'agent.tools.parameterConfig': 'Cấu hình', - 'agent.tools.noParamsNeeded': 'Không cần tham số', - 'agent.tools.pleaseInput': 'Vui lòng nhập', - 'agent.tools.inputOneItemPerLine': 'Nhập một mục mỗi dòng', - 'agent.tools.pleaseInputValidJson': 'Vui lòng nhập định dạng JSON hợp lệ', - 'agent.tools.enableFunction': 'Bật chức năng', - 'agent.tools.toggleFunction': 'Bật hoặc tắt chức năng này', - 'agent.tools.jsonFormatError': 'Lỗi định dạng JSON', - 'agent.tools.noMcpAddressToCopy': 'Không có địa chỉ MCP để sao chép', - 'agent.tools.mcpAddressCopied': 'Đã sao chép địa chỉ MCP vào bộ nhớ tạm', - 'agent.tools.copyFailed': 'Sao chép thất bại, vui lòng thử lại', - 'agent.tools.defaultValue': 'Giá trị mặc định', - 'agent.tools.notSelected': 'Chưa chọn', - 'agent.tools.clickToConfigure': 'Nhấp để cấu hình', - 'agent.tools.mcpEndpoint': 'Điểm cuối MCP', - 'agent.tools.eachLineOneItem': 'Nhập một mục mỗi dòng', + // Trang công cụ đại lý + 'agent.tools.pageTitle': 'Công cụ đại lý', + 'agent.tools.unselected': 'Chưa chọn', + 'agent.tools.selected': 'Đã chọn', + 'agent.tools.noMorePlugins': 'Không còn plugin', + 'agent.tools.pleaseSelectPlugin': 'Vui lòng chọn chức năng plugin', + 'agent.tools.builtInPlugins': 'Plugin tích hợp', + 'agent.tools.mcpAccessPoint': 'Điểm truy cập MCP', + 'agent.tools.copy': 'Sao chép', + 'agent.tools.noTools': 'Không có công cụ nào', + 'agent.tools.parameterConfig': 'Cấu hình', + 'agent.tools.noParamsNeeded': 'Không cần tham số', + 'agent.tools.pleaseInput': 'Vui lòng nhập', + 'agent.tools.inputOneItemPerLine': 'Nhập một mục mỗi dòng', + 'agent.tools.pleaseInputValidJson': 'Vui lòng nhập định dạng JSON hợp lệ', + 'agent.tools.enableFunction': 'Bật chức năng', + 'agent.tools.toggleFunction': 'Bật hoặc tắt chức năng này', + 'agent.tools.jsonFormatError': 'Lỗi định dạng JSON', + 'agent.tools.noMcpAddressToCopy': 'Không có địa chỉ MCP để sao chép', + 'agent.tools.mcpAddressCopied': 'Đã sao chép địa chỉ MCP vào bộ nhớ tạm', + 'agent.tools.copyFailed': 'Sao chép thất bại, vui lòng thử lại', + 'agent.tools.defaultValue': 'Giá trị mặc định', + 'agent.tools.notSelected': 'Chưa chọn', + 'agent.tools.clickToConfigure': 'Nhấp để cấu hình', + 'agent.tools.mcpEndpoint': 'Điểm cuối MCP', + 'agent.tools.eachLineOneItem': 'Nhập một mục mỗi dòng', // Trang cấu hình thiết bị 'deviceConfig.pageTitle': 'Cấu hình thiết bị', @@ -497,8 +591,8 @@ export default { 'deviceConfig.audioPlaybackError': 'Lỗi phát âm thanh', 'deviceConfig.playbackFailed': 'Phát thất bại', - // Voiceprint page - 'voiceprint.audioNotExist': 'Âm thanh không tồn tại', - 'voiceprint.getAudioFailed': 'Không thể lấy âm thanh', - 'voiceprint.audioPlayFailed': 'Phát âm thanh thất bại', -} \ No newline at end of file + // Voiceprint page + 'voiceprint.audioNotExist': 'Âm thanh không tồn tại', + 'voiceprint.getAudioFailed': 'Không thể lấy âm thanh', + 'voiceprint.audioPlayFailed': 'Phát âm thanh thất bại', +} diff --git a/main/manager-mobile/src/layouts/default.vue b/main/manager-mobile/src/layouts/default.vue index 360c6b216..ffde284ea 100644 --- a/main/manager-mobile/src/layouts/default.vue +++ b/main/manager-mobile/src/layouts/default.vue @@ -1,5 +1,5 @@ + + + + diff --git a/main/manager-mobile/src/pages/agent/components/agentSnapshotContracts.test.mjs b/main/manager-mobile/src/pages/agent/components/agentSnapshotContracts.test.mjs new file mode 100644 index 000000000..a217a99aa --- /dev/null +++ b/main/manager-mobile/src/pages/agent/components/agentSnapshotContracts.test.mjs @@ -0,0 +1,103 @@ +/* eslint-disable test/no-import-node-test -- zero-dependency source contract gate */ +import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' +import test from 'node:test' + +const panelSource = await readFile(new URL('./AgentSnapshotPanel.vue', import.meta.url), 'utf8') +const editSource = await readFile(new URL('../edit.vue', import.meta.url), 'utf8') + +function sourceBetween(source, startMarker, endMarker) { + const start = source.indexOf(startMarker) + const end = source.indexOf(endMarker, start + startMarker.length) + assert.notEqual(start, -1, `missing start marker: ${startMarker}`) + assert.notEqual(end, -1, `missing end marker: ${endMarker}`) + return source.slice(start, end) +} + +test('restore enters busy state before confirmations and requires a final destructive confirmation', () => { + const restore = sourceBetween( + panelSource, + 'async function confirmRestoreSnapshot()', + 'async function requestRestoreConfirmation', + ) + const busyIndex = restore.indexOf('restoring.value = true') + const unsavedConfirmIndex = restore.indexOf('title: t(\'agentSnapshot.unsavedChangesTitle\')') + const destructiveConfirmIndex = restore.indexOf('msg: t(\'agentSnapshot.restoreChatHistoryDestructiveWarning\')') + const postIndex = restore.indexOf('await restoreAgentSnapshot(') + + assert.ok(busyIndex >= 0 && busyIndex < unsavedConfirmIndex) + assert.ok(destructiveConfirmIndex > unsavedConfirmIndex && destructiveConfirmIndex < postIndex) + assert.match(restore, /if \(context\.willClearChatHistory\)/) + assert.match(restore.slice(destructiveConfirmIndex, postIndex), /isActiveRestoreAction\(context\)/) + const finalMutationGuardIndex = restore.lastIndexOf('if (!isActiveRestoreAction(context))', postIndex) + const postBoundaryIndex = restore.indexOf('restorePostActionSequence = context.actionSequence') + assert.ok(finalMutationGuardIndex > destructiveConfirmIndex) + assert.ok(finalMutationGuardIndex < postBoundaryIndex && postBoundaryIndex < postIndex) +}) +test('restore guards popup exits and stale action completion', () => { + assert.match(panelSource, /if \(!value && restoring\.value\) \{\s*return\s*\}/) + assert.equal((panelSource.match(/:close-on-click-modal="!restoring"/g) || []).length, 2) + assert.match(panelSource, /function closeDetail\(force = false\) \{\s*if \(restoring\.value && !force\)/) + assert.match(panelSource, /context\.agentId === props\.agentId/) + assert.match(panelSource, /context\.detailRequestSequence === detailRequestSequence/) + assert.match(panelSource, /if \(!isActiveRestoreAction\(context\)\) \{\s*return\s*\}\s*toast\.success/) + assert.match(panelSource, /mutationBusy\?: boolean/) + assert.match(panelSource, /&& !props\.mutationBusy[\s\S]*currentDetail\.value\?\.mode === 'restore'/) + assert.match(panelSource, /&& \(!props\.mutationBusy \|\| restorePostActionSequence === context\.actionSequence\)/) + assert.match(panelSource, /if \(restorePostInFlight\) \{\s*return\s*\}/) +}) + +test('post-restore detail and tag reload fail closed before save', () => { + const save = sourceBetween(editSource, 'async function saveAgent()', 'function loadPluginFunctions()') + const reload = sourceBetween( + editSource, + 'async function reloadAgentAfterSnapshotRestore', + 'function isActiveSnapshotReload', + ) + + assert.ok(save.indexOf('if (snapshotReloadBlocked.value)') < save.indexOf('await updateAgent(')) + assert.match(reload, /snapshotReloadBlocked\.value = true/) + assert.match(reload, /Promise\.all\(\[\s*getAgentDetail\(targetAgentId\),\s*getAgentTags\(targetAgentId\)/) + assert.ok(reload.indexOf('const [detail, tags] = await Promise.all') < reload.indexOf('applyPersistedAgentDetail(')) + assert.match(reload, /snapshotReloadFailed\.value = true/) + assert.match(editSource, /:disabled="saving \|\| ttsOptionsLoading \|\| snapshotReloadBlocked"/) + assert.match(editSource, /v-if="snapshotReloadFailed"[\s\S]*@click="retrySnapshotReload"/) +}) + +test('parent mutations guard history opening and propagate into every restore gate', () => { + const opener = sourceBetween(editSource, 'function openSnapshotPanel()', 'function isSameStringList') + const restore = sourceBetween( + panelSource, + 'async function confirmRestoreSnapshot()', + 'async function requestRestoreConfirmation', + ) + + assert.match(opener, /if \(saving\.value \|\| snapshotReloadBlocked\.value\) \{[\s\S]*return/) + assert.match(editSource, /:disabled="saving \|\| snapshotReloadBlocked"[\s\S]*@click="openSnapshotPanel"/) + assert.match(editSource, /:mutation-busy="saving \|\| snapshotReloadBlocked"/) + assert.match(restore, /if \(props\.mutationBusy\) \{[\s\S]*return/) + const postIndex = restore.indexOf('await restoreAgentSnapshot(') + const finalGate = restore.lastIndexOf('if (!isActiveRestoreAction(context))', postIndex) + assert.ok(finalGate >= 0 && finalGate < postIndex) +}) + +test('the latest snapshot hides restore and delete actions', () => { + const restoreGate = sourceBetween( + panelSource, + 'function canRestoreSnapshot(row: SnapshotRow)', + 'function canDeleteSnapshot(row: SnapshotRow)', + ) + const deleteGate = sourceBetween( + panelSource, + 'function canDeleteSnapshot(row: SnapshotRow)', + 'function buildDetailItems', + ) + + assert.match(restoreGate, /!!row\?\.id && !row\.isLatestSnapshot/) + assert.match(deleteGate, /!!row\?\.id && !row\.isLatestSnapshot/) + assert.match(panelSource, /v-if="canRestoreSnapshot\(snapshot\)"/) + assert.match( + panelSource, + /async function previewRestoreSnapshot\(row: SnapshotRow\) \{\s*if \(!canRestoreSnapshot\(row\)\) \{\s*return/, + ) +}) diff --git a/main/manager-mobile/src/pages/agent/components/agentSnapshotUtils.mjs b/main/manager-mobile/src/pages/agent/components/agentSnapshotUtils.mjs new file mode 100644 index 000000000..c94a46879 --- /dev/null +++ b/main/manager-mobile/src/pages/agent/components/agentSnapshotUtils.mjs @@ -0,0 +1,314 @@ +export const SNAPSHOT_SECRET_REDACTED = '__SNAPSHOT_SECRET_REDACTED__' + +/** @param {unknown} voices */ +export function hasUsableTtsVoiceMetadata(voices) { + return Array.isArray(voices) && voices.length > 0 +} + +/** + * @param {unknown} currentMemModelId + * @param {unknown} targetMemModelId + */ +export function willRestorePermanentlyDeleteChatHistory(currentMemModelId, targetMemModelId) { + return currentMemModelId !== 'Memory_nomem' && targetMemModelId === 'Memory_nomem' +} + +/** + * @param {Array>} voices + * @param {string} language + */ +export function filterTtsVoicesByLanguage(voices, language) { + if (!language) { + return voices + } + return voices.filter((voice) => { + if (typeof voice.languages !== 'string' || !voice.languages.trim()) { + return false + } + return voice.languages + .split(/[、;;,,]/) + .map(item => item.trim()) + .filter(Boolean) + .includes(language) + }) +} + +/** @param {unknown} value */ +export function normalizeSnapshotTtsNumber(value) { + if (value === undefined || value === null || String(value).trim() === '') { + return null + } + if (typeof value === 'number') { + return Math.trunc(value) + } + const text = String(value).trim() + return /^[+-]?\d+$/.test(text) ? Number.parseInt(text, 10) : text +} + +/** + * Normalize object-key order without changing array order. Context providers + * are consumed sequentially by the runtime, so their list order is semantic. + * @param {unknown} value + */ +export function normalizeSnapshotOrderedList(value) { + if (!Array.isArray(value)) { + return [] + } + return value + .filter(item => item !== undefined && item !== null) + .map(normalizeDisplayObject) +} + +/** + * @param {unknown} value + * @param {string} redactedLabel + * @param {string} [parentKey] + * @returns {unknown} + */ +export function redactSnapshotDisplayValue(value, redactedLabel, parentKey = '') { + if (value === SNAPSHOT_SECRET_REDACTED || isSensitiveKey(parentKey)) { + return redactedLabel + } + if (Array.isArray(value)) { + return value.map(item => redactSnapshotDisplayValue(item, redactedLabel, parentKey)) + } + if (isPlainObject(value)) { + const entryNameKey = Object.keys(value).find((key) => { + return ['key', 'name'].includes(key.toLowerCase()) + && typeof value[key] === 'string' + && isSensitiveKey(value[key]) + }) + const entryValueKey = Object.keys(value).find(key => key.toLowerCase() === 'value') + return Object.keys(value).sort().reduce((result, key) => { + const semanticKey = resolveUrlSemanticKey(parentKey, key) + if (entryNameKey && key === entryValueKey) { + result[key] = redactedLabel + } + else { + result[key] = redactSnapshotDisplayValue(value[key], redactedLabel, semanticKey) + } + return result + }, {}) + } + if (typeof value === 'string' && isSnapshotUrlValue(parentKey, value)) { + return redactUrl(value, redactedLabel, parentKey) + } + return value +} + +/** @param {unknown} value */ +export function stablePrettyStringify(value) { + return JSON.stringify(normalizeDisplayObject(value), null, 2) +} + +/** @param {string} language */ +export function toIntlLocale(language) { + return language.replace('_', '-') +} + +/** @param {string} key */ +export function isSensitiveKey(key) { + const normalized = String(key).toLowerCase().replace(/[^a-z0-9]/g, '') + return normalized === 'authorization' + || normalized.includes('authorization') + || normalized.includes('authentication') + || normalized === 'auth' + || normalized.endsWith('auth') + || normalized === 'cookie' + || normalized === 'cookie2' + || normalized === 'setcookie' + || normalized === 'setcookie2' + || normalized.endsWith('cookie') + || normalized === 'session' + || normalized.endsWith('session') + || normalized.includes('sessionid') + || normalized.includes('sessionkey') + || normalized.includes('sessiontoken') + || normalized.includes('sessioncookie') + || normalized.endsWith('sessid') + || normalized === 'token' + || normalized.endsWith('token') + || normalized.includes('apikey') + || normalized.includes('appkey') + || normalized.includes('accesskey') + || normalized.includes('subscriptionkey') + || normalized.includes('privatekey') + || normalized.includes('password') + || normalized.includes('passwd') + || normalized.includes('secret') + || normalized.includes('credential') +} + +/** + * @param {string} value + * @param {string} redactedLabel + * @param {string} parentKey + */ +function redactUrl(value, redactedLabel, parentKey) { + const withoutCredentials = value.replace( + /^((?:[a-z][a-z0-9+.-]*:)*\/\/)[^/?#\s]*@/i, + (match, prefix) => `${prefix}${redactedLabel}@`, + ) + const schemeMatch = /^((?:[a-z][a-z0-9+.-]*:)*\/\/)/i.exec(withoutCredentials) + let pathRedacted = withoutCredentials + if (schemeMatch) { + const scheme = schemeMatch[1] + const remainder = withoutCredentials.slice(scheme.length) + const suffixIndex = remainder.search(/[?#]/) + const authorityAndPath = suffixIndex < 0 ? remainder : remainder.slice(0, suffixIndex) + const suffix = suffixIndex < 0 ? '' : remainder.slice(suffixIndex) + const pathIndex = authorityAndPath.indexOf('/') + const authority = pathIndex < 0 ? authorityAndPath : authorityAndPath.slice(0, pathIndex) + const path = pathIndex < 0 ? '' : authorityAndPath.slice(pathIndex) + let host = authority.slice(authority.lastIndexOf('@') + 1) + if (host.startsWith('[')) { + const closingBracket = host.indexOf(']') + host = closingBracket > 0 ? host.slice(1, closingBracket) : host + } + else { + host = host.replace(/:\d+$/, '') + } + host = host.toLowerCase() + pathRedacted = `${scheme}${authority}${redactCapabilityPath(path, host, parentKey, redactedLabel)}${suffix}` + } + else { + const suffixIndex = withoutCredentials.search(/[?#]/) + const path = suffixIndex < 0 ? withoutCredentials : withoutCredentials.slice(0, suffixIndex) + const suffix = suffixIndex < 0 ? '' : withoutCredentials.slice(suffixIndex) + pathRedacted = `${redactCapabilityPath(path, '', parentKey, redactedLabel)}${suffix}` + } + const queryIndex = pathRedacted.search(/[?#]/) + if (queryIndex < 0) { + return pathRedacted + } + return `${pathRedacted.slice(0, queryIndex)}${pathRedacted[queryIndex]}${redactedLabel}` +} + +/** + * Capability URLs often carry credentials in path segments rather than in + * query parameters. Preserve public provider IDs where their formats are + * known, and fail closed after generic hook markers. + * @param {string} path + * @param {string} host + * @param {string} parentKey + * @param {string} redactedLabel + */ +function redactCapabilityPath(path, host, parentKey, redactedLabel) { + if (!path) { + return path + } + const segments = path.split('/') + const normalizedSegments = segments.map(segment => segment.toLowerCase()) + + if (host === 'hooks.slack.com' || host === 'hooks.slack-gov.com') { + const servicesIndex = normalizedSegments.indexOf('services') + const capabilityIndex = servicesIndex >= 0 ? servicesIndex + 3 : -1 + if (capabilityIndex > 0 && capabilityIndex < segments.length) { + segments[capabilityIndex] = redactedLabel + return segments.join('/') + } + } + + if (host === 'discord.com' + || host.endsWith('.discord.com') + || host === 'discordapp.com' + || host.endsWith('.discordapp.com')) { + const webhooksIndex = normalizedSegments.indexOf('webhooks') + const capabilityIndex = webhooksIndex >= 0 ? webhooksIndex + 2 : -1 + if (capabilityIndex > 0 && capabilityIndex < segments.length) { + segments[capabilityIndex] = redactedLabel + return segments.join('/') + } + } + + if (host === 'api.telegram.org') { + const botIndex = segments.findIndex(segment => /^bot[^:]+:.+$/i.test(segment)) + if (botIndex >= 0) { + segments[botIndex] = segments[botIndex].replace(/^bot([^:]+):.+$/i, `bot$1:${redactedLabel}`) + return segments.join('/') + } + } + + const markerIndex = normalizedSegments.findIndex(segment => /^(?:webhooks?|hooks?)$/.test(segment)) + if (markerIndex >= 0 && markerIndex + 1 < segments.length) { + return [...segments.slice(0, markerIndex + 1), redactedLabel].join('/') + } + + const normalizedKey = String(parentKey).toLowerCase().replace(/[^a-z0-9]/g, '') + if (normalizedKey.includes('webhook')) { + let lastSegmentIndex = -1 + for (let index = segments.length - 1; index >= 0; index -= 1) { + if (segments[index].length > 0) { + lastSegmentIndex = index + break + } + } + if (lastSegmentIndex >= 0) { + segments[lastSegmentIndex] = redactedLabel + return segments.join('/') + } + } + + return path +} + +/** + * Carry webhook capability semantics through wrapper objects such as + * `{ deliveryWebhook: { options: { target: "https://.../secret" } } }`. + * @param {string} parentKey + * @param {string} childKey + */ +function resolveUrlSemanticKey(parentKey, childKey) { + if (isWebhookSemanticKey(childKey)) { + return childKey + } + if (isWebhookSemanticKey(parentKey)) { + return childKey ? `${parentKey}.${childKey}` : parentKey + } + return childKey +} + +/** @param {string} value */ +function isWebhookSemanticKey(value) { + const normalized = String(value || '').toLowerCase().replace(/[^a-z0-9]/g, '') + return normalized.includes('webhook') + || normalized === 'hook' + || normalized === 'hooks' + || normalized.endsWith('hook') + || normalized.endsWith('hooks') +} + +/** + * @param {string} parentKey + * @param {string} value + */ +function isSnapshotUrlValue(parentKey, value) { + const normalizedKey = String(parentKey).toLowerCase().replace(/[^a-z0-9]/g, '') + return normalizedKey.includes('url') + || normalizedKey.endsWith('uri') + || normalizedKey.includes('endpoint') + || isWebhookSemanticKey(parentKey) + || /^(?:[a-z][a-z0-9+.-]*:)*\/\//i.test(value) +} + +/** @param {unknown} value */ +function normalizeDisplayObject(value) { + if (Array.isArray(value)) { + return value.map(normalizeDisplayObject) + } + if (isPlainObject(value)) { + return Object.keys(value).sort().reduce((result, key) => { + result[key] = normalizeDisplayObject(value[key]) + return result + }, {}) + } + return value +} + +/** + * @param {unknown} value + * @returns {value is Record} + */ +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value) +} diff --git a/main/manager-mobile/src/pages/agent/components/agentSnapshotUtils.test.mjs b/main/manager-mobile/src/pages/agent/components/agentSnapshotUtils.test.mjs new file mode 100644 index 000000000..a75e25dc2 --- /dev/null +++ b/main/manager-mobile/src/pages/agent/components/agentSnapshotUtils.test.mjs @@ -0,0 +1,183 @@ +/* eslint-disable test/no-import-node-test -- this zero-dependency gate intentionally uses Node's built-in runner */ +import assert from 'node:assert/strict' +import test from 'node:test' +import { + filterTtsVoicesByLanguage, + hasUsableTtsVoiceMetadata, + isSensitiveKey, + normalizeSnapshotOrderedList, + normalizeSnapshotTtsNumber, + redactSnapshotDisplayValue, + SNAPSHOT_SECRET_REDACTED, + stablePrettyStringify, + toIntlLocale, + willRestorePermanentlyDeleteChatHistory, +} from './agentSnapshotUtils.mjs' + +test('rejects empty TTS metadata while keeping language-less voices selectable without a filter', () => { + const voices = [{ id: 'voice-without-language', languages: '' }] + assert.equal(hasUsableTtsVoiceMetadata([]), false) + assert.equal(hasUsableTtsVoiceMetadata(voices), true) + assert.deepEqual(filterTtsVoicesByLanguage(voices, ''), voices) + assert.deepEqual(filterTtsVoicesByLanguage(voices, 'zh-CN'), []) +}) + +test('keeps inherited TTS values distinct from explicit zero', () => { + assert.equal(normalizeSnapshotTtsNumber(null), null) + assert.equal(normalizeSnapshotTtsNumber(''), null) + assert.equal(normalizeSnapshotTtsNumber(0), 0) + assert.equal(normalizeSnapshotTtsNumber('0'), 0) +}) + +test('warns only when restoring from a memory mode to no-memory mode', () => { + assert.equal(willRestorePermanentlyDeleteChatHistory('Memory_mem_local_short', 'Memory_nomem'), true) + assert.equal(willRestorePermanentlyDeleteChatHistory(undefined, 'Memory_nomem'), true) + assert.equal(willRestorePermanentlyDeleteChatHistory('Memory_nomem', 'Memory_nomem'), false) + assert.equal(willRestorePermanentlyDeleteChatHistory('Memory_mem_local_short', 'Memory_mem0ai'), false) +}) + +test('keeps context-provider order while stabilizing object keys', () => { + const first = normalizeSnapshotOrderedList([ + { url: 'https://one.example', headers: { z: 'last', a: 'first' } }, + { url: 'https://two.example', headers: {} }, + ]) + const reversed = normalizeSnapshotOrderedList([ + { url: 'https://two.example', headers: {} }, + { headers: { a: 'first', z: 'last' }, url: 'https://one.example' }, + ]) + + assert.deepEqual(first[0], { + headers: { a: 'first', z: 'last' }, + url: 'https://one.example', + }) + assert.notDeepEqual(first, reversed) +}) + +test('redacts nested credentials, header entries, URL credentials and query values', () => { + const redacted = redactSnapshotDisplayValue({ + 'apiKey': 'api-secret', + 'Authentication': 'authentication-secret', + 'X-Auth': 'auth-secret', + 'PHPSESSID': 'php-session-secret', + 'Session-Key': 'session-key-secret', + 'headers': [ + { key: 'Authorization', value: 'Bearer secret' }, + { key: 'Proxy-Authorization', value: 'Basic secret' }, + { key: 'Cookie', value: 'sid=secret' }, + { key: 'Set-Cookie', value: 'session=secret' }, + { key: 'Content-Type', value: 'application/json' }, + ], + 'marker': SNAPSHOT_SECRET_REDACTED, + 'session_id': 'session-secret', + 'url': 'https://user:pass@example.com/context?access_token=secret#fragment', + 'endpoint': 'https://example.com/callback?signature=secret', + }, '[hidden]') + + assert.deepEqual(redacted, { + 'apiKey': '[hidden]', + 'Authentication': '[hidden]', + 'X-Auth': '[hidden]', + 'PHPSESSID': '[hidden]', + 'Session-Key': '[hidden]', + 'headers': [ + { key: 'Authorization', value: '[hidden]' }, + { key: 'Proxy-Authorization', value: '[hidden]' }, + { key: 'Cookie', value: '[hidden]' }, + { key: 'Set-Cookie', value: '[hidden]' }, + { key: 'Content-Type', value: 'application/json' }, + ], + 'marker': '[hidden]', + 'session_id': '[hidden]', + 'url': 'https://[hidden]@example.com/context?[hidden]', + 'endpoint': 'https://example.com/callback?[hidden]', + }) +}) + +test('redacts structured key/name entries without relying on property casing', () => { + const entries = [ + { KEY: 'Authentication', VALUE: 'key secret' }, + { Name: 'X-Auth', Value: 'name secret' }, + { key: 'public-label', NAME: 'Authorization', value: 'secret selected from either marker' }, + { NAME: 'Content-Type', VALUE: 'application/json; charset=utf-8' }, + ] + + assert.deepEqual(redactSnapshotDisplayValue(entries, '[hidden]'), [ + { KEY: 'Authentication', VALUE: '[hidden]' }, + { Name: 'X-Auth', Value: '[hidden]' }, + { key: 'public-label', NAME: 'Authorization', value: '[hidden]' }, + { NAME: 'Content-Type', VALUE: 'application/json; charset=utf-8' }, + ]) +}) + +test('redacts capability path values without hiding ordinary REST paths', () => { + const redacted = redactSnapshotDisplayValue({ + slack: 'https://hooks.slack.com/services/T111/B222/capability-value', + slackGov: 'https://hooks.slack-gov.com/services/T111/B222/gov-capability-value', + discord: 'https://discord.com/api/webhooks/123456/capability-value', + telegram: 'https://api.telegram.org/bot123456:capability-value/sendMessage', + genericHook: 'https://example.com/api/hook/capability/continuation', + genericHooks: 'https://example.com/api/hooks/capability/continuation', + genericWebhook: 'https://example.com/api/webhook/capability/continuation', + genericWebhooks: 'https://example.com/api/webhooks/capability/continuation', + relativeUrl: '/api/webhooks/capability/continuation', + callbackWebhookUrl: 'https://example.com/incoming/capability-value', + nested: { + deliveryWebhook: { + options: { + target: 'https://example.com/incoming/nested-capability-value', + relativeTarget: '/incoming/nested-relative-capability-value', + }, + }, + }, + protocolRelativeUrl: '//protocol-user:protocol-pass@example.com/context', + jdbcUrl: 'jdbc:mysql://jdbc-user:jdbc-pass@example.com/database', + ordinary: 'https://example.com/api/v1/agents/42', + }, '[hidden]') + + assert.deepEqual(redacted, { + slack: 'https://hooks.slack.com/services/T111/B222/[hidden]', + slackGov: 'https://hooks.slack-gov.com/services/T111/B222/[hidden]', + discord: 'https://discord.com/api/webhooks/123456/[hidden]', + telegram: 'https://api.telegram.org/bot123456:[hidden]/sendMessage', + genericHook: 'https://example.com/api/hook/[hidden]', + genericHooks: 'https://example.com/api/hooks/[hidden]', + genericWebhook: 'https://example.com/api/webhook/[hidden]', + genericWebhooks: 'https://example.com/api/webhooks/[hidden]', + relativeUrl: '/api/webhooks/[hidden]', + callbackWebhookUrl: 'https://example.com/incoming/[hidden]', + nested: { + deliveryWebhook: { + options: { + target: 'https://example.com/incoming/[hidden]', + relativeTarget: '/incoming/[hidden]', + }, + }, + }, + protocolRelativeUrl: '//[hidden]@example.com/context', + jdbcUrl: 'jdbc:mysql://[hidden]@example.com/database', + ordinary: 'https://example.com/api/v1/agents/42', + }) +}) + +test('matches the backend sensitive key variants', () => { + for (const key of [ + 'Authentication', + 'X-Auth', + 'Proxy-Authorization', + 'Cookie', + 'Set-Cookie', + 'PHPSESSID', + 'Session-Key', + 'session_token', + 'Ocp-Apim-Subscription-Key', + ]) { + assert.equal(isSensitiveKey(key), true, `${key} should be redacted`) + } + assert.equal(isSensitiveKey('Content-Type'), false) + assert.equal(isSensitiveKey('publicKey'), false) +}) + +test('formats objects stably and maps app locale names to Intl locales', () => { + assert.equal(stablePrettyStringify({ z: 1, a: { d: 2, c: 1 } }), '{\n "a": {\n "c": 1,\n "d": 2\n },\n "z": 1\n}') + assert.equal(toIntlLocale('pt_BR'), 'pt-BR') +}) diff --git a/main/manager-mobile/src/pages/agent/components/voicePreviewUtils.mjs b/main/manager-mobile/src/pages/agent/components/voicePreviewUtils.mjs new file mode 100644 index 000000000..94f3cdd95 --- /dev/null +++ b/main/manager-mobile/src/pages/agent/components/voicePreviewUtils.mjs @@ -0,0 +1,42 @@ +/** @param {Record} voice */ +export function hasVoicePreview(voice) { + return Boolean(voice?.isClone || voice?.voiceDemo || voice?.voice_demo) +} + +export function createVoicePreviewRequestGate() { + let sequence = 0 + + return { + begin() { + sequence += 1 + return sequence + }, + invalidate() { + sequence += 1 + }, + isCurrent(requestId) { + return requestId === sequence + }, + } +} + +/** + * @param {{ id: string, isClone?: boolean, voiceDemo?: string | null }} voice + * @param {(cloneId: string) => Promise} getCloneAudioId + * @param {string} baseUrl + */ +export async function resolveVoicePreviewUrl(voice, getCloneAudioId, baseUrl) { + if (!voice?.isClone) { + return typeof voice?.voiceDemo === 'string' ? voice.voiceDemo : '' + } + if (!voice.id) { + return '' + } + + const uuid = await getCloneAudioId(voice.id) + if (!uuid) { + return '' + } + + return `${baseUrl.replace(/\/+$/, '')}/voiceClone/play/${encodeURIComponent(uuid)}` +} diff --git a/main/manager-mobile/src/pages/agent/components/voicePreviewUtils.test.mjs b/main/manager-mobile/src/pages/agent/components/voicePreviewUtils.test.mjs new file mode 100644 index 000000000..d0284d5f4 --- /dev/null +++ b/main/manager-mobile/src/pages/agent/components/voicePreviewUtils.test.mjs @@ -0,0 +1,50 @@ +/* eslint-disable test/no-import-node-test -- this zero-dependency gate intentionally uses Node's built-in runner */ +import assert from 'node:assert/strict' +import test from 'node:test' +import { createVoicePreviewRequestGate, hasVoicePreview, resolveVoicePreviewUrl } from './voicePreviewUtils.mjs' + +test('keeps normal voice previews on their direct URL', async () => { + let cloneRequestCount = 0 + const url = await resolveVoicePreviewUrl({ + id: 'normal-voice', + isClone: false, + voiceDemo: 'https://cdn.example.test/normal.wav', + }, async () => { + cloneRequestCount += 1 + return 'unused' + }, 'https://api.example.test') + + assert.equal(url, 'https://cdn.example.test/normal.wav') + assert.equal(cloneRequestCount, 0) +}) + +test('uses the clone record id to obtain and construct a temporary play URL', async () => { + let requestedCloneId = '' + const url = await resolveVoicePreviewUrl({ + id: 'clone-record-id', + isClone: true, + voiceDemo: 'provider-speaker-id-must-not-be-played', + }, async (cloneId) => { + requestedCloneId = cloneId + return 'temporary uuid' + }, 'https://api.example.test/') + + assert.equal(requestedCloneId, 'clone-record-id') + assert.equal(url, 'https://api.example.test/voiceClone/play/temporary%20uuid') +}) + +test('shows a preview control for cloned voices even without voiceDemo', () => { + assert.equal(hasVoicePreview({ id: 'clone-record-id', isClone: true }), true) + assert.equal(hasVoicePreview({ id: 'normal-voice', isClone: false, voiceDemo: '' }), false) +}) + +test('invalidates an older request when the same voice is cancelled and retried', () => { + const gate = createVoicePreviewRequestGate() + const firstRequest = gate.begin() + + gate.invalidate() + const retryRequest = gate.begin() + + assert.equal(gate.isCurrent(firstRequest), false) + assert.equal(gate.isCurrent(retryRequest), true) +}) diff --git a/main/manager-mobile/src/pages/agent/edit.vue b/main/manager-mobile/src/pages/agent/edit.vue index 502993262..ce2f90e4c 100644 --- a/main/manager-mobile/src/pages/agent/edit.vue +++ b/main/manager-mobile/src/pages/agent/edit.vue @@ -1,10 +1,14 @@ \ No newline at end of file diff --git a/main/manager-web/src/components/AddModelDialog.vue b/main/manager-web/src/components/AddModelDialog.vue index 96ab96006..6b37c63a2 100644 --- a/main/manager-web/src/components/AddModelDialog.vue +++ b/main/manager-web/src/components/AddModelDialog.vue @@ -18,8 +18,8 @@ {{ $t('modelConfigDialog.enable') }} -
- {{ $t('modelConfigDialog.setDefault') }} +
@@ -36,7 +36,7 @@ -
+
@@ -48,7 +48,6 @@
- @@ -91,8 +90,12 @@ - \ No newline at end of file diff --git a/main/manager-web/src/components/AddWisdomBodyDialog.vue b/main/manager-web/src/components/AddWisdomBodyDialog.vue index 33507fab1..b5500beca 100644 --- a/main/manager-web/src/components/AddWisdomBodyDialog.vue +++ b/main/manager-web/src/components/AddWisdomBodyDialog.vue @@ -1,12 +1,28 @@ diff --git a/main/manager-web/src/components/CustomPagination.vue b/main/manager-web/src/components/CustomPagination.vue index 3e5ed7b5f..013839a82 100644 --- a/main/manager-web/src/components/CustomPagination.vue +++ b/main/manager-web/src/components/CustomPagination.vue @@ -46,9 +46,6 @@ export default { diff --git a/main/manager-web/src/components/DeviceItem.vue b/main/manager-web/src/components/DeviceItem.vue index 5ece16c1c..425cc3378 100644 --- a/main/manager-web/src/components/DeviceItem.vue +++ b/main/manager-web/src/components/DeviceItem.vue @@ -77,7 +77,7 @@ export default { }, methods: { handleDelete() { - this.$emit('delete', this.device.agentId) + this.$emit('delete', this.device) }, handleConfigure() { this.$router.push({ path: '/role-config', query: { agentId: this.device.agentId } }); @@ -163,4 +163,4 @@ export default { .device-item-tooltip[x-placement^="bottom"] .popper__arrow { border-bottom-color: transparent !important; } - \ No newline at end of file + diff --git a/main/manager-web/src/components/DictDataDialog.vue b/main/manager-web/src/components/DictDataDialog.vue index e98c2a39f..7abed4f54 100644 --- a/main/manager-web/src/components/DictDataDialog.vue +++ b/main/manager-web/src/components/DictDataDialog.vue @@ -1,116 +1,117 @@ - \ No newline at end of file + diff --git a/main/manager-web/src/components/DictTypeDialog.vue b/main/manager-web/src/components/DictTypeDialog.vue index d04304d37..9e7ece310 100644 --- a/main/manager-web/src/components/DictTypeDialog.vue +++ b/main/manager-web/src/components/DictTypeDialog.vue @@ -1,97 +1,94 @@ - - \ No newline at end of file diff --git a/main/manager-web/src/components/FirmwareDialog.vue b/main/manager-web/src/components/FirmwareDialog.vue index 32a2f8e16..14651a2f6 100644 --- a/main/manager-web/src/components/FirmwareDialog.vue +++ b/main/manager-web/src/components/FirmwareDialog.vue @@ -2,7 +2,7 @@ - + @@ -10,7 +10,7 @@ - + - - + - \ No newline at end of file + diff --git a/main/manager-web/src/components/FunctionDialog.vue b/main/manager-web/src/components/FunctionDialog.vue index 3128dc44a..79b877184 100644 --- a/main/manager-web/src/components/FunctionDialog.vue +++ b/main/manager-web/src/components/FunctionDialog.vue @@ -656,6 +656,7 @@ export default { .drawer-footer { position: absolute; bottom: 0; + z-index: 2; width: 100%; border-top: 1px solid #e8e8e8; padding: 10px 16px; @@ -894,4 +895,4 @@ export default { padding: 10px 0; } } - \ No newline at end of file + diff --git a/main/manager-web/src/components/HeaderBar.vue b/main/manager-web/src/components/HeaderBar.vue index d446718b0..6852d225a 100644 --- a/main/manager-web/src/components/HeaderBar.vue +++ b/main/manager-web/src/components/HeaderBar.vue @@ -54,7 +54,7 @@ : 'None', }" /> {{ $t("header.voiceCloneManagement") }} - + @@ -101,7 +101,8 @@ $route.path === '/agent-template-management' || $route.path === '/ota-management' || $route.path === '/user-management' || - $route.path === '/feature-management', + $route.path === '/feature-management' || + $route.path === '/replacement-word-management' }" @visible-change="handleParamDropdownVisibleChange"> {{ $t("header.paramDictionary") }} - + @@ -154,32 +156,6 @@
-
-
- - - - -
-
- {{ $t("header.searchHistory") }} - - {{ $t("header.clearHistory") }} - -
-
-
- {{ item }} - -
-
-
-
-
- {{ userInfo.username || $t('header.loading') }} @@ -221,12 +197,6 @@ export default { voiceCloneDropdownVisible: false, userMenuVisible: false, // 添加用户菜单可见状态 menuVisibleTimer: null, // 菜单显示定时器,防止够快触发 - isSmallScreen: false, - // 搜索历史相关 - searchHistory: [], - showHistory: false, - SEARCH_HISTORY_KEY: "xiaozhi_search_history", - MAX_HISTORY_COUNT: 3, // Cascader 配置 cascaderProps: { expandTrigger: "click", @@ -312,10 +282,6 @@ export default { // 等待featureManager初始化完成后再加载功能状态 await this.loadFeatureStatus(); }, - //移除事件监听器 - beforeDestroy() { - window.removeEventListener("resize", this.checkScreenSize); - }, methods: { handleRouter(type) { this.$router.push(this.routerPaths[type]); @@ -332,104 +298,6 @@ export default { // 等待featureManager初始化完成 await featureManager.waitForInitialization(); }, - checkScreenSize() { - this.isSmallScreen = window.innerWidth <= 1386; - }, - // 处理搜索 - handleSearch() { - const searchValue = this.search.trim(); - - // 如果搜索内容为空,触发重置事件 - if (!searchValue) { - this.$emit("search-reset"); - return; - } - - // 保存搜索历史 - this.saveSearchHistory(searchValue); - - // 触发搜索事件,将搜索关键词传递给父组件 - this.$emit("search", searchValue); - - // 搜索完成后让输入框失去焦点,从而触发blur事件隐藏搜索历史 - if (this.$refs.searchInput) { - this.$refs.searchInput.blur(); - } - }, - - // 显示搜索历史 - showSearchHistory() { - this.showHistory = true; - }, - - // 隐藏搜索历史 - hideSearchHistory() { - // 延迟隐藏,以便点击事件能够执行 - setTimeout(() => { - this.showHistory = false; - }, 200); - }, - - // 加载搜索历史 - loadSearchHistory() { - try { - const history = localStorage.getItem(this.SEARCH_HISTORY_KEY); - if (history) { - this.searchHistory = JSON.parse(history); - } - } catch (error) { - console.error("加载搜索历史失败:", error); - this.searchHistory = []; - } - }, - - // 保存搜索历史 - saveSearchHistory(keyword) { - if (!keyword || this.searchHistory.includes(keyword)) { - return; - } - - // 添加到历史记录开头 - this.searchHistory.unshift(keyword); - - // 限制历史记录数量 - if (this.searchHistory.length > this.MAX_HISTORY_COUNT) { - this.searchHistory = this.searchHistory.slice(0, this.MAX_HISTORY_COUNT); - } - - // 保存到localStorage - try { - localStorage.setItem(this.SEARCH_HISTORY_KEY, JSON.stringify(this.searchHistory)); - } catch (error) { - console.error("保存搜索历史失败:", error); - } - }, - - // 选择搜索历史项 - selectSearchHistory(keyword) { - this.search = keyword; - this.handleSearch(); - }, - - // 移除单个搜索历史项 - removeSearchHistory(index) { - this.searchHistory.splice(index, 1); - try { - localStorage.setItem(this.SEARCH_HISTORY_KEY, JSON.stringify(this.searchHistory)); - } catch (error) { - console.error("更新搜索历史失败:", error); - } - }, - - // 清空所有搜索历史 - clearSearchHistory() { - this.searchHistory = []; - try { - localStorage.removeItem(this.SEARCH_HISTORY_KEY); - } catch (error) { - console.error("清空搜索历史失败:", error); - } - }, // 显示修改密码弹窗 showChangePasswordDialog() { this.isChangePasswordDialogVisible = true; @@ -592,11 +460,9 @@ export default { \ No newline at end of file diff --git a/main/manager-web/src/components/ModelEditDialog.vue b/main/manager-web/src/components/ModelEditDialog.vue index 7ef5d291f..c159cf84c 100644 --- a/main/manager-web/src/components/ModelEditDialog.vue +++ b/main/manager-web/src/components/ModelEditDialog.vue @@ -23,6 +23,7 @@
+
@@ -96,6 +97,7 @@ import Api from '@/apis/api'; export default { name: "ModelEditDialog", + components: { CustomDialog }, props: { visible: { type: Boolean, default: false }, modelData: { @@ -131,6 +133,11 @@ export default { }; }, computed: { + title() { + return this.modelData.duplicateMode + ? this.$t("modelConfigDialog.duplicateModel") + : this.$t("modelConfigDialog.editModel"); + }, chunkedCallInfoFields() { const chunkSize = 2; const result = []; @@ -155,9 +162,9 @@ export default { }, visible(val) { this.dialogVisible = val; - if (val) { - this.loadProviders(); - } + }, + dialogVisible(val) { + this.$emit("update:visible", val); }, 'form.configJson.type'(newVal) { if (newVal && this.providersLoaded) { @@ -166,6 +173,19 @@ export default { } }, methods: { + handleOpen() { + this.loadProviders(); + if (this.modelData.id) { + this.loadModelData(); + } + }, + handleClose() { + this.saving = false; + // 处理关闭弹窗闪动问题 + setTimeout(() => { + this.resetForm(); + }, 200) + }, resetForm() { this.form = { id: "", @@ -344,92 +364,57 @@ export default { - diff --git a/main/manager-web/src/components/ProviderDialog.vue b/main/manager-web/src/components/ProviderDialog.vue index 0954b3997..2c7e27ad5 100644 --- a/main/manager-web/src/components/ProviderDialog.vue +++ b/main/manager-web/src/components/ProviderDialog.vue @@ -1,56 +1,55 @@ - \ No newline at end of file diff --git a/main/manager-web/src/components/ReplacementWordDialog.vue b/main/manager-web/src/components/ReplacementWordDialog.vue index 596118115..d61ef7357 100644 --- a/main/manager-web/src/components/ReplacementWordDialog.vue +++ b/main/manager-web/src/components/ReplacementWordDialog.vue @@ -1,76 +1,67 @@ - - diff --git a/main/manager-web/src/components/TtsAdvancedSettings.vue b/main/manager-web/src/components/TtsAdvancedSettings.vue index f24cc59d2..597ab7c5b 100644 --- a/main/manager-web/src/components/TtsAdvancedSettings.vue +++ b/main/manager-web/src/components/TtsAdvancedSettings.vue @@ -25,6 +25,7 @@ :step="1" :format-tooltip="formatTooltip" class="tts-slider" + @change="markTtsSettingChanged('volume')" /> {{ $t('roleConfig.volumeHint') }} @@ -40,6 +41,7 @@ :step="1" :format-tooltip="formatTooltip" class="tts-slider" + @change="markTtsSettingChanged('speed')" /> {{ $t('roleConfig.speedHint') }} @@ -55,6 +57,7 @@ :step="1" :format-tooltip="formatTooltip" class="tts-slider" + @change="markTtsSettingChanged('pitch')" /> {{ $t('roleConfig.pitchHint') }} @@ -72,6 +75,8 @@ @@ -122,6 +127,11 @@ export default { speed: 0, pitch: 0, }, + changedTtsFields: { + volume: false, + speed: false, + pitch: false, + }, replacementWordIds: [], replacementWordList: [] }; @@ -141,6 +151,11 @@ export default { if (newVal) { // 当抽屉打开时,复制当前设置到本地 this.localSettings = { ...this.settings }; + this.changedTtsFields = { + volume: false, + speed: false, + pitch: false, + }; this.replacementWordIds = [...this.checkedReplacementWordIds]; this.fetchReplacementWordList(); } @@ -156,9 +171,18 @@ export default { }, handleSave() { // 保存设置并关闭 - this.$emit('save', { ...this.localSettings, replacementWordIds: this.replacementWordIds }); + const changedTtsFields = Object.keys(this.changedTtsFields) + .filter((field) => this.changedTtsFields[field]); + this.$emit('save', { + ...this.localSettings, + changedTtsFields, + replacementWordIds: this.replacementWordIds + }); this.handleClose(); }, + markTtsSettingChanged(field) { + this.$set(this.changedTtsFields, field, true); + }, formatTooltip(val) { return `${val}%`; }, diff --git a/main/manager-web/src/components/TtsModel.vue b/main/manager-web/src/components/TtsModel.vue index b1571864d..763d52f38 100644 --- a/main/manager-web/src/components/TtsModel.vue +++ b/main/manager-web/src/components/TtsModel.vue @@ -1,9 +1,7 @@ diff --git a/main/manager-web/src/components/VoicePrintDialog.vue b/main/manager-web/src/components/VoicePrintDialog.vue index c25f702f5..021bef5ae 100644 --- a/main/manager-web/src/components/VoicePrintDialog.vue +++ b/main/manager-web/src/components/VoicePrintDialog.vue @@ -1,55 +1,43 @@ - - diff --git a/main/manager-web/src/components/VoiceResourceDialog.vue b/main/manager-web/src/components/VoiceResourceDialog.vue index 9fced5dd9..e2cd96f9d 100644 --- a/main/manager-web/src/components/VoiceResourceDialog.vue +++ b/main/manager-web/src/components/VoiceResourceDialog.vue @@ -1,7 +1,15 @@ - - diff --git a/main/manager-web/src/components/agentSnapshotDisplayUtils.mjs b/main/manager-web/src/components/agentSnapshotDisplayUtils.mjs new file mode 100644 index 000000000..7e292533b --- /dev/null +++ b/main/manager-web/src/components/agentSnapshotDisplayUtils.mjs @@ -0,0 +1,186 @@ +export const SNAPSHOT_SECRET_REDACTED = "__SNAPSHOT_SECRET_REDACTED__"; + +export function hasValidCurrentStateToken(value) { + return typeof value === "string" && value.trim().length > 0; +} + +export function redactSnapshotDisplayValue(value, redactedLabel, parentKey = "") { + if (value === SNAPSHOT_SECRET_REDACTED || isSensitiveSnapshotKey(parentKey)) { + return redactedLabel; + } + if (Array.isArray(value)) { + return value.map((item) => redactSnapshotDisplayValue(item, redactedLabel, parentKey)); + } + if (isPlainObject(value)) { + const sensitiveEntry = Object.keys(value).some((key) => { + const normalizedKey = key.toLowerCase(); + return (normalizedKey === "key" || normalizedKey === "name") + && typeof value[key] === "string" + && isSensitiveSnapshotKey(value[key]); + }); + return Object.keys(value).reduce((result, key) => { + const semanticKey = resolveUrlSemanticKey(parentKey, key); + if (sensitiveEntry && key.toLowerCase() === "value") { + result[key] = redactedLabel; + } else { + result[key] = redactSnapshotDisplayValue(value[key], redactedLabel, semanticKey); + } + return result; + }, {}); + } + if (typeof value === "string" && isSnapshotUrlValue(parentKey, value)) { + return redactSnapshotUrl(value, redactedLabel, parentKey); + } + return value; +} + +export function normalizeSnapshotOrderedValue(value) { + if (Array.isArray(value)) { + return value.map((item) => normalizeSnapshotOrderedValue(item)); + } + if (isPlainObject(value)) { + return Object.keys(value).sort().reduce((result, key) => { + result[key] = normalizeSnapshotOrderedValue(value[key]); + return result; + }, {}); + } + return value === undefined ? null : value; +} + +export function isSensitiveSnapshotKey(key) { + const normalized = String(key || "").toLowerCase().replace(/[^a-z0-9]/g, ""); + return normalized === "authorization" + || normalized.includes("authorization") + || normalized.includes("authentication") + || normalized === "auth" + || normalized.endsWith("auth") + || normalized === "cookie" + || normalized === "cookie2" + || normalized === "setcookie" + || normalized === "setcookie2" + || normalized.endsWith("cookie") + || normalized === "session" + || normalized.endsWith("session") + || normalized.includes("sessionid") + || normalized.includes("sessionkey") + || normalized.includes("sessiontoken") + || normalized.includes("sessioncookie") + || normalized.endsWith("sessid") + || normalized === "token" + || normalized.endsWith("token") + || normalized.includes("apikey") + || normalized.includes("appkey") + || normalized.includes("accesskey") + || normalized.includes("subscriptionkey") + || normalized.includes("privatekey") + || normalized.includes("password") + || normalized.includes("passwd") + || normalized.includes("secret") + || normalized.includes("credential"); +} + +function isSnapshotUrlValue(parentKey, value) { + const normalizedKey = String(parentKey || "").toLowerCase().replace(/[^a-z0-9]/g, ""); + return normalizedKey.includes("url") + || normalizedKey.endsWith("uri") + || normalizedKey.includes("endpoint") + || normalizedKey.includes("webhook") + || /^(?:[a-z][a-z0-9+.-]*:)*\/\//i.test(value); +} + +function resolveUrlSemanticKey(parentKey, childKey) { + if (isWebhookSemanticKey(childKey)) { + return childKey; + } + if (isWebhookSemanticKey(parentKey)) { + return childKey ? `${parentKey}.${childKey}` : parentKey; + } + return childKey; +} + +function isWebhookSemanticKey(value) { + const normalized = String(value || "").toLowerCase().replace(/[^a-z0-9]/g, ""); + return normalized.includes("webhook") + || normalized === "hook" + || normalized === "hooks" + || normalized.endsWith("hook") + || normalized.endsWith("hooks"); +} + +function redactSnapshotUrl(value, redactedLabel, parentKey) { + const withoutCredentials = value.replace( + /^((?:[a-z][a-z0-9+.-]*:)*\/\/)([^/?#\s]*@)/i, + (match, prefix) => `${prefix}${redactedLabel}@` + ); + const suffixIndex = withoutCredentials.search(/[?#]/); + const base = suffixIndex < 0 ? withoutCredentials : withoutCredentials.slice(0, suffixIndex); + const redactedBase = redactSnapshotCapabilityPath(base, redactedLabel, parentKey); + return suffixIndex < 0 + ? redactedBase + : `${redactedBase}${withoutCredentials[suffixIndex]}${redactedLabel}`; +} + +function redactSnapshotCapabilityPath(value, redactedLabel, parentKey) { + const absoluteUrl = value.match(/^((?:[a-z][a-z0-9+.-]*:)*\/\/)([^/?#]*)([^?#]*)$/i); + if (!absoluteUrl) { + return redactGenericCapabilityPath(value, redactedLabel, parentKey); + } + + const [, scheme, authority, path = ""] = absoluteUrl; + const hostWithPort = authority.slice(authority.lastIndexOf("@") + 1); + const host = hostWithPort.replace(/:\d+$/, "").toLowerCase(); + let redactedPath = path; + let providerMatched = false; + + if (host === "hooks.slack.com" || host === "hooks.slack-gov.com") { + redactedPath = redactedPath.replace( + /^(\/services\/[^/]+\/[^/]+\/)([^/]+)(.*)$/i, + (match, prefix, secret, suffix) => `${prefix}${redactedLabel}${suffix}` + ); + providerMatched = redactedPath !== path; + } else if ( + host === "discord.com" + || host.endsWith(".discord.com") + || host === "discordapp.com" + || host.endsWith(".discordapp.com") + ) { + redactedPath = redactedPath.replace( + /^(\/api(?:\/v\d+)?\/webhooks\/[^/]+\/)([^/]+)(.*)$/i, + (match, prefix, secret, suffix) => `${prefix}${redactedLabel}${suffix}` + ); + providerMatched = redactedPath !== path; + } else if (host === "api.telegram.org") { + redactedPath = redactedPath.replace( + /^((?:\/file)?\/bot[^/:]+:)([^/]+)(.*)$/i, + (match, prefix, secret, suffix) => `${prefix}${redactedLabel}${suffix}` + ); + providerMatched = redactedPath !== path; + } + + if (!providerMatched) { + redactedPath = redactGenericCapabilityPath(redactedPath, redactedLabel, parentKey); + } + + return `${scheme}${authority}${redactedPath}`; +} + +function redactGenericCapabilityPath(path, redactedLabel, parentKey) { + const markerRedacted = path.replace( + /(^|\/)(webhooks?|hooks?)(\/)(.+)$/i, + (match, boundary, marker, separator) => `${boundary}${marker}${separator}${redactedLabel}` + ); + if (markerRedacted !== path) { + return markerRedacted; + } + if (!isWebhookSemanticKey(parentKey)) { + return path; + } + return path.replace( + /^(.*\/)([^/]+)(\/?)$/, + (match, prefix, secret, suffix) => `${prefix}${redactedLabel}${suffix}` + ); +} + +function isPlainObject(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} diff --git a/main/manager-web/src/components/agentSnapshotDisplayUtils.test.mjs b/main/manager-web/src/components/agentSnapshotDisplayUtils.test.mjs new file mode 100644 index 000000000..d7277445e --- /dev/null +++ b/main/manager-web/src/components/agentSnapshotDisplayUtils.test.mjs @@ -0,0 +1,155 @@ +/* eslint-disable test/no-import-node-test -- zero-dependency security regression gate */ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + hasValidCurrentStateToken, + normalizeSnapshotOrderedValue, + redactSnapshotDisplayValue, + SNAPSHOT_SECRET_REDACTED +} from "./agentSnapshotDisplayUtils.mjs"; + +test("accepts only non-empty opaque current-state tokens", () => { + assert.equal(hasValidCurrentStateToken("state-token"), true); + assert.equal(hasValidCurrentStateToken(" state-token "), true); + assert.equal(hasValidCurrentStateToken(""), false); + assert.equal(hasValidCurrentStateToken(" "), false); + assert.equal(hasValidCurrentStateToken(null), false); + assert.equal(hasValidCurrentStateToken(123), false); +}); + +test("redacts nested credentials without hiding non-sensitive display values", () => { + const redacted = redactSnapshotDisplayValue({ + apiKey: "api-secret", + headers: [ + { key: "Authorization", value: "Bearer secret" }, + { key: "Proxy-Authorization", value: "Basic secret" }, + { key: "Set-Cookie", value: "session=secret" }, + { key: "Content-Type", value: "application/json" } + ], + marker: SNAPSHOT_SECRET_REDACTED, + session_id: "session-secret", + url: "https://user:pass@example.com/context?access_token=secret#fragment", + visible: "kept" + }, "[hidden]"); + + assert.deepEqual(redacted, { + apiKey: "[hidden]", + headers: [ + { key: "Authorization", value: "[hidden]" }, + { key: "Proxy-Authorization", value: "[hidden]" }, + { key: "Set-Cookie", value: "[hidden]" }, + { key: "Content-Type", value: "application/json" } + ], + marker: "[hidden]", + session_id: "[hidden]", + url: "https://[hidden]@example.com/context?[hidden]", + visible: "kept" + }); +}); + +test("uses a function parameter key when redacting scalar plugin values", () => { + assert.equal(redactSnapshotDisplayValue("secret", "[hidden]", "clientSecret"), "[hidden]"); + assert.equal(redactSnapshotDisplayValue("secret", "[hidden]", "Ocp-Apim-Subscription-Key"), "[hidden]"); + assert.equal(redactSnapshotDisplayValue("public", "[hidden]", "clientId"), "public"); +}); + +test("redacts mixed-case name/value credential entries", () => { + assert.deepEqual(redactSnapshotDisplayValue({ + headers: [ + { NAME: "Authorization", VALUE: "Bearer live-secret" }, + { NaMe: "Content-Type", VaLuE: "application/json" } + ] + }, "[hidden]"), { + headers: [ + { NAME: "Authorization", VALUE: "[hidden]" }, + { NaMe: "Content-Type", VaLuE: "application/json" } + ] + }); +}); + +test("redacts capability URL path secrets while preserving public route identity", () => { + const redacted = redactSnapshotDisplayValue({ + slackUrl: "https://hooks.slack.com/services/T00000000/B00000000/slack-secret", + slackGovUrl: "https://hooks.slack-gov.com/services/T00000000/B00000000/slack-gov-secret", + discordEndpoint: "https://discord.com/api/webhooks/123456789/discord-secret", + telegramUri: "https://api.telegram.org/bot123456789:telegram-secret/sendMessage", + telegramFileUri: "https://api.telegram.org/file/bot123456789:telegram-file-secret/documents/file.txt", + callbackUrl: "https://events.example.com/api/webhook/generic-secret/delivery", + hooksEndpoint: "https://events.example.com/v1/hooks/hook-secret/status", + hookEndpoint: "https://events.example.com/v1/hook/singular-secret/status", + webhooksEndpoint: "https://events.example.com/v1/webhooks/plural-secret/status", + relativeUrl: "/api/webhooks/relative-secret/continuation", + nested: { + deliveryWebhook: { + options: { + target: "https://events.example.com/incoming/nested-secret", + relativeTarget: "/incoming/nested-relative-secret" + } + } + }, + protocolRelativeUrl: "//protocol-user:protocol-pass@example.com/context", + jdbcUrl: "jdbc:mysql://jdbc-user:jdbc-pass@example.com/database", + webhook: "https://capability.example.com/public-prefix/key-secret", + restUrl: "https://api.example.com/v1/users/customer-123", + similarMarkerUrl: "https://api.example.com/v1/webhook-settings/public-value" + }, "[hidden]"); + + assert.deepEqual(redacted, { + slackUrl: "https://hooks.slack.com/services/T00000000/B00000000/[hidden]", + slackGovUrl: "https://hooks.slack-gov.com/services/T00000000/B00000000/[hidden]", + discordEndpoint: "https://discord.com/api/webhooks/123456789/[hidden]", + telegramUri: "https://api.telegram.org/bot123456789:[hidden]/sendMessage", + telegramFileUri: "https://api.telegram.org/file/bot123456789:[hidden]/documents/file.txt", + callbackUrl: "https://events.example.com/api/webhook/[hidden]", + hooksEndpoint: "https://events.example.com/v1/hooks/[hidden]", + hookEndpoint: "https://events.example.com/v1/hook/[hidden]", + webhooksEndpoint: "https://events.example.com/v1/webhooks/[hidden]", + relativeUrl: "/api/webhooks/[hidden]", + nested: { + deliveryWebhook: { + options: { + target: "https://events.example.com/incoming/[hidden]", + relativeTarget: "/incoming/[hidden]" + } + } + }, + protocolRelativeUrl: "//[hidden]@example.com/context", + jdbcUrl: "jdbc:mysql://[hidden]@example.com/database", + webhook: "https://capability.example.com/public-prefix/[hidden]", + restUrl: "https://api.example.com/v1/users/customer-123", + similarMarkerUrl: "https://api.example.com/v1/webhook-settings/public-value" + }); + assert.equal(JSON.stringify(redacted).includes("slack-secret"), false); + assert.equal(JSON.stringify(redacted).includes("slack-gov-secret"), false); + assert.equal(JSON.stringify(redacted).includes("discord-secret"), false); + assert.equal(JSON.stringify(redacted).includes("telegram-secret"), false); + assert.equal(JSON.stringify(redacted).includes("telegram-file-secret"), false); + assert.equal(JSON.stringify(redacted).includes("generic-secret"), false); + assert.equal(JSON.stringify(redacted).includes("hook-secret"), false); + assert.equal(JSON.stringify(redacted).includes("singular-secret"), false); + assert.equal(JSON.stringify(redacted).includes("plural-secret"), false); + assert.equal(JSON.stringify(redacted).includes("relative-secret"), false); + assert.equal(JSON.stringify(redacted).includes("nested-secret"), false); + assert.equal(JSON.stringify(redacted).includes("key-secret"), false); +}); + +test("normalizes object keys without erasing ordered-list changes", () => { + const before = [ + { url: "https://first.example", headers: { Zeta: "2", Accept: "json" } }, + { url: "https://second.example" } + ]; + const sameOrder = [ + { headers: { Accept: "json", Zeta: "2" }, url: "https://first.example" }, + { url: "https://second.example" } + ]; + const reversed = [...sameOrder].reverse(); + + assert.deepEqual( + normalizeSnapshotOrderedValue(before), + normalizeSnapshotOrderedValue(sameOrder) + ); + assert.notDeepEqual( + normalizeSnapshotOrderedValue(before), + normalizeSnapshotOrderedValue(reversed) + ); +}); diff --git a/main/manager-web/src/i18n/de.js b/main/manager-web/src/i18n/de.js index 21a8ee9fa..3b104cd4a 100644 --- a/main/manager-web/src/i18n/de.js +++ b/main/manager-web/src/i18n/de.js @@ -353,6 +353,8 @@ export default { // Replacement word management page related 'replacementWordManagement.pageTitle': 'Ersetzungswortverwaltung', + 'replacementWordManagement.searchPlaceholder': 'Bitte geben Sie den Dateinamen zur Suche ein', + 'replacementWordManagement.search': 'Suchen', 'replacementWordManagement.fileName': 'Dateiname', 'replacementWordManagement.replacementWordCount': 'Anzahl der Ersetzungswörter', 'replacementWordManagement.replacementWordContent': 'Ersetzungswortinhalt', @@ -476,8 +478,8 @@ export default { 'device.type': 'Gerätetyp', 'device.status': 'Gerätestatus', 'device.dialogTitle': 'Gerät hinzufügen', - 'device.verificationCode': 'Bestätigungscode:', - 'device.verificationCodePlaceholder': 'Bitte den 6-stelligen Bestätigungscode eingeben, der vom Gerät gesendet wird..', + 'device.verificationCode': 'Bestätigungscode', + 'device.verificationCodePlaceholder': 'Bitte den 6-stelligen Bestätigungscode eingeben, der vom Gerät gesendet wird…', 'device.confirmButton': 'Bestätigen', 'device.cancelButton': 'Abbrechen', 'device.input6DigitCode': 'Bitte 6-stelligen Bestätigungscode eingeben', @@ -489,7 +491,7 @@ export default { 'device.firmwareVersion': 'Firmware-Version', 'device.bindTime': 'Bindungszeit', 'device.lastConversation': 'Letzte Konversation', - 'device.remark': 'Bemerkung', + 'device.alias': 'Gerätealias', 'device.autoUpdate': 'Automatische Aktualisierung', 'device.operation': 'Operation', 'device.search': 'Suchen', @@ -504,9 +506,9 @@ export default { 'device.confirmBatchUnbind': 'Sind Sie sicher, dass Sie {count} ausgewählte Geräte entbinden möchten?', 'device.batchUnbindSuccess': 'Erfolgreich {count} Geräte entbunden', 'device.batchUnbindError': 'Fehler beim Massen-Entbinden aufgetreten', - 'device.remarkTooLong': 'Bemerkung darf 64 Zeichen nicht überschreiten', - 'device.remarkSaved': 'Bemerkung erfolgreich gespeichert', - 'device.remarkSaveFailed': 'Speichern der Bemerkung fehlgeschlagen', + 'device.aliasTooLong': 'Gerätealias darf 64 Zeichen nicht überschreiten', + 'device.aliasSaved': 'Gerätealias erfolgreich gespeichert', + 'device.aliasSaveFailed': 'Speichern des Gerätealias fehlgeschlagen', 'device.confirmUnbind': 'Sind Sie sicher, dass Sie dieses Gerät entbinden möchten?', 'device.unbindSuccess': 'Gerät erfolgreich entbunden', 'device.unbindFailed': 'Entbinden des Geräts fehlgeschlagen', @@ -592,6 +594,7 @@ export default { // Dictionary management page text 'dictManagement.pageTitle': 'Wörterbuchverwaltung', + 'dictManagement.dictTypeCategory': 'Wörterbuchkategorie', 'dictManagement.searchPlaceholder': 'Bitte Wörterbuchwert-Label zur Suche eingeben', 'dictManagement.search': 'Suchen', 'dictManagement.dictTypeName': 'WDT-Name', @@ -646,6 +649,8 @@ export default { 'user.disable': 'Deaktivieren', 'user.delete': 'Löschen', 'user.selectUsersFirst': 'Bitte wählen Sie zuerst Benutzer zum Löschen aus', + 'user.selectUsersToDisable': 'Bitte wählen Sie Benutzer zum Deaktivieren aus', + 'user.selectUsersToEnable': 'Bitte wählen Sie Benutzer zum Aktivieren aus', 'user.confirmDeleteSelected': 'Sind Sie sicher, dass Sie {count} ausgewählte Benutzer löschen möchten?', 'user.deleting': 'Löscht...', 'user.deleteSuccess': 'Erfolgreich {count} Benutzer gelöscht', @@ -705,6 +710,9 @@ export default { 'common.cancel': 'Abbrechen', 'common.sensitive': 'Sensibel', 'common.loading': 'Lädt', + 'common.copySuccess': 'Erfolgreich kopiert', + 'common.copyFailed': 'Kopieren fehlgeschlagen', + 'common.copyAddress': 'Adresse kopieren', // Language switch 'language.en': 'English', @@ -727,7 +735,12 @@ export default { 'home.justNow': 'Gerade eben', 'home.minutesAgo': 'Vor {minutes} Minuten', 'home.hoursAgo': 'Vor {hours} Stunden {minutes} Minuten', - 'home.confirmDeleteAgent': 'Sind Sie sicher, dass Sie diesen Agenten löschen möchten?', + 'home.deleteConfirmTitle': 'Agent löschen', + 'home.confirmDeleteAgent': 'Das Löschen kann nicht rückgängig gemacht werden. Geben Sie den Agentennamen "{agentName}" ein, um zu bestätigen.', + 'home.deleteAgentNamePlaceholder': 'Agentennamen eingeben', + 'home.deleteAgentNameMismatch': 'Der Agentenname stimmt nicht überein', + 'home.deleteAgentPasteForbidden': 'Bitte geben Sie den Agentennamen manuell ein. Einfügen ist nicht erlaubt.', + 'home.deleteAgentMissingInfo': 'Agenteninformationen konnten nicht bestätigt werden. Bitte aktualisieren und erneut versuchen.', 'home.deleteSuccess': 'Löschen erfolgreich', 'home.deleteFailed': 'Löschen fehlgeschlagen', 'home.enableMemory': 'Bitte aktivieren Sie zuerst den Speicher auf der \"Rolle konfigurieren\" Seite', @@ -738,8 +751,10 @@ export default { 'paramManagement.search': 'Suchen', 'paramManagement.paramCode': 'Parameter-Code', 'paramManagement.paramValue': 'Parameter-Wert', + 'paramManagement.valueType': 'Typ', 'paramManagement.remark': 'Bemerkung', 'paramManagement.operation': 'Operation', + 'paramManagement.select': 'Auswahl', 'paramManagement.hide': 'Ausblenden', 'paramManagement.view': 'Anzeigen', 'paramManagement.deselectAll': 'Alle abwählen', @@ -747,11 +762,29 @@ export default { 'paramManagement.add': 'Hinzufügen', 'paramManagement.delete': 'Löschen', 'paramManagement.edit': 'Bearbeiten', + 'paramManagement.refresh': 'Aktualisieren', 'paramManagement.itemsPerPage': 'Einträge/Seite', 'paramManagement.firstPage': 'Erste Seite', 'paramManagement.prevPage': 'Vorherige Seite', 'paramManagement.nextPage': 'Nächste Seite', - 'paramManagement.totalRecords': 'Insgesamt {total} Datensätze', + 'paramManagement.totalRecords': '{total} insgesamt', + 'paramManagement.selectedCount': '{count} ausgewählt', + 'paramManagement.groupHint': 'Nach Namespace gruppiert', + 'paramManagement.emptyResult': 'Keine passenden Parameter', + 'paramManagement.group.all': 'Alle', + 'paramManagement.group.server': 'Server', + 'paramManagement.group.plugins': 'Plugins', + 'paramManagement.group.log': 'Logging', + 'paramManagement.group.session': 'Sitzung', + 'paramManagement.group.general': 'Allgemein', + 'paramManagement.subgroup.root': 'Basis', + 'paramManagement.subgroup.auth': 'Auth', + 'paramManagement.subgroup.connection': 'Verbindung', + 'paramManagement.subgroup.registry': 'Registry', + 'paramManagement.subgroup.resilience': 'Resilience', + 'paramManagement.subgroup.metrics': 'Metriken', + 'paramManagement.subgroup.tracing': 'Tracing', + 'paramManagement.subgroup.plugin': 'Plugin · {name}', 'paramManagement.addParam': 'Parameter hinzufügen', 'paramManagement.editParam': 'Parameter bearbeiten', 'paramManagement.getParamsListFailed': 'Parameterliste konnte nicht abgerufen werden', @@ -786,7 +819,7 @@ export default { // Add agent dialog text 'addAgentDialog.title': 'Agent hinzufügen', 'addAgentDialog.agentName': 'Agent-Name', - 'addAgentDialog.placeholder': 'Bitte Agent-Namen eingeben..', + 'addAgentDialog.placeholder': 'Bitte Agent-Namen eingeben…', 'addAgentDialog.confirm': 'Bestätigen', 'addAgentDialog.cancel': 'Abbrechen', 'addAgentDialog.nameRequired': 'Bitte Agent-Namen eingeben', @@ -797,12 +830,129 @@ export default { 'roleConfig.addTag': 'Neues Label hinzufügen', 'roleConfig.restartNotice': 'Neustart nach Konfigurationsspeichern zur Aktivierung.', 'roleConfig.saveConfig': 'Konfiguration speichern', + 'roleConfig.snapshotHistory': 'Versionsverlauf', + 'roleConfig.currentVersion': 'Aktuelle Version {version}', + 'roleConfig.functionName': 'Funktionsname', 'roleConfig.reset': 'Zurücksetzen', 'roleConfig.agentName': 'Spitzname', 'roleConfig.roleTemplate': 'Vorlage', 'roleConfig.roleIntroduction': 'Einführung', 'roleConfig.languageCode': 'Sprachcode', 'roleConfig.interactionLanguage': 'Interaktionssprache', + 'agentSnapshot.title': 'Versionsverlauf', + 'agentSnapshot.empty': 'Noch keine Versionen', + 'agentSnapshot.version': 'Version', + 'agentSnapshot.createdAt': 'Gespeichert am', + 'agentSnapshot.source': 'Quelle', + 'agentSnapshot.changedFields': 'Änderungen', + 'agentSnapshot.actions': 'Aktionen', + 'agentSnapshot.view': 'Anzeigen', + 'agentSnapshot.restore': 'Wiederherstellen', + 'agentSnapshot.delete': 'Löschen', + 'agentSnapshot.detailTitle': 'Änderungsdetails', + 'agentSnapshot.restorePreviewTitle': 'Wiederherstellungsvorschau', + 'agentSnapshot.confirmRestore': 'Wiederherstellung bestätigen', + 'agentSnapshot.before': 'Vorher', + 'agentSnapshot.after': 'Nachher', + 'agentSnapshot.emptyValue': 'Keine', + 'agentSnapshot.secretRedacted': 'Geheimer Schlüssel maskiert', + 'agentSnapshot.configValue': 'Konfigurationswert', + 'agentSnapshot.noChangedContent': 'Keine anzeigbaren Änderungen', + 'agentSnapshot.noFunctionChange': 'Keine Funktionsänderungen', + 'agentSnapshot.beforeChange': 'Vor der Änderung', + 'agentSnapshot.afterChange': 'Nach der Änderung', + 'agentSnapshot.beforeRestore': 'Vor der Wiederherstellung', + 'agentSnapshot.afterRestore': 'Nach der Wiederherstellung', + 'agentSnapshot.restoreMemoryWarning': 'Beim Wiederherstellen einer Version ohne Speicher wird der Chatverlauf dieses Agenten gelöscht. Fahren Sie nur fort, wenn Sie dieses Risiko bestätigt haben.', + 'agentSnapshot.restoreMemoryDestructiveWarning': 'Diese Wiederherstellung löscht den bestehenden Chatverlauf dieses Agenten dauerhaft. Chatverläufe sind nicht in Konfigurations-Snapshots enthalten und können nicht über den Versionsverlauf wiederhergestellt werden.', + 'agentSnapshot.unsavedChangesWarning': 'Nicht gespeicherte Änderungen auf dieser Seite werden nicht in den Verlauf übernommen und nach der Wiederherstellung verworfen.', + 'agentSnapshot.restoreConfirm': 'Version {version} wiederherstellen? Die aktuelle Konfiguration bleibt im Verlauf erhalten.', + 'agentSnapshot.restoreSuccess': 'Version wurde wiederhergestellt', + 'agentSnapshot.restoreFailed': 'Version konnte nicht wiederhergestellt werden', + 'agentSnapshot.restoreFailedRollback': 'Version konnte nicht wiederhergestellt werden. Die Transaktion wurde zurueckgerollt und die aktuelle Konfiguration wurde nicht geaendert', + 'agentSnapshot.deleteConfirm': 'Version {version} löschen? Dies kann nicht rückgängig gemacht werden.', + 'agentSnapshot.deleteSuccess': 'Verlaufsversion gelöscht', + 'agentSnapshot.deleteFailed': 'Verlaufsversion konnte nicht gelöscht werden', + 'agentSnapshot.fetchFailed': 'Versionsverlauf konnte nicht abgerufen werden', + 'agentSnapshot.detailFailed': 'Snapshot-Details konnten nicht abgerufen werden', + 'agentSnapshot.currentVersion': 'Neuester Snapshot', + 'agentSnapshot.source.config': 'Konfiguration gespeichert', + 'agentSnapshot.source.current': 'Aktuelle Konfiguration', + 'agentSnapshot.source.restore': 'Wiederherstellungsergebnis', + 'agentSnapshot.source.initial': 'Initialversion', + 'agentSnapshot.field.restore': 'Wiederherstellung', + 'agentSnapshot.field.initial': 'Initialer Snapshot', + 'agentSnapshot.field.agentCode': 'Agent-Code', + 'agentSnapshot.field.agentName': 'Spitzname', + 'agentSnapshot.field.asrModelId': 'Spracherkennung', + 'agentSnapshot.field.vadModelId': 'Sprachaktivitätserkennung', + 'agentSnapshot.field.llmModelId': 'Hauptsprachmodell', + 'agentSnapshot.field.slmModelId': 'Kleines Sprachmodell', + 'agentSnapshot.field.vllmModelId': 'Vision-Modell', + 'agentSnapshot.field.ttsModelId': 'Text-zu-Sprache', + 'agentSnapshot.field.ttsVoiceId': 'Stimme', + 'agentSnapshot.field.ttsLanguage': 'Sprache', + 'agentSnapshot.field.ttsVolume': 'Lautstärke', + 'agentSnapshot.field.ttsRate': 'Geschwindigkeit', + 'agentSnapshot.field.ttsPitch': 'Tonhöhe', + 'agentSnapshot.field.memModelId': 'Speichermodell', + 'agentSnapshot.field.intentModelId': 'Absichtserkennung', + 'agentSnapshot.field.chatHistoryConf': 'Chatverlauf', + 'agentSnapshot.field.systemPrompt': 'Einführung', + 'agentSnapshot.field.summaryMemory': 'Speicher', + 'agentSnapshot.field.langCode': 'Sprachcode', + 'agentSnapshot.field.language': 'Interaktionssprache', + 'agentSnapshot.field.sort': 'Sortierung', + 'agentSnapshot.field.functions': 'Funktionen', + 'agentSnapshot.field.contextProviders': 'Kontextquellen', + 'agentSnapshot.field.correctWordFileIds': 'Ersatzwörter', + 'agentSnapshot.field.tagNames': 'Labels', + 'agentSnapshot.field.tagIds': 'Label-IDs', + 'agentSnapshot.function.added': 'Aktiviert', + 'agentSnapshot.function.removed': 'Deaktiviert', + 'agentSnapshot.function.updated': 'Parameter geändert', + 'agentSnapshot.function.enabled': 'Aktiviert', + 'agentSnapshot.function.disabled': 'Deaktiviert', + 'agentSnapshot.function.disabledNote': 'Diese Funktion ist deaktiviert', + 'agentSnapshot.function.noParams': 'Keine Parameter erforderlich', + 'agentSnapshot.chatHistoryConf.none': 'Chatverlauf nicht aufzeichnen', + 'agentSnapshot.chatHistoryConf.text': 'Text melden', + 'agentSnapshot.chatHistoryConf.textVoice': 'Text und Sprache melden', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_WEATHER': 'Wetter', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_MUSIC': 'Server-Musikplayer', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_NEWS_CHINANEWS': 'China News', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_NEWS_NEWSNOW': 'NewsNow-Aggregation', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_HA_STATE': 'HomeAssistant-Gerätesteuerung', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_HA_PLAY_MUSIC': 'HomeAssistant-Musikplayer', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_WEB_SEARCH': 'Websuche', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_CALL_DEVICE': 'Geräteanruf', + 'agentSnapshot.pluginField.url': 'Endpunkt-URL', + 'agentSnapshot.pluginField.news_sources': 'Nachrichtenquellen', + 'agentSnapshot.pluginField.default_rss_url': 'Standard-RSS-URL', + 'agentSnapshot.pluginField.society_rss_url': 'RSS-URL für Gesellschaft', + 'agentSnapshot.pluginField.world_rss_url': 'RSS-URL für Welt', + 'agentSnapshot.pluginField.finance_rss_url': 'RSS-URL für Finanzen', + 'agentSnapshot.pluginField.api_key': 'API-Schlüssel', + 'agentSnapshot.pluginField.default_location': 'Standardstadt', + 'agentSnapshot.pluginField.api_host': 'Entwickler-API-Host', + 'agentSnapshot.pluginField.base_url': 'Server-URL', + 'agentSnapshot.pluginField.devices': 'Geräte', + 'agentSnapshot.pluginField.provider': 'Suchanbieter', + 'agentSnapshot.pluginField.description': 'Werkzeugbeschreibung', + 'agentSnapshot.pluginField.max_results': 'Ergebnisanzahl', + 'agentSnapshot.model.Memory_nomem': 'Kein Speicher', + 'agentSnapshot.model.Memory_mem_local_short': 'Lokaler Kurzzeitspeicher', + 'agentSnapshot.model.Memory_mem0ai': 'Mem0AI-Speicher', + 'agentSnapshot.model.Memory_mem_report_only': 'Nur melden', + 'agentSnapshot.model.Intent_nointent': 'Keine Absichtserkennung', + 'agentSnapshot.model.Intent_intent_llm': 'Externe LLM-Absichtserkennung', + 'agentSnapshot.model.Intent_function_call': 'LLM-Funktionsaufruf', + 'agentSnapshot.voice.TTS_EdgeTTS0001': 'EdgeTTS weiblich - Xiaoxiao', + 'agentSnapshot.voice.TTS_EdgeTTS0002': 'EdgeTTS männlich - Yunyang', + 'agentSnapshot.voice.TTS_EdgeTTS0003': 'EdgeTTS weiblich - Xiaoyi', + 'agentSnapshot.voice.TTS_EdgeTTS0004': 'EdgeTTS männlich - Yunjian', + 'agentSnapshot.voice.TTS_EdgeTTS0005': 'EdgeTTS männlich - Yunxi', + 'agentSnapshot.voice.TTS_EdgeTTS0006': 'EdgeTTS männlich - Yunxia', 'roleConfig.vad': 'VAD', 'roleConfig.asr': 'ASR', 'roleConfig.llm': 'Hauptsprachmodell (LLM)', @@ -1115,6 +1265,8 @@ export default { 'agentTemplateManagement.action': 'Aktion', 'agentTemplateManagement.createTemplate': 'Vorlage erstellen', 'templateQuickConfig.newTemplate': 'Neue Vorlage', + 'templateQuickConfig.editTemplate': 'Vorlage bearbeiten', + 'templateQuickConfig.addTemplate': 'Vorlage hinzufügen', 'agentTemplateManagement.editTemplate': 'Vorlage bearbeiten', 'agentTemplateManagement.deleteTemplate': 'Vorlage löschen', 'agentTemplateManagement.deleteSuccess': 'Vorlage erfolgreich gelöscht', @@ -1194,6 +1346,8 @@ export default { 'voiceClone.operationClosed': 'Popup geschlossen', 'voiceClone.cloneSuccess': 'Klonen erfolgreich', 'voiceClone.cloneFailed': 'Klonen fehlgeschlagen', + 'voiceClone.cloneErrorTip': 'Klonen fehlgeschlagen, bitte bewegen Sie die Maus über die Fehlermeldung für Details', + 'voiceClone.apiError': 'API-Aufruf Fehler', 'voiceClone.confirmClone': 'Sind Sie sicher, dass Sie diese Stimme klonen möchten?', 'voiceClone.onlySuccessCanClone': 'Nur erfolgreich trainierte Stimmen können geklont werden', 'common.insufficient': 'Unzureichend', @@ -1211,6 +1365,7 @@ export default { 'voiceClone.training': 'Training', 'voiceClone.trainSuccess': 'Training erfolgreich', 'voiceClone.trainFailed': 'Training fehlgeschlagen', + 'voiceClone.trainFailedWithError': 'Training fehlgeschlagen: {error}', 'voiceClone.itemsPerPage': '{items} Einträge/Seite', 'voiceClone.firstPage': 'Erste Seite', 'voiceClone.prevPage': 'Vorherige Seite', @@ -1322,10 +1477,6 @@ export default { 'knowledgeFileUpload.viewSlices': 'Segmente anzeigen', 'knowledgeFileUpload.delete': 'Löschen', 'knowledgeFileUpload.itemsPerPage': 'Einträge/Seite', - 'knowledgeFileUpload.firstPage': 'Erste Seite', - 'knowledgeFileUpload.prevPage': 'Vorherige Seite', - 'knowledgeFileUpload.nextPage': 'Nächste Seite', - 'knowledgeFileUpload.totalRecords': 'Insgesamt {total} Datensätze', 'knowledgeFileUpload.uploadDocument': 'Dokument hochladen', 'knowledgeFileUpload.documentNamePlaceholder': 'Bitte Dokumentnamen eingeben', 'knowledgeFileUpload.file': 'Datei', @@ -1364,10 +1515,7 @@ export default { 'knowledgeFileUpload.sliceCount': 'Segmentanzahl', 'knowledgeFileUpload.add': 'Hinzufügen', 'knowledgeFileUpload.retrievalTest': 'Abruftest', - 'knowledgeFileUpload.testQuestion': 'Testfrage', - 'knowledgeFileUpload.testQuestionPlaceholder': 'Bitte geben Sie die zu testende Frage ein', 'knowledgeFileUpload.executeTest': 'Test ausführen', - 'knowledgeFileUpload.testResult': 'Testergebnis:', 'knowledgeFileUpload.selectedFiles': 'Ausgewählte Dateien', 'knowledgeFileUpload.totalSlices': 'Insgesamt {total} Datensätze', 'knowledgeFileUpload.slice': 'Segment', @@ -1412,8 +1560,6 @@ export default { 'featureManagement.groupDescription.featureManagement': 'Aktivierungsstatus der Kernfunktionsmodule steuern', 'featureManagement.groupDescription.voiceManagement': 'Konfigurieren, welche Funktionen für Agenten (KI-Assistenten) sichtbar und verfügbar sind', 'featureManagement.moduleCount': '{count} Module insgesamt', - 'featureManagement.enabled': 'Aktiviert', - 'featureManagement.disabled': 'Deaktiviert', // Feature names and descriptions 'feature.voiceprintRecognition.name': 'Stimmerkennung', @@ -1434,12 +1580,10 @@ export default { // Adressbuch Verwaltungsseite 'addressBookManagement.title': 'Adressbuchverwaltung', 'addressBookManagement.searchPlaceholder': 'Gerätename oder MAC-Adresse suchen', - 'addressBookManagement.search': 'Suchen', 'addressBookManagement.selectAgent': 'Bitte Agent auswählen', 'addressBookManagement.name': 'Adressbuchname', 'addressBookManagement.description': 'Adressbuchbeschreibung', 'addressBookManagement.contactCount': 'Kontaktanzahl', - 'addressBookManagement.status': 'Aktiviert', 'addressBookManagement.createdAt': 'Erstellt am', 'addressBookManagement.operation': 'Aktion', 'addressBookManagement.add': 'Hinzufügen', @@ -1460,9 +1604,7 @@ export default { 'addressBookManagement.operationCancelled': 'Löschvorgang abgebrochen', 'addressBookManagement.updateSuccess': 'Aktualisierung erfolgreich', 'addressBookManagement.addSuccess': 'Erfolgreich hinzugefügt', - 'addressBookManagement.updateFailed': 'Aktualisierung fehlgeschlagen', 'addressBookManagement.addFailed': 'Hinzufügen fehlgeschlagen', - 'addressBookManagement.selectAll': 'Alle auswählen', 'addressBookManagement.cancelSelectAll': 'Alle abwählen', 'addressBookManagement.deviceName': 'Gerätename', 'addressBookManagement.deviceType': 'Gerätetyp', @@ -1477,9 +1619,7 @@ export default { 'addressBookManagement.addressBookDescPlaceholder': 'Bitte Adressbuchbeschreibung eingeben', 'addressBookManagement.remarksPlaceholder': 'Bitte Bemerkungen eingeben', 'addressBookManagement.selectDevice': 'Bitte ein Gerät auswählen, um Adressbuchdetails anzuzeigen', - 'addressBookManagement.save': 'Speichern', 'addressBookManagement.saveSuccess': 'Speichern erfolgreich', - 'addressBookManagement.saveFailed': 'Speichern fehlgeschlagen', 'addressBookManagement.deviceNotSelected': 'Bitte zuerst ein Gerät auswählen', 'addressBookManagement.addDeviceTip': 'Gerät hinzufügen Funktion ist in Entwicklung', 'addressBookManagement.selectAgentFirst': 'Bitte zuerst einen Agent auswählen', diff --git a/main/manager-web/src/i18n/en.js b/main/manager-web/src/i18n/en.js index 2a89f69dc..9d5bdf13e 100644 --- a/main/manager-web/src/i18n/en.js +++ b/main/manager-web/src/i18n/en.js @@ -352,6 +352,8 @@ export default { // Replacement word management page related 'replacementWordManagement.pageTitle': 'Replacement Word Management', + 'replacementWordManagement.searchPlaceholder': 'Please enter file name to search', + 'replacementWordManagement.search': 'Search', 'replacementWordManagement.fileName': 'File Name', 'replacementWordManagement.replacementWordCount': 'Replacement Word Count', 'replacementWordManagement.replacementWordContent': 'Replacement Word Content', @@ -475,8 +477,8 @@ export default { 'device.type': 'Device Type', 'device.status': 'Device Status', 'device.dialogTitle': 'Add Device', - 'device.verificationCode': 'Verification Code:', - 'device.verificationCodePlaceholder': 'Please enter the 6-digit verification code broadcasted by the device..', + 'device.verificationCode': 'Verification Code', + 'device.verificationCodePlaceholder': 'Please enter the 6-digit verification code broadcasted by the device…', 'device.confirmButton': 'Confirm', 'device.cancelButton': 'Cancel', 'device.input6DigitCode': 'Please enter a 6-digit verification code', @@ -488,7 +490,7 @@ export default { 'device.firmwareVersion': 'Firmware Version', 'device.bindTime': 'Binding Time', 'device.lastConversation': 'Last Conversation', - 'device.remark': 'Remark', + 'device.alias': 'Device Alias', 'device.autoUpdate': 'Auto Update', 'device.operation': 'Operation', 'device.search': 'Search', @@ -503,9 +505,9 @@ export default { 'device.confirmBatchUnbind': 'Are you sure you want to unbind {count} selected devices?', 'device.batchUnbindSuccess': 'Successfully unbound {count} devices', 'device.batchUnbindError': 'Error occurred during batch unbinding', - 'device.remarkTooLong': 'Remark cannot exceed 64 characters', - 'device.remarkSaved': 'Remark saved successfully', - 'device.remarkSaveFailed': 'Failed to save remark', + 'device.aliasTooLong': 'Device alias cannot exceed 64 characters', + 'device.aliasSaved': 'Device alias saved successfully', + 'device.aliasSaveFailed': 'Failed to save device alias', 'device.confirmUnbind': 'Are you sure you want to unbind this device?', 'device.unbindSuccess': 'Device unbound successfully', 'device.unbindFailed': 'Failed to unbind device', @@ -591,6 +593,7 @@ export default { // Dictionary management page text 'dictManagement.pageTitle': 'Dictionary Management', + 'dictManagement.dictTypeCategory': 'Dict Category', 'dictManagement.searchPlaceholder': 'Please enter dict value label to search', 'dictManagement.search': 'Search', 'dictManagement.dictTypeName': 'Dict Type Name', @@ -645,6 +648,8 @@ export default { 'user.disable': 'Disable', 'user.delete': 'Delete', 'user.selectUsersFirst': 'Please select users to delete first', + 'user.selectUsersToDisable': 'Please select users to disable', + 'user.selectUsersToEnable': 'Please select users to enable', 'user.confirmDeleteSelected': 'Are you sure you want to delete {count} selected users?', 'user.deleting': 'Deleting...', 'user.deleteSuccess': 'Successfully deleted {count} users', @@ -704,6 +709,9 @@ export default { 'common.cancel': 'Cancel', 'common.sensitive': 'Sensitive', 'common.loading': 'Loading', + 'common.copySuccess': 'Copy successful', + 'common.copyFailed': 'Copy failed', + 'common.copyAddress': 'Copy address', // Language switch 'language.zhCN': '中文简体', @@ -728,7 +736,12 @@ export default { 'home.justNow': 'Just now', 'home.minutesAgo': '{minutes} minutes ago', 'home.hoursAgo': '{hours} hours {minutes} minutes ago', - 'home.confirmDeleteAgent': 'Are you sure you want to delete this agent?', + 'home.deleteConfirmTitle': 'Delete Agent', + 'home.confirmDeleteAgent': 'Deletion cannot be undone. Type the agent name "{agentName}" to confirm.', + 'home.deleteAgentNamePlaceholder': 'Enter agent name', + 'home.deleteAgentNameMismatch': 'The agent name does not match', + 'home.deleteAgentPasteForbidden': 'Please type the agent name manually. Pasting is not allowed.', + 'home.deleteAgentMissingInfo': 'Unable to confirm agent information. Please refresh and try again.', 'home.deleteSuccess': 'Delete successful', 'home.deleteFailed': 'Delete failed', 'home.enableMemory': 'Please enable memory in the "Config Role" page first', @@ -739,8 +752,10 @@ export default { 'paramManagement.search': 'Search', 'paramManagement.paramCode': 'Parameter Code', 'paramManagement.paramValue': 'Parameter Value', + 'paramManagement.valueType': 'Type', 'paramManagement.remark': 'Remark', 'paramManagement.operation': 'Operation', + 'paramManagement.select': 'Select', 'paramManagement.hide': 'Hide', 'paramManagement.view': 'View', 'paramManagement.deselectAll': 'Deselect All', @@ -748,11 +763,29 @@ export default { 'paramManagement.add': 'Add', 'paramManagement.delete': 'Delete', 'paramManagement.edit': 'Edit', + 'paramManagement.refresh': 'Refresh', 'paramManagement.itemsPerPage': 'items/page', 'paramManagement.firstPage': 'First Page', 'paramManagement.prevPage': 'Previous Page', 'paramManagement.nextPage': 'Next Page', - 'paramManagement.totalRecords': 'Total {total} records', + 'paramManagement.totalRecords': '{total} total', + 'paramManagement.selectedCount': '{count} selected', + 'paramManagement.groupHint': 'Grouped by namespace', + 'paramManagement.emptyResult': 'No matching parameters', + 'paramManagement.group.all': 'All', + 'paramManagement.group.server': 'Server', + 'paramManagement.group.plugins': 'Plugins', + 'paramManagement.group.log': 'Logging', + 'paramManagement.group.session': 'Session', + 'paramManagement.group.general': 'General', + 'paramManagement.subgroup.root': 'Basics', + 'paramManagement.subgroup.auth': 'Auth', + 'paramManagement.subgroup.connection': 'Connection', + 'paramManagement.subgroup.registry': 'Registry', + 'paramManagement.subgroup.resilience': 'Resilience', + 'paramManagement.subgroup.metrics': 'Metrics', + 'paramManagement.subgroup.tracing': 'Tracing', + 'paramManagement.subgroup.plugin': 'Plugin · {name}', 'paramManagement.addParam': 'Add Parameter', 'paramManagement.editParam': 'Edit Parameter', 'paramManagement.getParamsListFailed': 'Failed to get parameter list', @@ -787,7 +820,7 @@ export default { // Add agent dialog text 'addAgentDialog.title': 'Add Agent', 'addAgentDialog.agentName': 'Agent Name', - 'addAgentDialog.placeholder': 'Please enter agent name..', + 'addAgentDialog.placeholder': 'Please enter agent name…', 'addAgentDialog.confirm': 'Confirm', 'addAgentDialog.cancel': 'Cancel', 'addAgentDialog.nameRequired': 'Please enter agent name', @@ -798,6 +831,9 @@ export default { 'roleConfig.addTag': 'Add New Tag', 'roleConfig.restartNotice': 'After saving the configuration, you need to restart the device for the new configuration to take effect.', 'roleConfig.saveConfig': 'Save Configuration', + 'roleConfig.snapshotHistory': 'History', + 'roleConfig.currentVersion': 'Current Version {version}', + 'roleConfig.functionName': 'Function Name', 'roleConfig.reset': 'Reset', 'roleConfig.agentName': 'Nickname', 'roleConfig.roleTemplate': 'Template', @@ -854,6 +890,120 @@ export default { 'roleConfig.audioPlayFailed': 'Audio playback failed', 'roleConfig.cannotPlayAudio': 'Cannot play audio', 'roleConfig.audioPlayError': 'Error occurred during audio playback', + 'agentSnapshot.title': 'Version History', + 'agentSnapshot.empty': 'No versions yet', + 'agentSnapshot.version': 'Version', + 'agentSnapshot.createdAt': 'Saved At', + 'agentSnapshot.source': 'Source', + 'agentSnapshot.changedFields': 'Changes', + 'agentSnapshot.actions': 'Actions', + 'agentSnapshot.view': 'View', + 'agentSnapshot.restore': 'Restore', + 'agentSnapshot.delete': 'Delete', + 'agentSnapshot.detailTitle': 'Change Details', + 'agentSnapshot.restorePreviewTitle': 'Restore Preview', + 'agentSnapshot.confirmRestore': 'Confirm Restore', + 'agentSnapshot.before': 'Before', + 'agentSnapshot.after': 'After', + 'agentSnapshot.emptyValue': 'None', + 'agentSnapshot.secretRedacted': 'Secret redacted', + 'agentSnapshot.configValue': 'Config Value', + 'agentSnapshot.noChangedContent': 'No changes to display', + 'agentSnapshot.noFunctionChange': 'No function changes', + 'agentSnapshot.beforeChange': 'Before Change', + 'agentSnapshot.afterChange': 'After Change', + 'agentSnapshot.beforeRestore': 'Before Restore', + 'agentSnapshot.afterRestore': 'After Restore', + 'agentSnapshot.restoreMemoryWarning': 'Restoring to a no-memory version will clear this agent\'s chat history. Continue only after confirming this risk.', + 'agentSnapshot.restoreMemoryDestructiveWarning': 'This restore will permanently delete this agent\'s existing chat history. Chat history is not included in configuration snapshots and cannot be recovered from version history.', + 'agentSnapshot.unsavedChangesWarning': 'Unsaved changes on this page are not included in history and will be discarded after restore.', + 'agentSnapshot.restoreConfirm': 'Restore to version {version}? The current configuration will be preserved in history.', + 'agentSnapshot.restoreSuccess': 'Version restored', + 'agentSnapshot.restoreFailed': 'Failed to restore version', + 'agentSnapshot.restoreFailedRollback': 'Failed to restore version. The transaction was rolled back and the current configuration was not changed', + 'agentSnapshot.deleteConfirm': 'Delete version {version}? This cannot be undone.', + 'agentSnapshot.deleteSuccess': 'History version deleted', + 'agentSnapshot.deleteFailed': 'Failed to delete history version', + 'agentSnapshot.fetchFailed': 'Failed to fetch versions', + 'agentSnapshot.detailFailed': 'Failed to fetch snapshot details', + 'agentSnapshot.currentVersion': 'Latest Snapshot', + 'agentSnapshot.source.config': 'Config Save', + 'agentSnapshot.source.current': 'Current Config', + 'agentSnapshot.source.restore': 'Restored', + 'agentSnapshot.source.initial': 'Initial Version', + 'agentSnapshot.field.restore': 'Restore', + 'agentSnapshot.field.initial': 'Initial Snapshot', + 'agentSnapshot.field.agentCode': 'Agent Code', + 'agentSnapshot.field.agentName': 'Nickname', + 'agentSnapshot.field.asrModelId': 'Speech Recognition', + 'agentSnapshot.field.vadModelId': 'Voice Detect', + 'agentSnapshot.field.llmModelId': 'Main Language Model', + 'agentSnapshot.field.slmModelId': 'Small Language Model', + 'agentSnapshot.field.vllmModelId': 'Vision Model', + 'agentSnapshot.field.ttsModelId': 'Text-to-Speech', + 'agentSnapshot.field.ttsVoiceId': 'Voice', + 'agentSnapshot.field.ttsLanguage': 'Language', + 'agentSnapshot.field.ttsVolume': 'Volume', + 'agentSnapshot.field.ttsRate': 'Speed', + 'agentSnapshot.field.ttsPitch': 'Pitch', + 'agentSnapshot.field.memModelId': 'Memory Model', + 'agentSnapshot.field.intentModelId': 'Intent Recognition', + 'agentSnapshot.field.chatHistoryConf': 'Chat History', + 'agentSnapshot.field.systemPrompt': 'Introduction', + 'agentSnapshot.field.summaryMemory': 'Memory', + 'agentSnapshot.field.langCode': 'Language Code', + 'agentSnapshot.field.language': 'Interaction Language', + 'agentSnapshot.field.sort': 'Sort', + 'agentSnapshot.field.functions': 'Functions', + 'agentSnapshot.field.contextProviders': 'Context Providers', + 'agentSnapshot.field.correctWordFileIds': 'Replacement Words', + 'agentSnapshot.field.tagNames': 'Tags', + 'agentSnapshot.field.tagIds': 'Tag IDs', + 'agentSnapshot.function.added': 'Enabled', + 'agentSnapshot.function.removed': 'Disabled', + 'agentSnapshot.function.updated': 'Parameters changed', + 'agentSnapshot.function.enabled': 'Enabled', + 'agentSnapshot.function.disabled': 'Disabled', + 'agentSnapshot.function.disabledNote': 'This function is disabled', + 'agentSnapshot.function.noParams': 'No parameters required', + 'agentSnapshot.chatHistoryConf.none': 'Do not record chat history', + 'agentSnapshot.chatHistoryConf.text': 'Report text', + 'agentSnapshot.chatHistoryConf.textVoice': 'Report text and voice', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_WEATHER': 'Weather', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_MUSIC': 'Server music player', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_NEWS_CHINANEWS': 'China News', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_NEWS_NEWSNOW': 'NewsNow aggregation', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_HA_STATE': 'HomeAssistant device control', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_HA_PLAY_MUSIC': 'HomeAssistant music player', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_WEB_SEARCH': 'Web search', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_CALL_DEVICE': 'Device-to-device call', + 'agentSnapshot.pluginField.url': 'Endpoint URL', + 'agentSnapshot.pluginField.news_sources': 'News sources', + 'agentSnapshot.pluginField.default_rss_url': 'Default RSS URL', + 'agentSnapshot.pluginField.society_rss_url': 'Society RSS URL', + 'agentSnapshot.pluginField.world_rss_url': 'World RSS URL', + 'agentSnapshot.pluginField.finance_rss_url': 'Finance RSS URL', + 'agentSnapshot.pluginField.api_key': 'API key', + 'agentSnapshot.pluginField.default_location': 'Default city', + 'agentSnapshot.pluginField.api_host': 'Developer API host', + 'agentSnapshot.pluginField.base_url': 'Server URL', + 'agentSnapshot.pluginField.devices': 'Devices', + 'agentSnapshot.pluginField.provider': 'Search provider', + 'agentSnapshot.pluginField.description': 'Tool description', + 'agentSnapshot.pluginField.max_results': 'Result count', + 'agentSnapshot.model.Memory_nomem': 'No memory', + 'agentSnapshot.model.Memory_mem_local_short': 'Local short memory', + 'agentSnapshot.model.Memory_mem0ai': 'Mem0AI memory', + 'agentSnapshot.model.Memory_mem_report_only': 'Report only', + 'agentSnapshot.model.Intent_nointent': 'No intent recognition', + 'agentSnapshot.model.Intent_intent_llm': 'External LLM intent recognition', + 'agentSnapshot.model.Intent_function_call': 'LLM function calling', + 'agentSnapshot.voice.TTS_EdgeTTS0001': 'EdgeTTS female - Xiaoxiao', + 'agentSnapshot.voice.TTS_EdgeTTS0002': 'EdgeTTS male - Yunyang', + 'agentSnapshot.voice.TTS_EdgeTTS0003': 'EdgeTTS female - Xiaoyi', + 'agentSnapshot.voice.TTS_EdgeTTS0004': 'EdgeTTS male - Yunjian', + 'agentSnapshot.voice.TTS_EdgeTTS0005': 'EdgeTTS male - Yunxi', + 'agentSnapshot.voice.TTS_EdgeTTS0006': 'EdgeTTS male - Yunxia', // Form field Tooltip descriptions 'roleConfig.tooltip.agentName': 'Set the name of your AI agent for identification and recognition', @@ -1150,6 +1300,8 @@ export default { 'templateQuickConfig.cancel': 'Cancel', 'templateQuickConfig.templateNotFound': 'Template not found', 'templateQuickConfig.newTemplate': 'New Template', + 'templateQuickConfig.editTemplate': 'Edit Template', + 'templateQuickConfig.addTemplate': 'Add Template', 'warning': 'Warning', 'info': 'Info', 'common.networkError': 'Network request failed', @@ -1195,6 +1347,8 @@ export default { 'voiceClone.operationClosed': 'Popup closed', 'voiceClone.cloneSuccess': 'Clone successful', 'voiceClone.cloneFailed': 'Clone failed', + 'voiceClone.cloneErrorTip': 'Clone failed, please hover over the error tip to view error details', + 'voiceClone.apiError': 'API call error', 'voiceClone.confirmClone': 'Are you sure you want to clone this voice?', 'voiceClone.onlySuccessCanClone': 'Only successfully trained voices can be cloned', 'common.insufficient': 'Insufficient', @@ -1212,6 +1366,7 @@ export default { 'voiceClone.training': 'Training', 'voiceClone.trainSuccess': 'Training successful', 'voiceClone.trainFailed': 'Training failed', + 'voiceClone.trainFailedWithError': 'Training failed: {error}', 'voiceClone.itemsPerPage': '{items} items/page', 'voiceClone.firstPage': 'First Page', 'voiceClone.prevPage': 'Previous Page', @@ -1323,10 +1478,6 @@ export default { 'knowledgeFileUpload.viewSlices': 'View Slices', 'knowledgeFileUpload.delete': 'Delete', 'knowledgeFileUpload.itemsPerPage': 'items/page', - 'knowledgeFileUpload.firstPage': 'First Page', - 'knowledgeFileUpload.prevPage': 'Previous Page', - 'knowledgeFileUpload.nextPage': 'Next Page', - 'knowledgeFileUpload.totalRecords': 'Total {total} records', 'knowledgeFileUpload.uploadDocument': 'Upload Document', 'knowledgeFileUpload.documentNamePlaceholder': 'Please enter document name', 'knowledgeFileUpload.file': 'File', @@ -1365,10 +1516,7 @@ export default { 'knowledgeFileUpload.sliceCount': 'Slice Count', 'knowledgeFileUpload.add': 'Add', 'knowledgeFileUpload.retrievalTest': 'Retrieval Test', - 'knowledgeFileUpload.testQuestion': 'Test Question', - 'knowledgeFileUpload.testQuestionPlaceholder': 'Please enter the question to test', 'knowledgeFileUpload.executeTest': 'Execute Test', - 'knowledgeFileUpload.testResult': 'Test Result:', 'knowledgeFileUpload.selectedFiles': 'Selected Files', 'knowledgeFileUpload.totalSlices': 'Total {total} records', 'knowledgeFileUpload.slice': 'Slice', @@ -1420,8 +1568,6 @@ export default { 'featureManagement.groupDescription.featureManagement': 'Control the enable status of core feature modules', 'featureManagement.groupDescription.voiceManagement': 'Configure which features are visible and available to agents (AI assistants)', 'featureManagement.moduleCount': '{count} modules in total', - 'featureManagement.enabled': 'Enabled', - 'featureManagement.disabled': 'Disabled', // Feature names and descriptions 'feature.voiceprintRecognition.name': 'Voiceprint Recognition', @@ -1442,12 +1588,10 @@ export default { // Address Book Management page 'addressBookManagement.title': 'Address Book Management', 'addressBookManagement.searchPlaceholder': 'Search device name or MAC address', - 'addressBookManagement.search': 'Search', 'addressBookManagement.selectAgent': 'Please select agent', 'addressBookManagement.name': 'Address Book Name', 'addressBookManagement.description': 'Address Book Description', 'addressBookManagement.contactCount': 'Contact Count', - 'addressBookManagement.status': 'Enabled', 'addressBookManagement.createdAt': 'Created Time', 'addressBookManagement.operation': 'Operation', 'addressBookManagement.add': 'Add', @@ -1468,9 +1612,7 @@ export default { 'addressBookManagement.operationCancelled': 'Delete operation cancelled', 'addressBookManagement.updateSuccess': 'Update successful', 'addressBookManagement.addSuccess': 'Add successful', - 'addressBookManagement.updateFailed': 'Update failed', 'addressBookManagement.addFailed': 'Add failed', - 'addressBookManagement.selectAll': 'Select All', 'addressBookManagement.cancelSelectAll': 'Deselect All', 'addressBookManagement.deviceName': 'Device Name', 'addressBookManagement.deviceType': 'Device Type', @@ -1485,9 +1627,7 @@ export default { 'addressBookManagement.addressBookDescPlaceholder': 'Please enter address book description', 'addressBookManagement.remarksPlaceholder': 'Please enter remarks', 'addressBookManagement.selectDevice': 'Please select a device to view address book details', - 'addressBookManagement.save': 'Save', 'addressBookManagement.saveSuccess': 'Save successful', - 'addressBookManagement.saveFailed': 'Save failed', 'addressBookManagement.deviceNotSelected': 'Please select a device first', 'addressBookManagement.addDeviceTip': 'Add device feature is under development', 'addressBookManagement.selectAgentFirst': 'Please select an agent first', diff --git a/main/manager-web/src/i18n/index.js b/main/manager-web/src/i18n/index.js index 4acb3a327..46dff1bf1 100644 --- a/main/manager-web/src/i18n/index.js +++ b/main/manager-web/src/i18n/index.js @@ -5,6 +5,14 @@ import de from './de'; import vi from './vi'; import ptBR from './pt_BR'; +import enLocale from 'element-ui/lib/locale/lang/en' +import zhLocale from 'element-ui/lib/locale/lang/zh-CN' +import twLocale from 'element-ui/lib/locale/lang/zh-TW' +import deLocale from 'element-ui/lib/locale/lang/de' +import viLocale from 'element-ui/lib/locale/lang/vi' +import ptBRLocale from 'element-ui/lib/locale/lang/pt-br' + + Vue.use(VueI18n); export const supportedLanguages = Object.freeze([ diff --git a/main/manager-web/src/i18n/pt_BR.js b/main/manager-web/src/i18n/pt_BR.js index 7620bf29c..1213d3c43 100644 --- a/main/manager-web/src/i18n/pt_BR.js +++ b/main/manager-web/src/i18n/pt_BR.js @@ -353,6 +353,8 @@ export default { // Replacement word management page related 'replacementWordManagement.pageTitle': 'Gerenciamento de Palavras de Substituição', + 'replacementWordManagement.searchPlaceholder': 'Digite o nome do arquivo para pesquisar', + 'replacementWordManagement.search': 'Pesquisar', 'replacementWordManagement.fileName': 'Nome do Arquivo', 'replacementWordManagement.replacementWordCount': 'Quantidade de Palavras de Substituição', 'replacementWordManagement.replacementWordContent': 'Conteúdo Substituto', @@ -476,8 +478,8 @@ export default { 'device.type': 'Tipo de Dispositivo', 'device.status': 'Status do Dispositivo', 'device.dialogTitle': 'Adicionar Dispositivo', - 'device.verificationCode': 'Código de Verificação:', - 'device.verificationCodePlaceholder': 'Por favor, insira o código de verificação de 6 dígitos transmitido pelo dispositivo..', + 'device.verificationCode': 'Código de Verificação', + 'device.verificationCodePlaceholder': 'Por favor, insira o código de verificação de 6 dígitos transmitido pelo dispositivo…', 'device.confirmButton': 'Confirmar', 'device.cancelButton': 'Cancelar', 'device.input6DigitCode': 'Por favor, insira um código de verificação de 6 dígitos', @@ -489,7 +491,7 @@ export default { 'device.firmwareVersion': 'Versão do Firmware', 'device.bindTime': 'Data de Vinculação', 'device.lastConversation': 'Última Conversa', - 'device.remark': 'Observação', + 'device.alias': 'Alias do dispositivo', 'device.autoUpdate': 'Atualização Automática', 'device.operation': 'Operação', 'device.search': 'Pesquisar', @@ -504,9 +506,9 @@ export default { 'device.confirmBatchUnbind': 'Tem certeza de que deseja desvincular {count} dispositivos selecionados?', 'device.batchUnbindSuccess': '{count} dispositivos desvinculados com sucesso', 'device.batchUnbindError': 'Ocorreu um erro durante a desvinculação em lote', - 'device.remarkTooLong': 'A observação não pode exceder 64 caracteres', - 'device.remarkSaved': 'Observação salva com sucesso', - 'device.remarkSaveFailed': 'Falha ao salvar observação', + 'device.aliasTooLong': 'O alias do dispositivo não pode exceder 64 caracteres', + 'device.aliasSaved': 'Alias do dispositivo salvo com sucesso', + 'device.aliasSaveFailed': 'Falha ao salvar o alias do dispositivo', 'device.confirmUnbind': 'Tem certeza de que deseja desvincular este dispositivo?', 'device.unbindSuccess': 'Dispositivo desvinculado com sucesso', 'device.unbindFailed': 'Falha ao desvincular dispositivo', @@ -592,6 +594,7 @@ export default { // Página de gerenciamento de dicionário 'dictManagement.pageTitle': 'Gerenciamento de Dicionário', + 'dictManagement.dictTypeCategory': 'Categoria do Dicionário', 'dictManagement.searchPlaceholder': 'Por favor, insira o rótulo do dicionário para pesquisar', 'dictManagement.search': 'Pesquisar', 'dictManagement.dictTypeName': 'Nome do Tipo de Dicionário', @@ -646,6 +649,8 @@ export default { 'user.disable': 'Desativar', 'user.delete': 'Excluir', 'user.selectUsersFirst': 'Por favor, selecione usuários para excluir primeiro', + 'user.selectUsersToDisable': 'Por favor, selecione usuários para desativar', + 'user.selectUsersToEnable': 'Por favor, selecione usuários para ativar', 'user.confirmDeleteSelected': 'Tem certeza de que deseja excluir {count} usuários selecionados?', 'user.deleting': 'Excluindo...', 'user.deleteSuccess': '{count} usuários excluídos com sucesso', @@ -705,6 +710,9 @@ export default { 'common.cancel': 'Cancelar', 'common.sensitive': 'Sensível', 'common.loading': 'Carregando', + 'common.copySuccess': 'Cópia bem-sucedida', + 'common.copyFailed': 'Falha ao copiar', + 'common.copyAddress': 'Copiar endereço', // Troca de idioma 'language.en': 'English', @@ -727,7 +735,12 @@ export default { 'home.justNow': 'Agora mesmo', 'home.minutesAgo': 'Há {minutes} minutos', 'home.hoursAgo': 'Há {hours} horas e {minutes} minutos', - 'home.confirmDeleteAgent': 'Tem certeza de que deseja excluir este agente?', + 'home.deleteConfirmTitle': 'Excluir Agente', + 'home.confirmDeleteAgent': 'A exclusão não pode ser desfeita. Digite o nome do agente "{agentName}" para confirmar.', + 'home.deleteAgentNamePlaceholder': 'Digite o nome do agente', + 'home.deleteAgentNameMismatch': 'O nome do agente não corresponde', + 'home.deleteAgentPasteForbidden': 'Digite o nome do agente manualmente. Colar não é permitido.', + 'home.deleteAgentMissingInfo': 'Não foi possível confirmar as informações do agente. Atualize a página e tente novamente.', 'home.deleteSuccess': 'Excluído com sucesso', 'home.deleteFailed': 'Falha ao excluir', 'home.enableMemory': 'Por favor, ative a memória na página "Configurar Papel" primeiro', @@ -738,8 +751,10 @@ export default { 'paramManagement.search': 'Pesquisar', 'paramManagement.paramCode': 'Código do Parâmetro', 'paramManagement.paramValue': 'Valor do Parâmetro', + 'paramManagement.valueType': 'Tipo', 'paramManagement.remark': 'Observação', 'paramManagement.operation': 'Operação', + 'paramManagement.select': 'Selecionar', 'paramManagement.hide': 'Ocultar', 'paramManagement.view': 'Visualizar', 'paramManagement.deselectAll': 'Desmarcar Tudo', @@ -747,11 +762,29 @@ export default { 'paramManagement.add': 'Adicionar', 'paramManagement.delete': 'Excluir', 'paramManagement.edit': 'Editar', + 'paramManagement.refresh': 'Atualizar', 'paramManagement.itemsPerPage': 'itens/página', 'paramManagement.firstPage': 'Primeira Página', 'paramManagement.prevPage': 'Página Anterior', 'paramManagement.nextPage': 'Próxima Página', - 'paramManagement.totalRecords': 'Total de {total} registros', + 'paramManagement.totalRecords': '{total} no total', + 'paramManagement.selectedCount': '{count} selecionados', + 'paramManagement.groupHint': 'Agrupado por namespace', + 'paramManagement.emptyResult': 'Nenhum parâmetro correspondente', + 'paramManagement.group.all': 'Todos', + 'paramManagement.group.server': 'Servidor', + 'paramManagement.group.plugins': 'Plugins', + 'paramManagement.group.log': 'Logs', + 'paramManagement.group.session': 'Sessão', + 'paramManagement.group.general': 'Geral', + 'paramManagement.subgroup.root': 'Básico', + 'paramManagement.subgroup.auth': 'Auth', + 'paramManagement.subgroup.connection': 'Conexão', + 'paramManagement.subgroup.registry': 'Registry', + 'paramManagement.subgroup.resilience': 'Resilience', + 'paramManagement.subgroup.metrics': 'Métricas', + 'paramManagement.subgroup.tracing': 'Tracing', + 'paramManagement.subgroup.plugin': 'Plugin · {name}', 'paramManagement.addParam': 'Adicionar Parâmetro', 'paramManagement.editParam': 'Editar Parâmetro', 'paramManagement.getParamsListFailed': 'Falha ao obter lista de parâmetros', @@ -786,7 +819,7 @@ export default { // Diálogo de adicionar agente 'addAgentDialog.title': 'Adicionar Agente', 'addAgentDialog.agentName': 'Nome do Agente', - 'addAgentDialog.placeholder': 'Por favor, insira o nome do agente..', + 'addAgentDialog.placeholder': 'Por favor, insira o nome do agente…', 'addAgentDialog.confirm': 'Confirmar', 'addAgentDialog.cancel': 'Cancelar', 'addAgentDialog.nameRequired': 'Por favor, insira o nome do agente', @@ -797,12 +830,129 @@ export default { 'roleConfig.addTag': 'Adicionar Novo Rótulo', 'roleConfig.restartNotice': 'Reinicie após salvar a configuração para ativação.', 'roleConfig.saveConfig': 'Salvar Configuração', + 'roleConfig.snapshotHistory': 'Histórico de Versões', + 'roleConfig.currentVersion': 'Versão Atual {version}', + 'roleConfig.functionName': 'Nome da Função', 'roleConfig.reset': 'Redefinir', 'roleConfig.agentName': 'Apelido', 'roleConfig.roleTemplate': 'Modelo', 'roleConfig.roleIntroduction': 'Introdução', 'roleConfig.languageCode': 'Código do Idioma', 'roleConfig.interactionLanguage': 'Idioma de Interação', + 'agentSnapshot.title': 'Histórico de Versões', + 'agentSnapshot.empty': 'Ainda sem versões', + 'agentSnapshot.version': 'Versão', + 'agentSnapshot.createdAt': 'Salvo em', + 'agentSnapshot.source': 'Origem', + 'agentSnapshot.changedFields': 'Alterações', + 'agentSnapshot.actions': 'Ações', + 'agentSnapshot.view': 'Ver', + 'agentSnapshot.restore': 'Restaurar', + 'agentSnapshot.delete': 'Excluir', + 'agentSnapshot.detailTitle': 'Detalhes da Alteração', + 'agentSnapshot.restorePreviewTitle': 'Prévia da Restauração', + 'agentSnapshot.confirmRestore': 'Confirmar Restauração', + 'agentSnapshot.before': 'Antes', + 'agentSnapshot.after': 'Depois', + 'agentSnapshot.emptyValue': 'Nenhum', + 'agentSnapshot.secretRedacted': 'Chave secreta mascarada', + 'agentSnapshot.configValue': 'Valor da configuração', + 'agentSnapshot.noChangedContent': 'Nenhuma alteração para exibir', + 'agentSnapshot.noFunctionChange': 'Sem alterações de função', + 'agentSnapshot.beforeChange': 'Antes da Alteração', + 'agentSnapshot.afterChange': 'Depois da Alteração', + 'agentSnapshot.beforeRestore': 'Antes da Restauração', + 'agentSnapshot.afterRestore': 'Depois da Restauração', + 'agentSnapshot.restoreMemoryWarning': 'Restaurar para uma versão sem memória apagará o histórico de conversa deste agente. Continue somente após confirmar esse risco.', + 'agentSnapshot.restoreMemoryDestructiveWarning': 'Esta restauração excluirá permanentemente o histórico de conversa existente deste agente. O histórico de conversa não faz parte dos snapshots de configuração e não pode ser recuperado pelo histórico de versões.', + 'agentSnapshot.unsavedChangesWarning': 'As alterações não salvas nesta página não serão incluídas no histórico e serão descartadas após a restauração.', + 'agentSnapshot.restoreConfirm': 'Restaurar para a versão {version}? A configuração atual será preservada no histórico.', + 'agentSnapshot.restoreSuccess': 'Versão restaurada', + 'agentSnapshot.restoreFailed': 'Falha ao restaurar versão', + 'agentSnapshot.restoreFailedRollback': 'Falha ao restaurar versão. A transação foi revertida e a configuração atual não foi alterada', + 'agentSnapshot.deleteConfirm': 'Excluir a versão {version}? Esta ação não pode ser desfeita.', + 'agentSnapshot.deleteSuccess': 'Versão do histórico excluída', + 'agentSnapshot.deleteFailed': 'Falha ao excluir a versão do histórico', + 'agentSnapshot.fetchFailed': 'Falha ao buscar versões', + 'agentSnapshot.detailFailed': 'Falha ao buscar detalhes do snapshot', + 'agentSnapshot.currentVersion': 'Snapshot mais recente', + 'agentSnapshot.source.config': 'Configuração Salva', + 'agentSnapshot.source.current': 'Configuração Atual', + 'agentSnapshot.source.restore': 'Resultado da restauração', + 'agentSnapshot.source.initial': 'Versão inicial', + 'agentSnapshot.field.restore': 'Restauração', + 'agentSnapshot.field.initial': 'Snapshot inicial', + 'agentSnapshot.field.agentCode': 'Código do Agente', + 'agentSnapshot.field.agentName': 'Apelido', + 'agentSnapshot.field.asrModelId': 'Reconhecimento de Fala', + 'agentSnapshot.field.vadModelId': 'Detecção de Atividade de Voz', + 'agentSnapshot.field.llmModelId': 'Modelo de Linguagem Principal', + 'agentSnapshot.field.slmModelId': 'Modelo de Linguagem Pequeno', + 'agentSnapshot.field.vllmModelId': 'Modelo de Visão', + 'agentSnapshot.field.ttsModelId': 'Texto para Fala', + 'agentSnapshot.field.ttsVoiceId': 'Voz', + 'agentSnapshot.field.ttsLanguage': 'Idioma', + 'agentSnapshot.field.ttsVolume': 'Volume', + 'agentSnapshot.field.ttsRate': 'Velocidade', + 'agentSnapshot.field.ttsPitch': 'Tom', + 'agentSnapshot.field.memModelId': 'Modelo de Memória', + 'agentSnapshot.field.intentModelId': 'Reconhecimento de Intenção', + 'agentSnapshot.field.chatHistoryConf': 'Histórico de Conversa', + 'agentSnapshot.field.systemPrompt': 'Introdução', + 'agentSnapshot.field.summaryMemory': 'Memória', + 'agentSnapshot.field.langCode': 'Código do Idioma', + 'agentSnapshot.field.language': 'Idioma de Interação', + 'agentSnapshot.field.sort': 'Ordenação', + 'agentSnapshot.field.functions': 'Funções', + 'agentSnapshot.field.contextProviders': 'Provedores de Contexto', + 'agentSnapshot.field.correctWordFileIds': 'Palavras de Substituição', + 'agentSnapshot.field.tagNames': 'Rótulos', + 'agentSnapshot.field.tagIds': 'IDs dos Rótulos', + 'agentSnapshot.function.added': 'Ativado', + 'agentSnapshot.function.removed': 'Desativado', + 'agentSnapshot.function.updated': 'Parâmetros alterados', + 'agentSnapshot.function.enabled': 'Ativado', + 'agentSnapshot.function.disabled': 'Desativado', + 'agentSnapshot.function.disabledNote': 'Esta função está desativada', + 'agentSnapshot.function.noParams': 'Nenhum parâmetro necessário', + 'agentSnapshot.chatHistoryConf.none': 'Não registrar histórico de conversa', + 'agentSnapshot.chatHistoryConf.text': 'Enviar texto', + 'agentSnapshot.chatHistoryConf.textVoice': 'Enviar texto e voz', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_WEATHER': 'Clima', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_MUSIC': 'Reprodutor de música do servidor', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_NEWS_CHINANEWS': 'China News', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_NEWS_NEWSNOW': 'Agregação NewsNow', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_HA_STATE': 'Controle de dispositivo do HomeAssistant', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_HA_PLAY_MUSIC': 'Reprodutor de música do HomeAssistant', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_WEB_SEARCH': 'Pesquisa na web', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_CALL_DEVICE': 'Chamada entre dispositivos', + 'agentSnapshot.pluginField.url': 'URL do endpoint', + 'agentSnapshot.pluginField.news_sources': 'Fontes de notícias', + 'agentSnapshot.pluginField.default_rss_url': 'URL RSS padrão', + 'agentSnapshot.pluginField.society_rss_url': 'URL RSS de sociedade', + 'agentSnapshot.pluginField.world_rss_url': 'URL RSS mundial', + 'agentSnapshot.pluginField.finance_rss_url': 'URL RSS financeiro', + 'agentSnapshot.pluginField.api_key': 'Chave de API', + 'agentSnapshot.pluginField.default_location': 'Cidade padrão', + 'agentSnapshot.pluginField.api_host': 'Host da API de desenvolvedor', + 'agentSnapshot.pluginField.base_url': 'URL do servidor', + 'agentSnapshot.pluginField.devices': 'Dispositivos', + 'agentSnapshot.pluginField.provider': 'Provedor de pesquisa', + 'agentSnapshot.pluginField.description': 'Descrição da ferramenta', + 'agentSnapshot.pluginField.max_results': 'Quantidade de resultados', + 'agentSnapshot.model.Memory_nomem': 'Sem memória', + 'agentSnapshot.model.Memory_mem_local_short': 'Memória curta local', + 'agentSnapshot.model.Memory_mem0ai': 'Memória Mem0AI', + 'agentSnapshot.model.Memory_mem_report_only': 'Somente relatório', + 'agentSnapshot.model.Intent_nointent': 'Sem reconhecimento de intenção', + 'agentSnapshot.model.Intent_intent_llm': 'Reconhecimento de intenção por LLM externo', + 'agentSnapshot.model.Intent_function_call': 'Chamada de função por LLM', + 'agentSnapshot.voice.TTS_EdgeTTS0001': 'EdgeTTS feminino - Xiaoxiao', + 'agentSnapshot.voice.TTS_EdgeTTS0002': 'EdgeTTS masculino - Yunyang', + 'agentSnapshot.voice.TTS_EdgeTTS0003': 'EdgeTTS feminino - Xiaoyi', + 'agentSnapshot.voice.TTS_EdgeTTS0004': 'EdgeTTS masculino - Yunjian', + 'agentSnapshot.voice.TTS_EdgeTTS0005': 'EdgeTTS masculino - Yunxi', + 'agentSnapshot.voice.TTS_EdgeTTS0006': 'EdgeTTS masculino - Yunxia', 'roleConfig.vad': 'Detecção de Voz', 'roleConfig.asr': 'Reconhecimento de Fala', 'roleConfig.llm': 'Modelo de Linguagem Principal', @@ -1149,6 +1299,8 @@ export default { 'templateQuickConfig.cancel': 'Cancelar', 'templateQuickConfig.templateNotFound': 'Modelo não encontrado', 'templateQuickConfig.newTemplate': 'Novo Modelo', + 'templateQuickConfig.editTemplate': 'Editar Modelo', + 'templateQuickConfig.addTemplate': 'Adicionar Modelo', 'warning': 'Aviso', 'info': 'Informação', 'common.networkError': 'Falha na requisição de rede', @@ -1192,8 +1344,10 @@ export default { 'voiceClone.selectFirst': 'Por favor, selecione recursos de voz para excluir primeiro', 'voiceClone.operationCancelled': 'Cancelar', 'voiceClone.operationClosed': 'Popup fechado', - 'voiceClone.cloneSuccess': 'Clonado com sucesso', + 'voiceClone.cloneSuccess': 'Clonagem bem-sucedida', 'voiceClone.cloneFailed': 'Falha ao clonar', + 'voiceClone.cloneErrorTip': 'Falha na clonagem, passe o mouse sobre a dica de erro para ver os detalhes', + 'voiceClone.apiError': 'Erro na chamada da API', 'voiceClone.confirmClone': 'Tem certeza de que deseja clonar esta voz?', 'voiceClone.onlySuccessCanClone': 'Apenas vozes treinadas com sucesso podem ser clonadas', 'common.insufficient': 'Insuficiente', @@ -1211,6 +1365,7 @@ export default { 'voiceClone.training': 'Treinando', 'voiceClone.trainSuccess': 'Treinamento bem-sucedido', 'voiceClone.trainFailed': 'Treinamento falhou', + 'voiceClone.trainFailedWithError': 'Treinamento falhou: {error}', 'voiceClone.itemsPerPage': '{items} itens/página', 'voiceClone.firstPage': 'Primeira Página', 'voiceClone.prevPage': 'Página Anterior', @@ -1322,10 +1477,6 @@ export default { 'knowledgeFileUpload.viewSlices': 'Ver Fatias', 'knowledgeFileUpload.delete': 'Excluir', 'knowledgeFileUpload.itemsPerPage': 'itens/página', - 'knowledgeFileUpload.firstPage': 'Primeira Página', - 'knowledgeFileUpload.prevPage': 'Página Anterior', - 'knowledgeFileUpload.nextPage': 'Próxima Página', - 'knowledgeFileUpload.totalRecords': 'Total de {total} registros', 'knowledgeFileUpload.uploadDocument': 'Enviar Documento', 'knowledgeFileUpload.documentNamePlaceholder': 'Por favor, insira o nome do documento', 'knowledgeFileUpload.file': 'Arquivo', @@ -1364,10 +1515,7 @@ export default { 'knowledgeFileUpload.sliceCount': 'Quantidade de Fatias', 'knowledgeFileUpload.add': 'Adicionar', 'knowledgeFileUpload.retrievalTest': 'Teste de Recuperação', - 'knowledgeFileUpload.testQuestion': 'Pergunta de Teste', - 'knowledgeFileUpload.testQuestionPlaceholder': 'Por favor, insira a pergunta para testar', 'knowledgeFileUpload.executeTest': 'Executar Teste', - 'knowledgeFileUpload.testResult': 'Resultado do Teste:', 'knowledgeFileUpload.selectedFiles': 'Arquivos Selecionados', 'knowledgeFileUpload.totalSlices': 'Total de {total} registros', 'knowledgeFileUpload.slice': 'Fatia', @@ -1412,8 +1560,6 @@ export default { 'featureManagement.groupDescription.featureManagement': 'Controlar o status de ativação dos módulos de funcionalidade principal', 'featureManagement.groupDescription.voiceManagement': 'Configurar quais funcionalidades são visíveis e disponíveis para agentes (assistentes de IA)', 'featureManagement.moduleCount': '{count} módulos no total', - 'featureManagement.enabled': 'Ativado', - 'featureManagement.disabled': 'Desativado', // Nomes e descrições de funcionalidades 'feature.voiceprintRecognition.name': 'Reconhecimento de Impressão Vocal', @@ -1434,12 +1580,10 @@ export default { // Página de Gerenciamento de Lista de Contatos 'addressBookManagement.title': 'Gerenciamento de Lista de Contatos', 'addressBookManagement.searchPlaceholder': 'Pesquisar nome do dispositivo ou endereço MAC', - 'addressBookManagement.search': 'Pesquisar', 'addressBookManagement.selectAgent': 'Selecione um agente', 'addressBookManagement.name': 'Nome da Lista de Contatos', 'addressBookManagement.description': 'Descrição da Lista de Contatos', 'addressBookManagement.contactCount': 'Número de Contatos', - 'addressBookManagement.status': 'Ativo', 'addressBookManagement.createdAt': 'Data de Criação', 'addressBookManagement.operation': 'Operação', 'addressBookManagement.add': 'Adicionar', @@ -1460,9 +1604,7 @@ export default { 'addressBookManagement.operationCancelled': 'Operação de exclusão cancelada', 'addressBookManagement.updateSuccess': 'Atualização bem-sucedida', 'addressBookManagement.addSuccess': 'Adição bem-sucedida', - 'addressBookManagement.updateFailed': 'Falha na atualização', 'addressBookManagement.addFailed': 'Falha ao adicionar', - 'addressBookManagement.selectAll': 'Selecionar Todos', 'addressBookManagement.cancelSelectAll': 'Desmarcar Todos', 'addressBookManagement.deviceName': 'Nome do Dispositivo', 'addressBookManagement.deviceType': 'Tipo do Dispositivo', @@ -1477,9 +1619,7 @@ export default { 'addressBookManagement.addressBookDescPlaceholder': 'Digite a descrição da lista de contatos', 'addressBookManagement.remarksPlaceholder': 'Digite as observações', 'addressBookManagement.selectDevice': 'Selecione um dispositivo para ver os detalhes da lista de contatos', - 'addressBookManagement.save': 'Salvar', 'addressBookManagement.saveSuccess': 'Salvo com sucesso', - 'addressBookManagement.saveFailed': 'Falha ao salvar', 'addressBookManagement.deviceNotSelected': 'Selecione um dispositivo primeiro', 'addressBookManagement.addDeviceTip': 'Recurso de adicionar dispositivo em desenvolvimento', 'addressBookManagement.selectAgentFirst': 'Selecione um agente primeiro', diff --git a/main/manager-web/src/i18n/vi.js b/main/manager-web/src/i18n/vi.js index 30764ee0f..2b81020bd 100644 --- a/main/manager-web/src/i18n/vi.js +++ b/main/manager-web/src/i18n/vi.js @@ -353,6 +353,8 @@ export default { // Replacement word management page related 'replacementWordManagement.pageTitle': 'Quản lý từ thay thế', + 'replacementWordManagement.searchPlaceholder': 'Vui lòng nhập tên tệp để tìm kiếm', + 'replacementWordManagement.search': 'Tìm kiếm', 'replacementWordManagement.fileName': 'Tên tệp', 'replacementWordManagement.replacementWordCount': 'Số lượng từ thay thế', 'replacementWordManagement.replacementWordContent': 'Nội dung từ thay thế', @@ -476,8 +478,8 @@ export default { 'device.type': 'Loại thiết bị', 'device.status': 'Trạng thái thiết bị', 'device.dialogTitle': 'Thêm thiết bị', - 'device.verificationCode': 'Mã xác minh:', - 'device.verificationCodePlaceholder': 'Vui lòng nhập mã xác minh 6 chữ số được phát từ thiết bị..', + 'device.verificationCode': 'Mã xác minh', + 'device.verificationCodePlaceholder': 'Vui lòng nhập mã xác minh 6 chữ số được phát từ thiết bị…', 'device.confirmButton': 'Xác nhận', 'device.cancelButton': 'Hủy bỏ', 'device.input6DigitCode': 'Vui lòng nhập mã xác minh 6 chữ số', @@ -489,7 +491,7 @@ export default { 'device.firmwareVersion': 'Phiên bản firmware', 'device.bindTime': 'Thời gian liên kết', 'device.lastConversation': 'Cuộc trò chuyện cuối', - 'device.remark': 'Ghi chú', + 'device.alias': 'Bí danh thiết bị', 'device.autoUpdate': 'Tự động cập nhật', 'device.operation': 'Thao tác', 'device.search': 'Tìm kiếm', @@ -504,9 +506,9 @@ export default { 'device.confirmBatchUnbind': 'Bạn có chắc chắn muốn hủy liên kết {count} thiết bị đã chọn?', 'device.batchUnbindSuccess': 'Đã hủy liên kết thành công {count} thiết bị', 'device.batchUnbindError': 'Đã xảy ra lỗi khi hủy liên kết hàng loạt', - 'device.remarkTooLong': 'Ghi chú không được vượt quá 64 ký tự', - 'device.remarkSaved': 'Đã lưu ghi chú thành công', - 'device.remarkSaveFailed': 'Lưu ghi chú thất bại', + 'device.aliasTooLong': 'Bí danh thiết bị không được vượt quá 64 ký tự', + 'device.aliasSaved': 'Đã lưu bí danh thiết bị thành công', + 'device.aliasSaveFailed': 'Lưu bí danh thiết bị thất bại', 'device.confirmUnbind': 'Bạn có chắc chắn muốn hủy liên kết thiết bị này?', 'device.unbindSuccess': 'Đã hủy liên kết thiết bị thành công', 'device.unbindFailed': 'Hủy liên kết thiết bị thất bại', @@ -592,6 +594,7 @@ export default { // Dictionary management page text 'dictManagement.pageTitle': 'Quản lý từ điển', + 'dictManagement.dictTypeCategory': 'Danh mục từ điển', 'dictManagement.searchPlaceholder': 'Vui lòng nhập nhãn giá trị từ điển để tìm kiếm', 'dictManagement.search': 'Tìm kiếm', 'dictManagement.dictTypeName': 'Tên loại từ điển', @@ -646,6 +649,8 @@ export default { 'user.disable': 'Vô hiệu hóa', 'user.delete': 'Xóa', 'user.selectUsersFirst': 'Vui lòng chọn người dùng để xóa trước', + 'user.selectUsersToDisable': 'Vui lòng chọn người dùng để vô hiệu hóa', + 'user.selectUsersToEnable': 'Vui lòng chọn người dùng để kích hoạt', 'user.confirmDeleteSelected': 'Bạn có chắc chắn muốn xóa {count} người dùng đã chọn?', 'user.deleting': 'Đang xóa...', 'user.deleteSuccess': 'Đã xóa thành công {count} người dùng', @@ -705,6 +710,9 @@ export default { 'common.cancel': 'Hủy bỏ', 'common.sensitive': 'Nhạy cảm', 'common.loading': 'Đang tải', + 'common.copySuccess': 'Sao chép thành công', + 'common.copyFailed': 'Sao chép thất bại', + 'common.copyAddress': 'Sao chép địa chỉ', // Language switch 'language.en': 'English', @@ -727,7 +735,12 @@ export default { 'home.justNow': 'Vừa xong', 'home.minutesAgo': '{minutes} phút trước', 'home.hoursAgo': '{hours} giờ {minutes} phút trước', - 'home.confirmDeleteAgent': 'Bạn có chắc chắn muốn xóa tác nhân này?', + 'home.deleteConfirmTitle': 'Xóa đại lý', + 'home.confirmDeleteAgent': 'Không thể hoàn tác sau khi xóa. Nhập tên tác nhân "{agentName}" để xác nhận.', + 'home.deleteAgentNamePlaceholder': 'Nhập tên tác nhân', + 'home.deleteAgentNameMismatch': 'Tên tác nhân không khớp', + 'home.deleteAgentPasteForbidden': 'Vui lòng nhập thủ công tên tác nhân. Không được dán.', + 'home.deleteAgentMissingInfo': 'Không thể xác nhận thông tin tác nhân. Vui lòng tải lại rồi thử lại.', 'home.deleteSuccess': 'Xóa thành công', 'home.deleteFailed': 'Xóa thất bại', 'home.enableMemory': 'Vui lòng bật bộ nhớ trong trang \"Cấu hình vai trò\" trước', @@ -738,8 +751,10 @@ export default { 'paramManagement.search': 'Tìm kiếm', 'paramManagement.paramCode': 'Mã tham số', 'paramManagement.paramValue': 'Giá trị tham số', + 'paramManagement.valueType': 'Loại', 'paramManagement.remark': 'Ghi chú', 'paramManagement.operation': 'Thao tác', + 'paramManagement.select': 'Chọn', 'paramManagement.hide': 'Ẩn', 'paramManagement.view': 'Xem', 'paramManagement.deselectAll': 'Bỏ chọn tất cả', @@ -747,11 +762,29 @@ export default { 'paramManagement.add': 'Thêm', 'paramManagement.delete': 'Xóa', 'paramManagement.edit': 'Chỉnh sửa', + 'paramManagement.refresh': 'Làm mới', 'paramManagement.itemsPerPage': 'mục/trang', 'paramManagement.firstPage': 'Trang đầu', 'paramManagement.prevPage': 'Trang trước', 'paramManagement.nextPage': 'Trang sau', - 'paramManagement.totalRecords': 'Tổng cộng {total} bản ghi', + 'paramManagement.totalRecords': 'Tổng {total}', + 'paramManagement.selectedCount': 'Đã chọn {count}', + 'paramManagement.groupHint': 'Nhóm theo namespace', + 'paramManagement.emptyResult': 'Không có tham số phù hợp', + 'paramManagement.group.all': 'Tất cả', + 'paramManagement.group.server': 'Máy chủ', + 'paramManagement.group.plugins': 'Plugin', + 'paramManagement.group.log': 'Nhật ký', + 'paramManagement.group.session': 'Phiên', + 'paramManagement.group.general': 'Chung', + 'paramManagement.subgroup.root': 'Cơ bản', + 'paramManagement.subgroup.auth': 'Xác thực', + 'paramManagement.subgroup.connection': 'Kết nối', + 'paramManagement.subgroup.registry': 'Đăng ký', + 'paramManagement.subgroup.resilience': 'Resilience', + 'paramManagement.subgroup.metrics': 'Chỉ số', + 'paramManagement.subgroup.tracing': 'Tracing', + 'paramManagement.subgroup.plugin': 'Plugin · {name}', 'paramManagement.addParam': 'Thêm tham số', 'paramManagement.editParam': 'Chỉnh sửa tham số', 'paramManagement.getParamsListFailed': 'Không thể lấy danh sách tham số', @@ -786,7 +819,7 @@ export default { // Add agent dialog text 'addAgentDialog.title': 'Thêm tác nhân', 'addAgentDialog.agentName': 'Tên tác nhân', - 'addAgentDialog.placeholder': 'Vui lòng nhập tên tác nhân..', + 'addAgentDialog.placeholder': 'Vui lòng nhập tên tác nhân…', 'addAgentDialog.confirm': 'Xác nhận', 'addAgentDialog.cancel': 'Hủy bỏ', 'addAgentDialog.nameRequired': 'Vui lòng nhập tên tác nhân', @@ -797,12 +830,129 @@ export default { 'roleConfig.addTag': 'Thêm mới nhãn', 'roleConfig.restartNotice': 'Sau khi lưu cấu hình, bạn cần khởi động lại thiết bị để cấu hình mới có hiệu lực.', 'roleConfig.saveConfig': 'Lưu cấu hình', + 'roleConfig.snapshotHistory': 'Lịch sử phiên bản', + 'roleConfig.currentVersion': 'Phiên bản hiện tại {version}', + 'roleConfig.functionName': 'Tên chức năng', 'roleConfig.reset': 'Đặt lại', 'roleConfig.agentName': 'Biệt danh', 'roleConfig.roleTemplate': 'Mẫu', 'roleConfig.roleIntroduction': 'Giới thiệu', 'roleConfig.languageCode': 'Mã ngôn ngữ', 'roleConfig.interactionLanguage': 'Ngôn ngữ tương tác', + 'agentSnapshot.title': 'Lịch sử phiên bản', + 'agentSnapshot.empty': 'Chưa có phiên bản', + 'agentSnapshot.version': 'Phiên bản', + 'agentSnapshot.createdAt': 'Lưu lúc', + 'agentSnapshot.source': 'Nguồn', + 'agentSnapshot.changedFields': 'Thay đổi', + 'agentSnapshot.actions': 'Thao tác', + 'agentSnapshot.view': 'Xem', + 'agentSnapshot.restore': 'Khôi phục', + 'agentSnapshot.delete': 'Xóa', + 'agentSnapshot.detailTitle': 'Chi tiết thay đổi', + 'agentSnapshot.restorePreviewTitle': 'Xem trước khôi phục', + 'agentSnapshot.confirmRestore': 'Xác nhận khôi phục', + 'agentSnapshot.before': 'Trước', + 'agentSnapshot.after': 'Sau', + 'agentSnapshot.emptyValue': 'Không có', + 'agentSnapshot.secretRedacted': 'Khóa bí mật đã được ẩn', + 'agentSnapshot.configValue': 'Giá trị cấu hình', + 'agentSnapshot.noChangedContent': 'Không có thay đổi để hiển thị', + 'agentSnapshot.noFunctionChange': 'Không có thay đổi chức năng', + 'agentSnapshot.beforeChange': 'Trước thay đổi', + 'agentSnapshot.afterChange': 'Sau thay đổi', + 'agentSnapshot.beforeRestore': 'Trước khi khôi phục', + 'agentSnapshot.afterRestore': 'Sau khi khôi phục', + 'agentSnapshot.restoreMemoryWarning': 'Khôi phục về phiên bản không có bộ nhớ sẽ xóa lịch sử trò chuyện của tác nhân này. Chỉ tiếp tục sau khi xác nhận rủi ro này.', + 'agentSnapshot.restoreMemoryDestructiveWarning': 'Lần khôi phục này sẽ xóa vĩnh viễn lịch sử trò chuyện hiện có của tác nhân. Lịch sử trò chuyện không nằm trong ảnh chụp cấu hình và không thể khôi phục từ lịch sử phiên bản.', + 'agentSnapshot.unsavedChangesWarning': 'Các thay đổi chưa lưu trên trang này không được ghi vào lịch sử và sẽ bị loại bỏ sau khi khôi phục.', + 'agentSnapshot.restoreConfirm': 'Khôi phục về phiên bản {version}? Cấu hình hiện tại sẽ được giữ lại trong lịch sử.', + 'agentSnapshot.restoreSuccess': 'Đã khôi phục phiên bản', + 'agentSnapshot.restoreFailed': 'Khôi phục phiên bản thất bại', + 'agentSnapshot.restoreFailedRollback': 'Khôi phục phiên bản thất bại. Giao dịch đã được hoàn tác và cấu hình hiện tại chưa thay đổi', + 'agentSnapshot.deleteConfirm': 'Xóa phiên bản {version}? Không thể hoàn tác thao tác này.', + 'agentSnapshot.deleteSuccess': 'Đã xóa phiên bản lịch sử', + 'agentSnapshot.deleteFailed': 'Xóa phiên bản lịch sử thất bại', + 'agentSnapshot.fetchFailed': 'Không thể tải lịch sử phiên bản', + 'agentSnapshot.detailFailed': 'Không thể tải chi tiết snapshot', + 'agentSnapshot.currentVersion': 'Ảnh chụp mới nhất', + 'agentSnapshot.source.config': 'Lưu cấu hình', + 'agentSnapshot.source.current': 'Cấu hình hiện tại', + 'agentSnapshot.source.restore': 'Kết quả khôi phục', + 'agentSnapshot.source.initial': 'Phiên bản ban đầu', + 'agentSnapshot.field.restore': 'Khôi phục', + 'agentSnapshot.field.initial': 'Snapshot ban đầu', + 'agentSnapshot.field.agentCode': 'Mã tác nhân', + 'agentSnapshot.field.agentName': 'Biệt danh', + 'agentSnapshot.field.asrModelId': 'Nhận dạng giọng nói', + 'agentSnapshot.field.vadModelId': 'Phát hiện hoạt động giọng nói', + 'agentSnapshot.field.llmModelId': 'Mô hình ngôn ngữ chính', + 'agentSnapshot.field.slmModelId': 'Mô hình ngôn ngữ nhỏ', + 'agentSnapshot.field.vllmModelId': 'Mô hình thị giác', + 'agentSnapshot.field.ttsModelId': 'Văn bản thành giọng nói', + 'agentSnapshot.field.ttsVoiceId': 'Giọng nói', + 'agentSnapshot.field.ttsLanguage': 'Ngôn ngữ', + 'agentSnapshot.field.ttsVolume': 'Âm lượng', + 'agentSnapshot.field.ttsRate': 'Tốc độ', + 'agentSnapshot.field.ttsPitch': 'Cao độ', + 'agentSnapshot.field.memModelId': 'Mô hình bộ nhớ', + 'agentSnapshot.field.intentModelId': 'Nhận dạng ý định', + 'agentSnapshot.field.chatHistoryConf': 'Lịch sử trò chuyện', + 'agentSnapshot.field.systemPrompt': 'Giới thiệu', + 'agentSnapshot.field.summaryMemory': 'Bộ nhớ', + 'agentSnapshot.field.langCode': 'Mã ngôn ngữ', + 'agentSnapshot.field.language': 'Ngôn ngữ tương tác', + 'agentSnapshot.field.sort': 'Sắp xếp', + 'agentSnapshot.field.functions': 'Chức năng', + 'agentSnapshot.field.contextProviders': 'Nguồn ngữ cảnh', + 'agentSnapshot.field.correctWordFileIds': 'Từ thay thế', + 'agentSnapshot.field.tagNames': 'Nhãn', + 'agentSnapshot.field.tagIds': 'ID nhãn', + 'agentSnapshot.function.added': 'Đã bật', + 'agentSnapshot.function.removed': 'Đã tắt', + 'agentSnapshot.function.updated': 'Tham số đã thay đổi', + 'agentSnapshot.function.enabled': 'Đã bật', + 'agentSnapshot.function.disabled': 'Đã tắt', + 'agentSnapshot.function.disabledNote': 'Chức năng này đang tắt', + 'agentSnapshot.function.noParams': 'Không cần cấu hình tham số', + 'agentSnapshot.chatHistoryConf.none': 'Không ghi lịch sử trò chuyện', + 'agentSnapshot.chatHistoryConf.text': 'Báo cáo văn bản', + 'agentSnapshot.chatHistoryConf.textVoice': 'Báo cáo văn bản và giọng nói', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_WEATHER': 'Thời tiết', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_MUSIC': 'Trình phát nhạc máy chủ', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_NEWS_CHINANEWS': 'Tin tức China News', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_NEWS_NEWSNOW': 'Tổng hợp NewsNow', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_HA_STATE': 'Điều khiển thiết bị HomeAssistant', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_HA_PLAY_MUSIC': 'Trình phát nhạc HomeAssistant', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_WEB_SEARCH': 'Tìm kiếm web', + 'agentSnapshot.plugin.SYSTEM_PLUGIN_CALL_DEVICE': 'Gọi thiết bị', + 'agentSnapshot.pluginField.url': 'URL điểm cuối', + 'agentSnapshot.pluginField.news_sources': 'Nguồn tin', + 'agentSnapshot.pluginField.default_rss_url': 'URL RSS mặc định', + 'agentSnapshot.pluginField.society_rss_url': 'URL RSS xã hội', + 'agentSnapshot.pluginField.world_rss_url': 'URL RSS thế giới', + 'agentSnapshot.pluginField.finance_rss_url': 'URL RSS tài chính', + 'agentSnapshot.pluginField.api_key': 'Khóa API', + 'agentSnapshot.pluginField.default_location': 'Thành phố mặc định', + 'agentSnapshot.pluginField.api_host': 'Máy chủ API nhà phát triển', + 'agentSnapshot.pluginField.base_url': 'URL máy chủ', + 'agentSnapshot.pluginField.devices': 'Thiết bị', + 'agentSnapshot.pluginField.provider': 'Nhà cung cấp tìm kiếm', + 'agentSnapshot.pluginField.description': 'Mô tả công cụ', + 'agentSnapshot.pluginField.max_results': 'Số lượng kết quả', + 'agentSnapshot.model.Memory_nomem': 'Không có bộ nhớ', + 'agentSnapshot.model.Memory_mem_local_short': 'Bộ nhớ ngắn cục bộ', + 'agentSnapshot.model.Memory_mem0ai': 'Bộ nhớ Mem0AI', + 'agentSnapshot.model.Memory_mem_report_only': 'Chỉ báo cáo bộ nhớ', + 'agentSnapshot.model.Intent_nointent': 'Không nhận dạng ý định', + 'agentSnapshot.model.Intent_intent_llm': 'Nhận dạng ý định bằng LLM bên ngoài', + 'agentSnapshot.model.Intent_function_call': 'LLM gọi hàm', + 'agentSnapshot.voice.TTS_EdgeTTS0001': 'EdgeTTS nữ - Xiaoxiao', + 'agentSnapshot.voice.TTS_EdgeTTS0002': 'EdgeTTS nam - Yunyang', + 'agentSnapshot.voice.TTS_EdgeTTS0003': 'EdgeTTS nữ - Xiaoyi', + 'agentSnapshot.voice.TTS_EdgeTTS0004': 'EdgeTTS nam - Yunjian', + 'agentSnapshot.voice.TTS_EdgeTTS0005': 'EdgeTTS nam - Yunxi', + 'agentSnapshot.voice.TTS_EdgeTTS0006': 'EdgeTTS nam - Yunxia', 'roleConfig.vad': 'Phát hiện giọng nói', 'roleConfig.asr': 'Nhận dạng giọng nói', 'roleConfig.llm': 'Mô hình ngôn ngữ chính', @@ -1115,6 +1265,8 @@ export default { 'agentTemplateManagement.action': 'Hành động', 'agentTemplateManagement.createTemplate': 'Tạo mẫu', 'templateQuickConfig.newTemplate': 'Mẫu mới', + 'templateQuickConfig.editTemplate': 'Chỉnh sửa mẫu', + 'templateQuickConfig.addTemplate': 'Thêm mẫu', 'agentTemplateManagement.editTemplate': 'Chỉnh sửa mẫu', 'agentTemplateManagement.deleteTemplate': 'Xóa mẫu', 'agentTemplateManagement.deleteSuccess': 'Đã xóa mẫu thành công', @@ -1194,6 +1346,8 @@ export default { 'voiceClone.operationClosed': 'Đã đóng popup', 'voiceClone.cloneSuccess': 'Nhân bản thành công', 'voiceClone.cloneFailed': 'Nhân bản thất bại', + 'voiceClone.cloneErrorTip': 'Nhân bản thất bại, hãy di chuột qua thông báo lỗi để xem chi tiết', + 'voiceClone.apiError': 'Lỗi gọi API', 'voiceClone.confirmClone': 'Bạn có chắc chắn muốn nhân bản giọng này?', 'voiceClone.onlySuccessCanClone': 'Chỉ có thể nhân bản giọng đã huấn luyện thành công', 'common.insufficient': 'Không đủ', @@ -1211,6 +1365,7 @@ export default { 'voiceClone.training': 'Đang huấn luyện', 'voiceClone.trainSuccess': 'Huấn luyện thành công', 'voiceClone.trainFailed': 'Huấn luyện thất bại', + 'voiceClone.trainFailedWithError': 'Huấn luyện thất bại: {error}', 'voiceClone.itemsPerPage': '{items} mục/trang', 'voiceClone.firstPage': 'Trang đầu', 'voiceClone.prevPage': 'Trang trước', @@ -1322,10 +1477,6 @@ export default { 'knowledgeFileUpload.viewSlices': 'Xem các phần', 'knowledgeFileUpload.delete': 'Xóa', 'knowledgeFileUpload.itemsPerPage': 'mục/trang', - 'knowledgeFileUpload.firstPage': 'Trang đầu', - 'knowledgeFileUpload.prevPage': 'Trang trước', - 'knowledgeFileUpload.nextPage': 'Trang sau', - 'knowledgeFileUpload.totalRecords': 'Tổng cộng {total} bản ghi', 'knowledgeFileUpload.uploadDocument': 'Tải lên tài liệu', 'knowledgeFileUpload.documentNamePlaceholder': 'Vui lòng nhập tên tài liệu', 'knowledgeFileUpload.file': 'Tệp', @@ -1364,10 +1515,7 @@ export default { 'knowledgeFileUpload.sliceCount': 'Số lượng phần', 'knowledgeFileUpload.add': 'Thêm', 'knowledgeFileUpload.retrievalTest': 'Kiểm tra truy xuất', - 'knowledgeFileUpload.testQuestion': 'Câu hỏi kiểm tra', - 'knowledgeFileUpload.testQuestionPlaceholder': 'Vui lòng nhập câu hỏi để kiểm tra', 'knowledgeFileUpload.executeTest': 'Thực thi kiểm tra', - 'knowledgeFileUpload.testResult': 'Kết quả kiểm tra:', 'knowledgeFileUpload.selectedFiles': 'Tệp đã chọn', 'knowledgeFileUpload.totalSlices': 'Tổng cộng {total} bản ghi', 'knowledgeFileUpload.slice': 'Phần', @@ -1412,8 +1560,6 @@ export default { 'featureManagement.groupDescription.featureManagement': 'Kiểm soát trạng thái kích hoạt của các mô-đun tính năng cốt lõi', 'featureManagement.groupDescription.voiceManagement': 'Cấu hình các tính năng hiển thị và khả dụng cho agent (trợ lý AI)', 'featureManagement.moduleCount': 'Tổng cộng {count} mô-đun', - 'featureManagement.enabled': 'Đã bật', - 'featureManagement.disabled': 'Chưa bật', // Feature names and descriptions 'feature.voiceprintRecognition.name': 'Nhận dạng giọng nói', @@ -1434,12 +1580,10 @@ export default { // Trang quản lý danh bạ 'addressBookManagement.title': 'Quản lý danh bạ', 'addressBookManagement.searchPlaceholder': 'Tìm kiếm tên thiết bị hoặc địa chỉ MAC', - 'addressBookManagement.search': 'Tìm kiếm', 'addressBookManagement.selectAgent': 'Vui lòng chọn tác tử', 'addressBookManagement.name': 'Tên danh bạ', 'addressBookManagement.description': 'Mô tả danh bạ', 'addressBookManagement.contactCount': 'Số liên hệ', - 'addressBookManagement.status': 'Kích hoạt', 'addressBookManagement.createdAt': 'Thời gian tạo', 'addressBookManagement.operation': 'Thao tác', 'addressBookManagement.add': 'Thêm', @@ -1460,9 +1604,7 @@ export default { 'addressBookManagement.operationCancelled': 'Đã hủy thao tác xóa', 'addressBookManagement.updateSuccess': 'Cập nhật thành công', 'addressBookManagement.addSuccess': 'Thêm thành công', - 'addressBookManagement.updateFailed': 'Cập nhật thất bại', 'addressBookManagement.addFailed': 'Thêm thất bại', - 'addressBookManagement.selectAll': 'Chọn tất cả', 'addressBookManagement.cancelSelectAll': 'Bỏ chọn tất cả', 'addressBookManagement.deviceName': 'Tên thiết bị', 'addressBookManagement.deviceType': 'Loại thiết bị', @@ -1477,9 +1619,7 @@ export default { 'addressBookManagement.addressBookDescPlaceholder': 'Vui lòng nhập mô tả danh bạ', 'addressBookManagement.remarksPlaceholder': 'Vui lòng nhập ghi chú', 'addressBookManagement.selectDevice': 'Vui lòng chọn thiết bị để xem chi tiết danh bạ', - 'addressBookManagement.save': 'Lưu', 'addressBookManagement.saveSuccess': 'Lưu thành công', - 'addressBookManagement.saveFailed': 'Lưu thất bại', 'addressBookManagement.deviceNotSelected': 'Vui lòng chọn thiết bị trước', 'addressBookManagement.addDeviceTip': 'Tính năng thêm thiết bị đang phát triển', 'addressBookManagement.selectAgentFirst': 'Vui lòng chọn tác tử trước', diff --git a/main/manager-web/src/main.js b/main/manager-web/src/main.js index 85cb3697a..10417724b 100644 --- a/main/manager-web/src/main.js +++ b/main/manager-web/src/main.js @@ -6,6 +6,7 @@ import App from './App.vue'; import router from './router'; import store from './store'; import i18n from './i18n'; +import locale from 'element-ui/lib/locale' import './styles/global.scss'; import { register as registerServiceWorker } from './registerServiceWorker'; import featureManager from './utils/featureManager'; diff --git a/main/manager-web/src/utils/date.js b/main/manager-web/src/utils/date.js index c6210bc0d..84b0a9270 100755 --- a/main/manager-web/src/utils/date.js +++ b/main/manager-web/src/utils/date.js @@ -39,6 +39,7 @@ function formatDateTool(date, fmt) { const o = { 'M+': date.getMonth() + 1, 'd+': date.getDate(), + 'H+': date.getHours(), 'h+': date.getHours(), 'm+': date.getMinutes(), 's+': date.getSeconds() diff --git a/main/manager-web/src/utils/deviceTime.mjs b/main/manager-web/src/utils/deviceTime.mjs new file mode 100644 index 000000000..f1c1a64be --- /dev/null +++ b/main/manager-web/src/utils/deviceTime.mjs @@ -0,0 +1,41 @@ +export function hasTimestampValue(timestamp) { + if (timestamp === null || timestamp === undefined) return false; + return typeof timestamp !== 'string' || timestamp.trim() !== ''; +} + +export function parseTimestamp(timestamp) { + if (!hasTimestampValue(timestamp)) return null; + if (typeof timestamp !== 'number' && typeof timestamp !== 'string') return null; + + const normalizedTimestamp = typeof timestamp === 'string' ? timestamp.trim() : timestamp; + const parsedTimestamp = Number(normalizedTimestamp); + if (!Number.isFinite(parsedTimestamp)) return null; + + return Number.isNaN(new Date(parsedTimestamp).getTime()) ? null : parsedTimestamp; +} + +export function parseLegacyDate(dateValue) { + if (!dateValue) return null; + const timestamp = new Date(dateValue).getTime(); + return Number.isNaN(timestamp) ? null : timestamp; +} + +export function formatTimestamp(timestamp, formatter = value => new Date(value).toLocaleString()) { + const parsedTimestamp = parseTimestamp(timestamp); + return parsedTimestamp === null ? '-' : formatter(parsedTimestamp); +} + +export function formatCreateDate(timestamp, legacyDate, formatter) { + if (!hasTimestampValue(timestamp)) return legacyDate || '-'; + return formatTimestamp(timestamp, formatter); +} + +export function compareTimestamps(firstTimestamp, secondTimestamp) { + const firstIsValid = Number.isFinite(firstTimestamp); + const secondIsValid = Number.isFinite(secondTimestamp); + + if (firstIsValid && secondIsValid) return firstTimestamp - secondTimestamp; + if (firstIsValid) return -1; + if (secondIsValid) return 1; + return 0; +} diff --git a/main/manager-web/src/views/AddressBookManagement.vue b/main/manager-web/src/views/AddressBookManagement.vue index c0cec0c95..5b33dfb9b 100644 --- a/main/manager-web/src/views/AddressBookManagement.vue +++ b/main/manager-web/src/views/AddressBookManagement.vue @@ -15,10 +15,9 @@ :placeholder="$t('addressBookManagement.searchPlaceholder')" v-model="searchKeyword" class="search-input" - @keyup.enter="handleSearch" + @input="handleSearch" clearable /> - {{ $t('addressBookManagement.search') }} @@ -121,7 +120,7 @@
{{ $t('addressBookManagement.addTime') }}
-
{{ selectedDevice.createDate || '-' }}
+
{{ formatDeviceCreateDate(selectedDevice) }}
@@ -142,25 +141,24 @@

{{ $t('addressBookManagement.setPermissionDesc', { count: selectedPermissions.length }) }}

- {{ $t('common.cancel') }} - - {{ isAllSelected ? $t('addressBookManagement.deselectAll') : $t('addressBookManagement.selectAll') }} - - {{ $t('addressBookManagement.save') }} + {{ $t('common.cancel') }} + {{ isAllSelected ? $t('addressBookManagement.deselectAll') : $t('addressBookManagement.selectAll') }} + {{ $t('addressBookManagement.save') }}
-
+
avatar @@ -209,10 +207,12 @@ import VersionFooter from "@/components/VersionFooter.vue"; import Api from "@/apis/api.js"; import AddressBookApi from "@/apis/module/addressBook.js"; import MacAddressMask from "@/components/MacAddressMask.vue"; +import CustomButton from "@/components/CustomButton.vue"; +import { formatCreateDate, parseTimestamp } from '@/utils/deviceTime.mjs'; export default { name: "AddressBookManagement", - components: { HeaderBar, VersionFooter, MacAddressMask }, + components: { HeaderBar, VersionFooter, MacAddressMask, CustomButton }, data() { return { searchKeyword: "", @@ -230,7 +230,9 @@ export default { editAgentNameValue: '', editingDeviceId: null, editingDeviceName: '', - mqttServiceAvailable: false + mqttServiceAvailable: false, + permissionRequestSequence: 0, + permissionsLoading: false }; }, created() { @@ -283,7 +285,8 @@ export default { remarks: device.alias || '', online: false, createDate: device.createDate, - lastConnectedAt: device.lastConnectedAt, + createDateTimestamp: device.createDateTimestamp, + lastConnectedAt: device.lastConnectedAtTimestamp, deviceStatus: 'offline' })); resolve(); @@ -291,8 +294,11 @@ export default { }); }); Promise.all(agentPromises).then(() => { + const firstDevice = agentList[0] || {}; this.agentDeviceOptions = agentList; this.filteredAgents = agentList; + // 默认选中第一项 + this.handleDeviceClick(firstDevice.devices?.[0] || {}, firstDevice); // 获取设备状态 this.fetchDeviceStatus(); }); @@ -348,17 +354,6 @@ export default { } }); }, - handleAgentClick(agent) { - if (this.expandedAgentId === agent.id) { - this.expandedAgentId = null; - this.selectedAgent = null; - this.selectedDevice = null; - } else { - this.expandedAgentId = agent.id; - this.selectedAgent = agent; - this.selectedDevice = null; - } - }, handleDeviceClick(device, agent) { this.expandedAgentId = agent.id; this.selectedAgent = agent; @@ -371,18 +366,45 @@ export default { this.loadAddressBookPermissions(device.deviceId); }, loadAddressBookPermissions(macAddress) { + const requestId = ++this.permissionRequestSequence; + this.permissionsLoading = true; + this.selectedPermissions = []; + this.originalPermissions = []; + this.editingDeviceId = null; + this.editingDeviceName = ''; + this.allDevices.forEach(device => { + device.addressBookAlias = ''; + }); AddressBookApi.getAddressBookList(macAddress, (res) => { + if ( + requestId !== this.permissionRequestSequence || + this.selectedDevice?.deviceId !== macAddress + ) { + return; + } + this.permissionsLoading = false; if (res.data?.code === 0) { const permissions = res.data.data || []; + const permissionsByTargetMac = new Map( + permissions.map(permission => [ + (permission.targetMac || '').toLowerCase(), + permission + ]) + ); // 设置已选择的权限 - this.selectedPermissions = permissions - .filter(p => p.hasPermission) - .map(p => p.targetMac); + const permittedTargetMacs = new Set( + permissions + .filter(p => p.hasPermission) + .map(p => (p.targetMac || '').toLowerCase()) + ); + this.selectedPermissions = this.allDevices + .filter(device => permittedTargetMacs.has((device.deviceId || '').toLowerCase())) + .map(device => device.deviceId); // 保存初始权限状态(用于对比变更) this.originalPermissions = [...this.selectedPermissions]; // 更新设备的通讯录别名 this.allDevices.forEach(device => { - const addrBook = permissions.find(p => p.targetMac === device.deviceId); + const addrBook = permissionsByTargetMac.get((device.deviceId || '').toLowerCase()); if (addrBook) { device.addressBookAlias = addrBook.alias || ''; } else { @@ -393,6 +415,7 @@ export default { }); }, handleStartEditPermission(device) { + if (this.permissionsLoading) return; this.editingDeviceId = device.id; this.editingDeviceName = device.addressBookAlias || device.name; this.$nextTick(() => { @@ -410,8 +433,8 @@ export default { alias: newName }, (res) => { if (res.data?.code === 0) { - device.addressBookAlias = newName; this.$message.success(this.$t('addressBookManagement.aliasSaved')); + this.loadAddressBookPermissions(this.selectedDevice.deviceId); } else { this.$message.error(res.data?.msg || this.$t('addressBookManagement.saveFailed')); } @@ -420,13 +443,14 @@ export default { this.editingDeviceId = null; this.editingDeviceName = ''; }, - handlePermissionToggle(deviceId, checked) { + handlePermissionToggle(targetMac, checked) { + if (this.permissionsLoading) return; if (checked) { - if (!this.selectedPermissions.includes(deviceId)) { - this.selectedPermissions.push(deviceId); + if (!this.selectedPermissions.includes(targetMac)) { + this.selectedPermissions.push(targetMac); } } else { - const index = this.selectedPermissions.indexOf(deviceId); + const index = this.selectedPermissions.indexOf(targetMac); if (index > -1) { this.selectedPermissions.splice(index, 1); } @@ -436,21 +460,22 @@ export default { if (this.isAllSelected) { this.selectedPermissions = []; } else { - this.selectedPermissions = this.allDevices.map(d => d.id); + this.selectedPermissions = this.allDevices.map(d => d.deviceId); } }, handleCancel() { this.selectedPermissions = []; }, handleSavePermissions() { + if (this.permissionsLoading) return; const promises = this.allDevices .filter(device => { - const isNowSelected = this.selectedPermissions.includes(device.id); - const wasOriginallySelected = this.originalPermissions.includes(device.id); + const isNowSelected = this.selectedPermissions.includes(device.deviceId); + const wasOriginallySelected = this.originalPermissions.includes(device.deviceId); return isNowSelected !== wasOriginallySelected; }) .map(device => { - const hasPermission = this.selectedPermissions.includes(device.id); + const hasPermission = this.selectedPermissions.includes(device.deviceId); return new Promise((resolve) => { AddressBookApi.updatePermission({ macAddress: this.selectedDevice.deviceId, @@ -467,6 +492,7 @@ export default { } else if (results.every(r => r)) { this.$message.success(this.$t('addressBookManagement.permissionSaved')); this.originalPermissions = [...this.selectedPermissions]; + this.loadAddressBookPermissions(this.selectedDevice.deviceId); } else { this.$message.error(this.$t('addressBookManagement.partialSaveFailed')); } @@ -535,9 +561,10 @@ export default { this.isEditingAgentName = false; }, getTimeAgo(timestamp) { - if (!timestamp) return '-'; + const ts = parseTimestamp(timestamp); + if (ts === null) return '-'; const now = new Date(); - const date = new Date(timestamp); + const date = new Date(ts); const diff = now - date; const seconds = Math.floor(diff / 1000); @@ -554,6 +581,10 @@ export default { if (months < 12) return this.$t('addressBookManagement.monthsAgo', { months }); return this.$t('addressBookManagement.yearsAgo', { years }); }, + formatDeviceCreateDate(device) { + if (!device) return '-'; + return formatCreateDate(device.createDateTimestamp, device.createDate); + }, getDeviceAvatar(deviceId) { // 根据 deviceId 计算 MD5,选择对应的头像 const avatars = [ @@ -595,7 +626,7 @@ export default { display: flex; flex-direction: column; background-size: cover; - background: linear-gradient(to bottom right, #dce8ff, #e4eeff, #e6cbfd) center; + background: #eff4ff; -webkit-background-size: cover; -o-background-size: cover; overflow: hidden; @@ -815,21 +846,20 @@ export default { font-size: 12px; color: #686f85; text-align: left; + gap: 4px; .online { - margin-left: 4px; color: #686f85; display: inline-flex; align-items: center; gap: 4px; .status-dot { - margin-top: -3px; - margin-right: 4px; width: 9px; height: 9px; border-radius: 50%; background: #4eb36c; + flex-shrink: 0; } } @@ -840,12 +870,11 @@ export default { gap: 4px; .status-dot { - margin-top: -3px; - margin-right: 4px; width: 9px; height: 9px; border-radius: 50%; background: #999; + flex-shrink: 0; } } } @@ -954,8 +983,8 @@ export default { } .section-actions { + margin-top: 4px; display: flex; - gap: 8px; } } } @@ -1138,14 +1167,6 @@ export default { flex: 1; } -.btn-search { - padding: 10px 20px; - background: linear-gradient(135deg, #6b8cff, #a966ff); - border: none; - color: white; - width: 80px; -} - .agent-card { width: 100%; padding: 12px 0px; diff --git a/main/manager-web/src/views/AgentTemplateManagement.vue b/main/manager-web/src/views/AgentTemplateManagement.vue index 6cd56a029..3367350b8 100644 --- a/main/manager-web/src/views/AgentTemplateManagement.vue +++ b/main/manager-web/src/views/AgentTemplateManagement.vue @@ -130,8 +130,54 @@ @size-change="handlePageSizeChange" @current-change="handlePageChange" /> + + {{ $t("agentTemplateManagement.search") }} +
+ + + + + +
@@ -163,22 +209,38 @@ export default { currentPage: 1, pageSize: 10, total: 0, + tableColumns: [], + dialogVisible: false, + dialogTitle: "", + confirmLoading: false, + form: { + id: null, + agentCode: "小智", + agentName: "", + systemPrompt: "", + sort: 0, + model: { ...DEFAULT_MODEL_CONFIG } + }, + formRules: { + agentName: [ + { required: true, message: "请输入助手昵称", trigger: "blur" } + ], + systemPrompt: [ + { required: true, message: "请输入角色介绍", trigger: "blur" } + ] + }, + originalForm: null }; }, created() { + this.initTableColumns(); this.loadTemplateList(); }, // Add hasSelected property in computed section computed: { - pageCount() { - return Math.ceil(this.total / this.pageSize); - }, - visiblePages() { - return this.getVisiblePages(); - }, hasSelected() { return this.selectedTemplates.length > 0; - }, + } }, methods: { // Load template list @@ -187,7 +249,7 @@ export default { this.templateLoading = true; const params = { page: this.currentPage, - limit: this.pageSize, + limit: this.pageSize }; if (this.search) { params.agentName = this.search; @@ -226,30 +288,23 @@ export default { (error) => { this.templateList = []; this.total = 0; - this.templateLoading = false; - this.$message.error(this.$t("common.networkError")); + this.$message.error(res?.data?.msg || this.$t("agentTemplateManagement.fetchTemplateFailed")); } - ); - } catch (error) { - this.templateList = []; - this.total = 0; - this.templateLoading = false; - this.$message.error(this.$t("agentTemplateManagement.fetchTemplateBackendError")); - } + this.templateLoading = false; + }, + (error) => { + this.templateList = []; + this.total = 0; + this.templateLoading = false; + this.$message.error(this.$t("common.networkError")); + } + ); }, // Search templates handleSearch() { - if (this.search) { - const searchValue = this.search.toLowerCase(); - const filteredList = this.templateList.filter((template) => - template.agentName.toLowerCase().includes(searchValue) - ); - this.templateList = filteredList; - this.total = filteredList.length; - } else { - this.loadTemplateList(); - } + this.currentPage = 1; + this.loadTemplateList(); }, // Modify showAddTemplateDialog method to navigate to same page as edit page @@ -269,6 +324,9 @@ export default { query: { templateId: row.id }, }); }, + handleDialogConfirm() { + this.$refs.dialogForm.validate((valid) => { + if (!valid) return; // Delete template deleteTemplate(row) { @@ -278,7 +336,7 @@ export default { { confirmButtonText: this.$t("common.confirm"), cancelButtonText: this.$t("common.cancel"), - type: "warning", + type: "warning" } ) .then(() => { @@ -294,7 +352,7 @@ export default { ); } } else { - this.$message.error(this.$t("agentTemplateManagement.deleteBackendError")); + this.$message.error(res?.data?.msg || this.$t("agentTemplateManagement.deleteFailed")); } }); }) @@ -309,22 +367,18 @@ export default { this.$message.warning(this.$t("agentTemplateManagement.selectTemplate")); return; } - this.$confirm( - this.$t("agentTemplateManagement.confirmBatchDelete", { - count: this.selectedTemplates.length, - }), + this.$t("agentTemplateManagement.confirmBatchDelete", { count: this.selectedTemplates.length }), this.$t("common.warning"), { confirmButtonText: this.$t("common.confirm"), cancelButtonText: this.$t("common.cancel"), - type: "warning", + type: "warning" } ) .then(() => { // Ensure parameter format is correct - use id array as request body const ids = this.selectedTemplates.map((template) => template.id); - agentApi.batchDeleteAgentTemplate(ids, (res) => { if (res && typeof res === "object") { if (res.data && res.data.code === 0) { @@ -342,7 +396,7 @@ export default { ); } } else { - this.$message.error(this.$t("agentTemplateManagement.deleteBackendError")); + this.$message.error(res?.data?.msg || this.$t("agentTemplateManagement.batchDeleteFailed")); } }); }) @@ -356,7 +410,6 @@ export default { this.currentPage = page; this.loadTemplateList(); }, - handlePageSizeChange(size) { this.pageSize = size; this.currentPage = 1; @@ -429,41 +482,43 @@ export default { this.isAllSelected = this.templateList.length > 0 && this.selectedTemplates.length === this.templateList.length; - }, - }, + } + } }; + +:deep(.el-table .el-button--text) { + color: #7079aa; +} + +:deep(.el-table .el-button--text:hover) { + color: #5a64b5; +} + \ No newline at end of file diff --git a/main/manager-web/src/views/DeviceManagement.vue b/main/manager-web/src/views/DeviceManagement.vue index a897352ba..a4709ee68 100644 --- a/main/manager-web/src/views/DeviceManagement.vue +++ b/main/manager-web/src/views/DeviceManagement.vue @@ -2,118 +2,83 @@
-
-

{{ $t('device.management') }}

-
- - {{ $t('device.search') }} -
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- - {{ isCurrentPageAllSelected ? $t('common.deselectAll') : $t('common.selectAll') }} - - - {{ $t('device.bindWithCode') }} - - - {{ $t('device.manualAdd') }} - - - {{ $t('device.unbind') }} - -
-
- - - - - - - - - - {{ $t('dictManagement.totalRecords').replace('{total}', deviceList.length) }} - +
+

{{ $t('device.management') }}

+
+ + {{ $t('device.search') }}
+ + + + + + + + +
@@ -136,6 +101,16 @@ import HeaderBar from "@/components/HeaderBar.vue"; import ManualAddDeviceDialog from "@/components/ManualAddDeviceDialog.vue"; import VersionFooter from "@/components/VersionFooter.vue"; import MacAddressMask from "@/components/MacAddressMask.vue"; +import CustomButton from "@/components/CustomButton.vue"; +import CustomTable from "@/components/CustomTable.vue"; +import { + compareTimestamps, + formatCreateDate, + formatTimestamp, + hasTimestampValue, + parseLegacyDate, + parseTimestamp, +} from '@/utils/deviceTime.mjs'; export default { components: { @@ -144,6 +119,8 @@ export default { ManualAddDeviceDialog, VersionFooter, MacAddressMask, + CustomButton, + CustomTable, }, data() { return { @@ -160,7 +137,7 @@ export default { loading: false, userApi: null, firmwareTypes: [], - mqttServiceAvailable: false, // MQTT服务是否可用 + mqttServiceAvailable: false, }; }, computed: { @@ -178,28 +155,24 @@ export default { const end = start + this.pageSize; return this.filteredDeviceList.slice(start, end); }, - pageCount() { - return Math.ceil(this.filteredDeviceList.length / this.pageSize); - }, - // 计算当前页是否全选 isCurrentPageAllSelected() { return this.paginatedDeviceList.length > 0 && this.paginatedDeviceList.every(device => device.selected); }, - visiblePages() { - const pages = []; - const maxVisible = 3; - let start = Math.max(1, this.currentPage - 1); - let end = Math.min(this.pageCount, start + maxVisible - 1); - - if (end - start + 1 < maxVisible) { - start = Math.max(1, end - maxVisible + 1); + tableColumns() { + const columns = [ + { prop: 'model', label: this.$t('device.model'), align: 'center' }, + { prop: 'firmwareVersion', label: this.$t('device.firmwareVersion'), align: 'center' }, + { prop: 'macAddress', label: this.$t('device.macAddress'), align: 'center' }, + { prop: 'bindTime', label: this.$t('device.bindTime'), align: 'center' }, + { prop: 'lastConversation', label: this.$t('device.lastConversation'), align: 'center' }, + ]; + if (this.mqttServiceAvailable) { + columns.push({ prop: 'deviceStatus', label: this.$t('device.deviceStatus'), align: 'center' }); } - - for (let i = start; i <= end; i++) { - pages.push(i); - } - return pages; + columns.push({ prop: 'alias', label: this.$t('device.alias'), align: 'center' }); + columns.push({ prop: 'otaSwitch', label: this.$t('device.autoUpdate'), align: 'center' }); + return columns; }, }, mounted() { @@ -289,41 +262,39 @@ export default { handleManualAddDevice() { this.manualAddDeviceDialogVisible = true; }, - submitRemark(row) { + submitAlias(row) { if (row._submitting) return; - const text = (row.remark || '').trim(); + const text = (row.alias || '').trim(); if (text.length > 64) { - this.$message.warning(this.$t('device.remarkTooLong')); + this.$message.warning(this.$t('device.aliasTooLong')); return; } - if (text === row._originalRemark) { + if (text === row._originalAlias) { return; } row._submitting = true; this.updateDeviceInfo(row.device_id, { alias: text }, (ok, resp) => { if (ok) { - row._originalRemark = text; - this.$message.success(this.$t('device.remarkSaved')); + row._originalAlias = text; + this.$message.success(this.$t('device.aliasSaved')); } else { - row.remark = row._originalRemark; - this.$message.error(resp.msg || this.$t('device.remarkSaveFailed')); + row.alias = row._originalAlias; + this.$message.error(resp.msg || this.$t('device.aliasSaveFailed')); } row._submitting = false; }); }, - // 备注输入框:失焦时提交 - onRemarkBlur(row) { + onAliasBlur(row) { row.isEdit = false; setTimeout(() => { - this.submitRemark(row); - }, 100); // 延迟 100ms,避开 enter+blur 同时触发的窗口 + this.submitAlias(row); + }, 100); }, - // 备注输入框:按回车时提交 - onRemarkEnter(row) { + onAliasEnter(row) { row.isEdit = false; - this.submitRemark(row); + this.submitAlias(row); }, handleUnbind(device_id) { this.$confirm(this.$t('device.confirmUnbind'), this.$t('message.warning'), { @@ -354,15 +325,6 @@ export default { sessionStorage.setItem('devicePath', window.location.href); window.location.href = url; }, - goFirst() { - this.currentPage = 1; - }, - goPrev() { - if (this.currentPage > 1) this.currentPage--; - }, - goNext() { - if (this.currentPage < this.pageCount) this.currentPage++; - }, goToPage(page) { this.currentPage = page; }, @@ -373,31 +335,34 @@ export default { this.loading = false; if (data.code === 0) { this.deviceList = data.data.map(device => { + const hasCreateDateTimestamp = hasTimestampValue(device.createDateTimestamp); + const rawBindTime = hasCreateDateTimestamp + ? parseTimestamp(device.createDateTimestamp) + : parseLegacyDate(device.createDate); return { device_id: device.id, model: device.board, firmwareVersion: device.appVersion, macAddress: device.macAddress, - bindTime: device.createDate, - lastConversation: device.lastConnectedAtTimestamp - ? this.formatRelativeTime(device.lastConnectedAtTimestamp) - : '-', - remark: device.alias, - _originalRemark: device.alias, + bindTime: formatCreateDate(device.createDateTimestamp, device.createDate), + lastConversation: formatTimestamp(device.lastConnectedAtTimestamp), + alias: device.alias, + _originalAlias: device.alias, isEdit: false, _submitting: false, otaSwitch: device.autoUpdate === 1, - rawBindTime: new Date(device.createDate).getTime(), + rawBindTime, selected: false, - // 初始设置为离线状态 deviceStatus: 'offline' }; }) - .sort((a, b) => a.rawBindTime - b.rawBindTime); + .sort((firstDevice, secondDevice) => compareTimestamps( + firstDevice.rawBindTime, + secondDevice.rawBindTime, + )); this.activeSearchKeyword = ""; this.searchKeyword = ""; - // 获取设备列表后,立即获取设备状态 this.fetchDeviceStatus(agentId); } else { this.$message.error(data.msg || this.$t('device.getListFailed')); @@ -405,47 +370,35 @@ export default { }); }, - // 获取设备状态 fetchDeviceStatus(agentId) { - // 开启表格等待状态,处理动态加载表头导致鼠标所在行的hover事件无法移除的问题 this.loading = true; Api.device.getDeviceStatus(agentId, ({ data }) => { this.loading = false; if (data.code === 0) { try { - // 解析后端返回的设备状态JSON const statusData = JSON.parse(data.data); - // 直接使用解析后的数据作为设备状态映射(不需要devices字段包装) if (statusData && typeof statusData === 'object') { - // 成功获取到设备状态 this.mqttServiceAvailable = true; - // 更新设备状态 this.updateDeviceStatusFromResponse(statusData); } else { - // 数据格式不正确,MQTT服务不可用 this.mqttServiceAvailable = false; } } catch (error) { - // JSON解析失败,MQTT服务不可用 this.mqttServiceAvailable = false; } } else { - // 接口调用失败,MQTT服务不可用 this.mqttServiceAvailable = false; } }); }, - // 根据API响应更新设备状态 updateDeviceStatusFromResponse(deviceStatusMap) { this.deviceList.forEach(device => { - // 构建设备的MQTT客户端ID const macAddress = device.macAddress ? device.macAddress.replace(/:/g, '_') : 'unknown'; const groupId = device.model ? device.model.replace(/:/g, '_') : 'GID_default'; const mqttClientId = `${groupId}@@@${macAddress}@@@${macAddress}`; - // 从状态映射中获取设备状态 if (deviceStatusMap[mqttClientId]) { const statusInfo = deviceStatusMap[mqttClientId]; @@ -462,17 +415,10 @@ export default { device.deviceStatus = isOnline ? 'online' : 'offline'; } else { - // 如果没有找到对应的状态信息,默认为离线 device.deviceStatus = 'offline'; } }); }, - headerCellClassName({ columnIndex }) { - if (columnIndex === 0) { - return "custom-selection-header"; - } - return ""; - }, getFirmwareTypeName(type) { const firmwareType = this.firmwareTypes.find(item => item.key === type) return firmwareType ? firmwareType.name : type @@ -492,24 +438,15 @@ export default { this.$message.error(msg || this.$t('message.error')) }) }, - // 判断是否可以生成表情、主题、字体bin文件 isGenerate(row) { const version = row.firmwareVersion.replace(/\./g, ''); return Number(version) >= 200; }, - formatRelativeTime(timestamp) { - if (!timestamp) return '-'; - const ts = Number(timestamp); - if (isNaN(ts)) return '-'; - const date = new Date(ts); - if (isNaN(date.getTime())) return '-'; - return date.toLocaleString(); // 自动适配本地时区 - }, } }; - diff --git a/main/manager-web/src/views/DictManagement.vue b/main/manager-web/src/views/DictManagement.vue index 7cece1d80..e05f9ea5c 100644 --- a/main/manager-web/src/views/DictManagement.vue +++ b/main/manager-web/src/views/DictManagement.vue @@ -1,18 +1,17 @@ \ No newline at end of file + diff --git a/main/manager-web/src/views/FeatureManagement.vue b/main/manager-web/src/views/FeatureManagement.vue index f38eff561..9e67f518a 100644 --- a/main/manager-web/src/views/FeatureManagement.vue +++ b/main/manager-web/src/views/FeatureManagement.vue @@ -8,13 +8,13 @@

{{ $t('header.featureManagement') }}

- + {{ isAllSelected ? $t('featureManagement.deselectAll') : $t('featureManagement.selectAll') }} - + {{ $t('featureManagement.reset') }} - + {{ isSaving ? $t('featureManagement.saving') : $t('featureManagement.save') }}
@@ -45,19 +45,17 @@

{{ $t(`feature.${feature.id}.name`) }}

- {{ $t('featureManagement.enabled') }} - {{ $t('featureManagement.disabled') }} +
+ +

{{ $t(`feature.${feature.id}.description`) }}

-
- -
@@ -84,19 +82,17 @@

{{ $t(`feature.${feature.id}.name`) }}

- {{ $t('featureManagement.enabled') }} - {{ $t('featureManagement.disabled') }} +
+ +

{{ $t(`feature.${feature.id}.description`) }}

-
- -
@@ -360,7 +356,9 @@ export default { } - diff --git a/main/manager-web/src/views/ModelConfig.vue b/main/manager-web/src/views/ModelConfig.vue index 399a3531c..411fb94f4 100644 --- a/main/manager-web/src/views/ModelConfig.vue +++ b/main/manager-web/src/views/ModelConfig.vue @@ -96,7 +96,8 @@