mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
fix(westernization): English copy, audit hardening, and generator sync
- Finishes rebase follow-up: API/mobile/server strings and i18n tooltips - Tightens westernization audit script and playbook wording - Aligns public generator assets with rebuilt output
This commit is contained in:
parent
1aeb0794f1
commit
36ddc0bad2
40 changed files with 324 additions and 261 deletions
|
|
@ -157,22 +157,22 @@ public interface Constant {
|
||||||
String MEMORY_MEM_REPORT_ONLY = "Memory_mem_report_only";
|
String MEMORY_MEM_REPORT_ONLY = "Memory_mem_report_only";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mem0AI记忆
|
* Mem0AI memory.
|
||||||
*/
|
*/
|
||||||
String MEMORY_MEM0AI = "Memory_mem0ai";
|
String MEMORY_MEM0AI = "Memory_mem0ai";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* PowerMem记忆
|
* PowerMem memory.
|
||||||
*/
|
*/
|
||||||
String MEMORY_POWERMEM = "Memory_powermem";
|
String MEMORY_POWERMEM = "Memory_powermem";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 火山引擎双声道语音克隆
|
* Huoshan double-stream voice clone.
|
||||||
*/
|
*/
|
||||||
String VOICE_CLONE_HUOSHAN_DOUBLE_STREAM = "huoshan_double_stream";
|
String VOICE_CLONE_HUOSHAN_DOUBLE_STREAM = "huoshan_double_stream";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* RAG配置类型
|
* RAG config type.
|
||||||
*/
|
*/
|
||||||
String RAG_CONFIG_TYPE = "RAG";
|
String RAG_CONFIG_TYPE = "RAG";
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -153,7 +153,7 @@ public class AgentController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/chat-title/{sessionId}/generate")
|
@PostMapping("/chat-title/{sessionId}/generate")
|
||||||
@Operation(summary = "根据会话ID生成聊天标题")
|
@Operation(summary = "Generate chat title by session ID")
|
||||||
public Result<Void> generateAndSaveChatTitle(@PathVariable String sessionId) {
|
public Result<Void> generateAndSaveChatTitle(@PathVariable String sessionId) {
|
||||||
agentChatSummaryService.generateAndSaveChatTitle(sessionId);
|
agentChatSummaryService.generateAndSaveChatTitle(sessionId);
|
||||||
return new Result<Void>().ok(null);
|
return new Result<Void>().ok(null);
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,7 @@ public class AgentChatSessionDTO {
|
||||||
private Integer chatCount;
|
private Integer chatCount;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 会话标题
|
* Chat title.
|
||||||
*/
|
*/
|
||||||
private String title;
|
private String title;
|
||||||
}
|
}
|
||||||
|
|
@ -33,10 +33,10 @@ public class AgentUpdateDTO implements Serializable {
|
||||||
@Schema(description = "LLM model ID", example = "llm_model_02", nullable = true)
|
@Schema(description = "LLM model ID", example = "llm_model_02", nullable = true)
|
||||||
private String llmModelId;
|
private String llmModelId;
|
||||||
|
|
||||||
@Schema(description = "小模型标识", example = "slm_model_02", nullable = true)
|
@Schema(description = "Small model ID", example = "slm_model_02", nullable = true)
|
||||||
private String slmModelId;
|
private String slmModelId;
|
||||||
|
|
||||||
@Schema(description = "VLLM模型标识", example = "vllm_model_02", required = false)
|
@Schema(description = "VLLM model ID", example = "vllm_model_02", required = false)
|
||||||
private String vllmModelId;
|
private String vllmModelId;
|
||||||
|
|
||||||
@Schema(description = "TTS model ID", example = "tts_model_02", required = false)
|
@Schema(description = "TTS model ID", example = "tts_model_02", required = false)
|
||||||
|
|
|
||||||
|
|
@ -37,10 +37,10 @@ public class AgentEntity {
|
||||||
@Schema(description = "LLM model ID")
|
@Schema(description = "LLM model ID")
|
||||||
private String llmModelId;
|
private String llmModelId;
|
||||||
|
|
||||||
@Schema(description = "小模型标识")
|
@Schema(description = "Small model ID")
|
||||||
private String slmModelId;
|
private String slmModelId;
|
||||||
|
|
||||||
@Schema(description = "VLLM模型标识")
|
@Schema(description = "VLLM model ID")
|
||||||
private String vllmModelId;
|
private String vllmModelId;
|
||||||
|
|
||||||
@Schema(description = "TTS model ID")
|
@Schema(description = "TTS model ID")
|
||||||
|
|
|
||||||
|
|
@ -14,10 +14,10 @@ public interface AgentChatSummaryService {
|
||||||
boolean generateAndSaveChatSummary(String sessionId);
|
boolean generateAndSaveChatSummary(String sessionId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据会话ID生成聊天标题并保存
|
* Generate and save a chat title by session ID.
|
||||||
*
|
*
|
||||||
* @param sessionId 会话ID
|
* @param sessionId session ID
|
||||||
* @return 是否成功
|
* @return whether generation succeeded
|
||||||
*/
|
*/
|
||||||
boolean generateAndSaveChatTitle(String sessionId);
|
boolean generateAndSaveChatTitle(String sessionId);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -105,7 +105,7 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService {
|
||||||
String memModelId = agentService.getAgentById(agentId).getMemModelId();
|
String memModelId = agentService.getAgentById(agentId).getMemModelId();
|
||||||
|
|
||||||
if (memModelId == null || memModelId.equals(Constant.MEMORY_MEM_REPORT_ONLY)) {
|
if (memModelId == null || memModelId.equals(Constant.MEMORY_MEM_REPORT_ONLY)) {
|
||||||
log.info("会话 {} 使用仅上报聊天记录模式,跳过记忆总结", sessionId);
|
log.info("Session {} uses report-only chat history mode; skipping memory summarization", sessionId);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -121,12 +121,12 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService {
|
||||||
setSummaryMemory(summaryDTO.getSummary());
|
setSummaryMemory(summaryDTO.getSummary());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
log.info("成功保存会话 {} 的聊天记录总结到智能体 {}", sessionId, agentId);
|
log.info("Saved chat summary for session {} to agent {}", sessionId, agentId);
|
||||||
} else {
|
} else {
|
||||||
log.info("生成总结失败: {}", summaryDTO.getErrorMessage());
|
log.info("Summary generation failed: {}", summaryDTO.getErrorMessage());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.info("会话 {} 使用 {} 模式,跳过记忆总结", sessionId, memModelId);
|
log.info("Session {} uses {} mode; skipping memory summarization", sessionId, memModelId);
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|
@ -140,10 +140,10 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService {
|
||||||
@Override
|
@Override
|
||||||
public boolean generateAndSaveChatTitle(String sessionId) {
|
public boolean generateAndSaveChatTitle(String sessionId) {
|
||||||
try {
|
try {
|
||||||
// 自动获取agentId
|
// Resolve agentId automatically.
|
||||||
String agentId = findAgentIdBySessionId(sessionId);
|
String agentId = findAgentIdBySessionId(sessionId);
|
||||||
if (StringUtils.isBlank(agentId)) {
|
if (StringUtils.isBlank(agentId)) {
|
||||||
log.warn("会话 {} 无法获取智能体信息,跳过标题生成", sessionId);
|
log.warn("Unable to resolve agent information for session {}; skipping title generation", sessionId);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -159,7 +159,7 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService {
|
||||||
|
|
||||||
StringBuilder conversation = new StringBuilder();
|
StringBuilder conversation = new StringBuilder();
|
||||||
for (int i = 0; i < meaningfulMessages.size(); i++) {
|
for (int i = 0; i < meaningfulMessages.size(); i++) {
|
||||||
conversation.append("消息").append(i + 1).append(": ").append(meaningfulMessages.get(i)).append("\n");
|
conversation.append("Message ").append(i + 1).append(": ").append(meaningfulMessages.get(i)).append("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
String slmModelId = getSlmModelId(agentId);
|
String slmModelId = getSlmModelId(agentId);
|
||||||
|
|
@ -167,12 +167,12 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService {
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(title)) {
|
if (StringUtils.isNotBlank(title)) {
|
||||||
agentChatTitleService.saveOrUpdateTitle(sessionId, title);
|
agentChatTitleService.saveOrUpdateTitle(sessionId, title);
|
||||||
log.info("成功保存会话 {} 的标题: {}", sessionId, title);
|
log.info("Saved title for session {}: {}", sessionId, title);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("生成会话 {} 的标题时发生错误: {}", sessionId, e.getMessage());
|
log.error("Error while generating title for session {}: {}", sessionId, e.getMessage());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -190,21 +190,21 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService {
|
||||||
|
|
||||||
String slmModelId = agentInfo.getSlmModelId();
|
String slmModelId = agentInfo.getSlmModelId();
|
||||||
if (StringUtils.isNotBlank(slmModelId)) {
|
if (StringUtils.isNotBlank(slmModelId)) {
|
||||||
log.info("会话 {} 使用SLM模型: {}", agentId, slmModelId);
|
log.info("Agent {} uses SLM model: {}", agentId, slmModelId);
|
||||||
return slmModelId;
|
return slmModelId;
|
||||||
}
|
}
|
||||||
|
|
||||||
ModelConfigEntity defaultLlmConfig = getDefaultLLMConfig();
|
ModelConfigEntity defaultLlmConfig = getDefaultLLMConfig();
|
||||||
if (defaultLlmConfig != null) {
|
if (defaultLlmConfig != null) {
|
||||||
log.info("会话 {} 使用默认LLM模型: {}", agentId, defaultLlmConfig.getId());
|
log.info("Agent {} uses default LLM model: {}", agentId, defaultLlmConfig.getId());
|
||||||
return defaultLlmConfig.getId();
|
return defaultLlmConfig.getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
String llmModelId = agentInfo.getLlmModelId();
|
String llmModelId = agentInfo.getLlmModelId();
|
||||||
log.info("会话 {} 使用LLM模型(最终回退): {}", agentId, llmModelId);
|
log.info("Agent {} uses LLM model as final fallback: {}", agentId, llmModelId);
|
||||||
return llmModelId;
|
return llmModelId;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("获取智能体slm模型ID失败,agentId: {}, 错误: {}", agentId, e.getMessage());
|
log.error("Failed to get agent SLM model ID, agentId: {}, error: {}", agentId, e.getMessage());
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -224,7 +224,7 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService {
|
||||||
|
|
||||||
return llmConfigs.get(0);
|
return llmConfigs.get(0);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("获取默认LLM配置失败: {}", e.getMessage());
|
log.error("Failed to get default LLM config: {}", e.getMessage());
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -411,7 +411,7 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService {
|
||||||
String modelId = getSlmModelId(agentId);
|
String modelId = getSlmModelId(agentId);
|
||||||
|
|
||||||
if (StringUtils.isBlank(modelId)) {
|
if (StringUtils.isBlank(modelId)) {
|
||||||
log.info("未找到SLM模型,使用默认LLM服务");
|
log.info("No SLM model found; using default LLM service");
|
||||||
return llmService.generateSummaryWithHistory(conversation, historyMemory, null, null);
|
return llmService.generateSummaryWithHistory(conversation, historyMemory, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -439,7 +439,7 @@ public class AgentChatSummaryServiceImpl implements AgentChatSummaryService {
|
||||||
String modelId = getSlmModelId(agentId);
|
String modelId = getSlmModelId(agentId);
|
||||||
|
|
||||||
if (StringUtils.isBlank(modelId)) {
|
if (StringUtils.isBlank(modelId)) {
|
||||||
log.info("未找到SLM模型,使用默认LLM服务");
|
log.info("No SLM model found; using default LLM service");
|
||||||
return llmService.generateSummary(conversation);
|
return llmService.generateSummary(conversation);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -205,7 +205,7 @@ public class ConfigServiceImpl implements ConfigService {
|
||||||
result.put("mcp_endpoint", mcpEndpoint);
|
result.put("mcp_endpoint", mcpEndpoint);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取上下文源配置
|
// Context-provider configuration.
|
||||||
AgentContextProviderEntity contextProviderEntity = agentContextProviderService.getByAgentId(agent.getId());
|
AgentContextProviderEntity contextProviderEntity = agentContextProviderService.getByAgentId(agent.getId());
|
||||||
if (contextProviderEntity != null && contextProviderEntity.getContextProviders() != null
|
if (contextProviderEntity != null && contextProviderEntity.getContextProviders() != null
|
||||||
&& !contextProviderEntity.getContextProviders().isEmpty()) {
|
&& !contextProviderEntity.getContextProviders().isEmpty()) {
|
||||||
|
|
@ -459,7 +459,7 @@ public class ConfigServiceImpl implements ConfigService {
|
||||||
|
|
||||||
Map<String, Object> map = (Map<String, Object>) model.getConfigJson();
|
Map<String, Object> map = (Map<String, Object>) model.getConfigJson();
|
||||||
if (Constant.VOICE_CLONE_HUOSHAN_DOUBLE_STREAM.equals(map.get("type"))) {
|
if (Constant.VOICE_CLONE_HUOSHAN_DOUBLE_STREAM.equals(map.get("type"))) {
|
||||||
// 如果voice是”S_”开头的,使用seed-icl-1.0
|
// Use seed-icl-1.0 when the voice starts with S_.
|
||||||
if (voice != null && voice.startsWith("S_")) {
|
if (voice != null && voice.startsWith("S_")) {
|
||||||
map.put("resource_id", "seed-icl-1.0");
|
map.put("resource_id", "seed-icl-1.0");
|
||||||
}
|
}
|
||||||
|
|
@ -508,7 +508,7 @@ public class ConfigServiceImpl implements ConfigService {
|
||||||
typeConfig.put(memLocalShortLLM.getId(), memLocalShortLLM.getConfigJson());
|
typeConfig.put(memLocalShortLLM.getId(), memLocalShortLLM.getConfigJson());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// LLM也返回所选的SLM,如果同名id则不重复显示
|
// Return the selected SLM with LLM config, avoiding duplicate IDs.
|
||||||
if (StringUtils.isNotBlank(slmModelId) && !slmModelId.equals(llmModelId)) {
|
if (StringUtils.isNotBlank(slmModelId) && !slmModelId.equals(llmModelId)) {
|
||||||
if (!typeConfig.containsKey(slmModelId)) {
|
if (!typeConfig.containsKey(slmModelId)) {
|
||||||
ModelConfigEntity slmModel = modelConfigService.getModelByIdFromCache(slmModelId);
|
ModelConfigEntity slmModel = modelConfigService.getModelByIdFromCache(slmModelId);
|
||||||
|
|
|
||||||
|
|
@ -133,7 +133,7 @@ public class DatasetDTO {
|
||||||
private ParserConfig parserConfig;
|
private ParserConfig parserConfig;
|
||||||
|
|
||||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
@Schema(description = "PageRank 权重 (0-100)", example = "50")
|
@Schema(description = "PageRank weight (0-100)", example = "50")
|
||||||
private Integer pagerank;
|
private Integer pagerank;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -173,24 +173,24 @@ public abstract class KnowledgeBaseAdapter {
|
||||||
public abstract DatasetDTO.BatchOperationVO deleteDataset(DatasetDTO.BatchIdReq req);
|
public abstract DatasetDTO.BatchOperationVO deleteDataset(DatasetDTO.BatchIdReq req);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取数据集的文档数量
|
* Return the document count for a dataset.
|
||||||
*
|
*
|
||||||
* @param datasetId 数据集ID
|
* @param datasetId dataset ID
|
||||||
* @return 文档数量
|
* @return document count
|
||||||
*/
|
*/
|
||||||
public abstract Integer getDocumentCount(String datasetId);
|
public abstract Integer getDocumentCount(String datasetId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取数据集完整信息(名称、简介、文档数量等)
|
* Return full dataset information such as name, description, and document count.
|
||||||
* 用于检测 RAGFlow 端是否已删除、同步名称/简介变更
|
* Used to detect remote deletion and synchronize name/description updates from RAGFlow.
|
||||||
*
|
*
|
||||||
* @param datasetId 数据集ID
|
* @param datasetId dataset ID
|
||||||
* @return 数据集详情,若 RAGFlow 端不存在则返回 null
|
* @return dataset details, or null when it no longer exists in RAGFlow
|
||||||
*/
|
*/
|
||||||
public abstract DatasetDTO.InfoVO getDatasetInfo(String datasetId);
|
public abstract DatasetDTO.InfoVO getDatasetInfo(String datasetId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 发送流式请求 (SSE)
|
* Send a streaming request over SSE.
|
||||||
*
|
*
|
||||||
* @param endpoint API endpoint
|
* @param endpoint API endpoint
|
||||||
* @param body request body
|
* @param body request body
|
||||||
|
|
|
||||||
|
|
@ -492,7 +492,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("获取文档数量失败: {}", e.getMessage());
|
log.warn("Failed to load document count: {}", e.getMessage());
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -514,10 +514,10 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter {
|
||||||
return objectMapper.convertValue(list.get(0), DatasetDTO.InfoVO.class);
|
return objectMapper.convertValue(list.get(0), DatasetDTO.InfoVO.class);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// RAGFlow 端不存在该数据集
|
// Dataset no longer exists in RAGFlow.
|
||||||
return null;
|
return null;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("获取数据集信息失败: datasetId={}, error={}", datasetId, e.getMessage());
|
log.warn("Failed to load dataset information: datasetId={}, error={}", datasetId, e.getMessage());
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -122,11 +122,11 @@ public interface KnowledgeFilesService {
|
||||||
void syncRunningDocuments();
|
void syncRunningDocuments();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从RAGFlow全量同步文档到本地影子表
|
* Fully synchronize documents from RAGFlow into the local shadow table.
|
||||||
* 拉取远端所有文档,与本地影子表对比,插入缺失的记录
|
* Fetch all remote documents, compare with the local shadow table, and insert missing records.
|
||||||
*
|
*
|
||||||
* @param datasetId 数据集ID
|
* @param datasetId dataset ID
|
||||||
* @return 新同步的文档数量
|
* @return number of newly synchronized documents
|
||||||
*/
|
*/
|
||||||
int syncDocumentsFromRAG(String datasetId);
|
int syncDocumentsFromRAG(String datasetId);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -72,8 +72,8 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
||||||
if (pageData != null && pageData.getList() != null) {
|
if (pageData != null && pageData.getList() != null) {
|
||||||
pageData.getList().removeIf(dto -> {
|
pageData.getList().removeIf(dto -> {
|
||||||
enrichDocumentCount(dto);
|
enrichDocumentCount(dto);
|
||||||
// syncDatasetFromRAG 检测到 RAGFlow 端已删除时,会将本地记录清理
|
// syncDatasetFromRAG cleans local records when RAGFlow reports remote deletion.
|
||||||
// 此时 datasetId 被置空作为标记,需要在列表中移除该条目
|
// The datasetId is cleared as a marker, so this row should be removed from the list.
|
||||||
return dto.getDatasetId() == null;
|
return dto.getDatasetId() == null;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -85,8 +85,8 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从 RAGFlow 同步数据集信息:检测删除、同步名称/简介、获取文档数量
|
* Synchronize dataset information from RAGFlow: deletion status, name/description, and document count.
|
||||||
* 每次列表刷新时实时查询 RAGFlow,确保立即感知远端变更
|
* Query RAGFlow during each list refresh so remote changes are detected immediately.
|
||||||
*/
|
*/
|
||||||
private void syncDatasetFromRAG(KnowledgeBaseDTO dto) {
|
private void syncDatasetFromRAG(KnowledgeBaseDTO dto) {
|
||||||
try {
|
try {
|
||||||
|
|
@ -102,20 +102,20 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
||||||
DatasetDTO.InfoVO datasetInfo = adapter.getDatasetInfo(dto.getDatasetId());
|
DatasetDTO.InfoVO datasetInfo = adapter.getDatasetInfo(dto.getDatasetId());
|
||||||
|
|
||||||
if (datasetInfo == null) {
|
if (datasetInfo == null) {
|
||||||
// RAGFlow 端已删除 → 本地级联清理
|
// Remote dataset was deleted in RAGFlow; perform local cascade cleanup.
|
||||||
log.info("数据集 {} 在 RAGFlow 端不存在,执行本地清理", dto.getDatasetId());
|
log.info("Dataset {} no longer exists in RAGFlow, cleaning local records", dto.getDatasetId());
|
||||||
cleanupLocalDataset(dto.getDatasetId(), dto.getId());
|
cleanupLocalDataset(dto.getDatasetId(), dto.getId());
|
||||||
// 标记为已删除,让上层从列表中移除
|
// Mark as deleted so callers remove it from the list.
|
||||||
dto.setDatasetId(null);
|
dto.setDatasetId(null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 同步名称(去掉 username_ 前缀)
|
// Synchronize name after stripping the username prefix.
|
||||||
String ragflowName = datasetInfo.getName();
|
String ragflowName = datasetInfo.getName();
|
||||||
if (StringUtils.isNotBlank(ragflowName)) {
|
if (StringUtils.isNotBlank(ragflowName)) {
|
||||||
String localName = ragflowName.contains("_") ? ragflowName.substring(ragflowName.indexOf('_') + 1) : ragflowName;
|
String localName = ragflowName.contains("_") ? ragflowName.substring(ragflowName.indexOf('_') + 1) : ragflowName;
|
||||||
if (!localName.equals(dto.getName())) {
|
if (!localName.equals(dto.getName())) {
|
||||||
log.info("同步知识库名称: {} -> {}", dto.getName(), localName);
|
log.info("Synchronized knowledge base name: {} -> {}", dto.getName(), localName);
|
||||||
KnowledgeBaseEntity entity = knowledgeBaseDao.selectById(dto.getId());
|
KnowledgeBaseEntity entity = knowledgeBaseDao.selectById(dto.getId());
|
||||||
if (entity != null) {
|
if (entity != null) {
|
||||||
entity.setName(localName);
|
entity.setName(localName);
|
||||||
|
|
@ -125,12 +125,12 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 同步简介
|
// Synchronize description.
|
||||||
String ragflowDesc = datasetInfo.getDescription();
|
String ragflowDesc = datasetInfo.getDescription();
|
||||||
String localDesc = dto.getDescription();
|
String localDesc = dto.getDescription();
|
||||||
boolean descChanged = (ragflowDesc == null && localDesc != null) || (ragflowDesc != null && !ragflowDesc.equals(localDesc));
|
boolean descChanged = (ragflowDesc == null && localDesc != null) || (ragflowDesc != null && !ragflowDesc.equals(localDesc));
|
||||||
if (descChanged) {
|
if (descChanged) {
|
||||||
log.info("同步知识库简介: datasetId={}", dto.getDatasetId());
|
log.info("Synchronized knowledge base description: datasetId={}", dto.getDatasetId());
|
||||||
KnowledgeBaseEntity entity = knowledgeBaseDao.selectById(dto.getId());
|
KnowledgeBaseEntity entity = knowledgeBaseDao.selectById(dto.getId());
|
||||||
if (entity != null) {
|
if (entity != null) {
|
||||||
entity.setDescription(ragflowDesc);
|
entity.setDescription(ragflowDesc);
|
||||||
|
|
@ -139,35 +139,35 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置文档数量(保留原有功能)
|
// Set document count while preserving existing behavior.
|
||||||
if (datasetInfo.getDocumentCount() != null) {
|
if (datasetInfo.getDocumentCount() != null) {
|
||||||
dto.setDocumentCount(datasetInfo.getDocumentCount().intValue());
|
dto.setDocumentCount(datasetInfo.getDocumentCount().intValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("同步数据集信息失败 {}: {}", dto.getName(), e.getMessage());
|
log.warn("Failed to synchronize dataset information {}: {}", dto.getName(), e.getMessage());
|
||||||
dto.setDocumentCount(0);
|
dto.setDocumentCount(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 本地级联清理:RAGFlow 端已删除时,清理本地所有关联数据
|
* Local cascade cleanup when the dataset was deleted in RAGFlow.
|
||||||
* 不调用 RAGFlow 删除 API
|
* Does not call the RAGFlow delete API.
|
||||||
*/
|
*/
|
||||||
@Transactional(rollbackFor = Exception.class)
|
@Transactional(rollbackFor = Exception.class)
|
||||||
public void cleanupLocalDataset(String datasetId, String entityId) {
|
public void cleanupLocalDataset(String datasetId, String entityId) {
|
||||||
try {
|
try {
|
||||||
// 1. 删除文档影子记录
|
// 1. Delete document shadow records.
|
||||||
documentDao.delete(new QueryWrapper<DocumentEntity>().eq("dataset_id", datasetId));
|
documentDao.delete(new QueryWrapper<DocumentEntity>().eq("dataset_id", datasetId));
|
||||||
// 2. 删除插件映射
|
// 2. Delete plugin mappings.
|
||||||
knowledgeBaseDao.deletePluginMappingByKnowledgeBaseId(entityId);
|
knowledgeBaseDao.deletePluginMappingByKnowledgeBaseId(entityId);
|
||||||
// 3. 删除知识库记录
|
// 3. Delete the knowledge base record.
|
||||||
knowledgeBaseDao.deleteById(entityId);
|
knowledgeBaseDao.deleteById(entityId);
|
||||||
// 4. 清理缓存
|
// 4. Clear caches.
|
||||||
redisUtils.delete(RedisKeys.getKnowledgeBaseCacheKey(entityId));
|
redisUtils.delete(RedisKeys.getKnowledgeBaseCacheKey(entityId));
|
||||||
log.info("本地级联清理完成: datasetId={}, entityId={}", datasetId, entityId);
|
log.info("Local cascade cleanup completed: datasetId={}, entityId={}", datasetId, entityId);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("本地级联清理失败: datasetId={}, entityId={}", datasetId, entityId, e);
|
log.error("Local cascade cleanup failed: datasetId={}, entityId={}", datasetId, entityId, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -78,14 +78,14 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
|
||||||
throw new RenException(ErrorCode.RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL);
|
throw new RenException(ErrorCode.RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 全量对账同步: 从RAGFlow拉取远端文档,实时同步确保立即感知远端变更
|
// Full reconciliation: pull remote documents from RAGFlow so remote changes are detected immediately.
|
||||||
try {
|
try {
|
||||||
self.syncDocumentsFromRAG(datasetId);
|
self.syncDocumentsFromRAG(datasetId);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("从RAGFlow全量同步文档失败(不影响本地查询): datasetId={}, error={}", datasetId, e.getMessage());
|
log.warn("Full document sync from RAGFlow failed; local query can continue: datasetId={}, error={}", datasetId, e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. 获取本地影子表数据 (MyBatis-Plus 分页)
|
// 1. Load local shadow-table data with MyBatis-Plus pagination.
|
||||||
Page<DocumentEntity> pageParams = new Page<>(page, limit);
|
Page<DocumentEntity> pageParams = new Page<>(page, limit);
|
||||||
QueryWrapper<DocumentEntity> queryWrapper = new QueryWrapper<>();
|
QueryWrapper<DocumentEntity> queryWrapper = new QueryWrapper<>();
|
||||||
queryWrapper.eq("dataset_id", datasetId);
|
queryWrapper.eq("dataset_id", datasetId);
|
||||||
|
|
@ -419,10 +419,10 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 原子化保存影子记录(Upsert 语义)
|
* Save the shadow record atomically with upsert semantics.
|
||||||
* 若 document_id 已存在则更新,不存在则插入,避免 UNIQUE 约束冲突
|
* Update existing document IDs or insert missing ones to avoid UNIQUE constraint conflicts.
|
||||||
*
|
*
|
||||||
* @return true=新插入, false=更新已有记录
|
* @return true for a new insert, false for an existing record update
|
||||||
*/
|
*/
|
||||||
@Transactional(rollbackFor = Exception.class)
|
@Transactional(rollbackFor = Exception.class)
|
||||||
public boolean saveDocumentShadow(String datasetId, KnowledgeFilesDTO result, String originalName, String chunkMethod,
|
public boolean saveDocumentShadow(String datasetId, KnowledgeFilesDTO result, String originalName, String chunkMethod,
|
||||||
|
|
@ -467,21 +467,21 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
|
||||||
entity.setCreatedAt(result.getCreatedAt() != null ? result.getCreatedAt() : new Date());
|
entity.setCreatedAt(result.getCreatedAt() != null ? result.getCreatedAt() : new Date());
|
||||||
entity.setUpdatedAt(result.getUpdatedAt() != null ? result.getUpdatedAt() : new Date());
|
entity.setUpdatedAt(result.getUpdatedAt() != null ? result.getUpdatedAt() : new Date());
|
||||||
|
|
||||||
// Upsert: 检查 document_id 是否已存在,存在则更新,不存在则插入
|
// Upsert: update existing document IDs and insert missing ones.
|
||||||
DocumentEntity existing = documentDao.selectOne(
|
DocumentEntity existing = documentDao.selectOne(
|
||||||
new QueryWrapper<DocumentEntity>().eq("document_id", entity.getDocumentId()));
|
new QueryWrapper<DocumentEntity>().eq("document_id", entity.getDocumentId()));
|
||||||
|
|
||||||
if (existing != null) {
|
if (existing != null) {
|
||||||
entity.setId(existing.getId());
|
entity.setId(existing.getId());
|
||||||
entity.setCreatedAt(existing.getCreatedAt()); // 保留原始创建时间
|
entity.setCreatedAt(existing.getCreatedAt()); // Preserve original creation time.
|
||||||
documentDao.updateById(entity);
|
documentDao.updateById(entity);
|
||||||
log.info("影子记录已更新: documentId={}", entity.getDocumentId());
|
log.info("Shadow record updated: documentId={}", entity.getDocumentId());
|
||||||
return false;
|
return false;
|
||||||
} else {
|
} else {
|
||||||
documentDao.insert(entity);
|
documentDao.insert(entity);
|
||||||
// 新增记录时递增数据集文档总数统计
|
// Increment dataset document statistics when inserting a new record.
|
||||||
knowledgeBaseService.updateStatistics(datasetId, 1, 0L, 0L);
|
knowledgeBaseService.updateStatistics(datasetId, 1, 0L, 0L);
|
||||||
log.info("影子记录已插入: documentId={}, datasetId={}", entity.getDocumentId(), datasetId);
|
log.info("Shadow record inserted: documentId={}, datasetId={}", entity.getDocumentId(), datasetId);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -769,13 +769,13 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int syncDocumentsFromRAG(String datasetId) {
|
public int syncDocumentsFromRAG(String datasetId) {
|
||||||
log.info("=== 开始从RAGFlow全量同步文档到本地影子表: datasetId={} ===", datasetId);
|
log.info("=== Starting full RAGFlow-to-shadow-table document sync: datasetId={} ===", datasetId);
|
||||||
|
|
||||||
// 1. 获取适配器
|
// 1. Load adapter.
|
||||||
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
|
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
|
||||||
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig);
|
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig);
|
||||||
|
|
||||||
// 2. 分页拉取远端所有文档
|
// 2. Page through all remote documents.
|
||||||
List<KnowledgeFilesDTO> allRemoteDocs = new ArrayList<>();
|
List<KnowledgeFilesDTO> allRemoteDocs = new ArrayList<>();
|
||||||
int pageNum = 1;
|
int pageNum = 1;
|
||||||
int pageSize = 100;
|
int pageSize = 100;
|
||||||
|
|
@ -795,20 +795,20 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
|
||||||
pageNum++;
|
pageNum++;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 获取本地已有文档
|
// 3. Load existing local documents.
|
||||||
List<DocumentEntity> localDocs = documentDao.selectList(
|
List<DocumentEntity> localDocs = documentDao.selectList(
|
||||||
new QueryWrapper<DocumentEntity>().eq("dataset_id", datasetId));
|
new QueryWrapper<DocumentEntity>().eq("dataset_id", datasetId));
|
||||||
Set<String> localDocIds = localDocs.stream()
|
Set<String> localDocIds = localDocs.stream()
|
||||||
.map(DocumentEntity::getDocumentId)
|
.map(DocumentEntity::getDocumentId)
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
// 4. 远端文档ID集合
|
// 4. Build the set of remote document IDs.
|
||||||
Set<String> remoteDocIds = allRemoteDocs.stream()
|
Set<String> remoteDocIds = allRemoteDocs.stream()
|
||||||
.map(KnowledgeFilesDTO::getDocumentId)
|
.map(KnowledgeFilesDTO::getDocumentId)
|
||||||
.filter(id -> id != null)
|
.filter(id -> id != null)
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
// 5. 补充: 插入远端存在但本地缺失的文档
|
// 5. Insert documents that exist remotely but are missing locally.
|
||||||
List<KnowledgeFilesDTO> newDocs = allRemoteDocs.stream()
|
List<KnowledgeFilesDTO> newDocs = allRemoteDocs.stream()
|
||||||
.filter(doc -> doc.getDocumentId() != null && !localDocIds.contains(doc.getDocumentId()))
|
.filter(doc -> doc.getDocumentId() != null && !localDocIds.contains(doc.getDocumentId()))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
@ -818,7 +818,7 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
|
||||||
for (KnowledgeFilesDTO doc : newDocs) {
|
for (KnowledgeFilesDTO doc : newDocs) {
|
||||||
try {
|
try {
|
||||||
self.saveDocumentShadow(datasetId, doc, doc.getName(), doc.getChunkMethod(), doc.getParserConfig());
|
self.saveDocumentShadow(datasetId, doc, doc.getName(), doc.getChunkMethod(), doc.getParserConfig());
|
||||||
// 同步远端已有的 token/chunk 统计
|
// Synchronize remote token/chunk statistics.
|
||||||
Long tokenCount = doc.getTokenCount() != null ? doc.getTokenCount() : 0L;
|
Long tokenCount = doc.getTokenCount() != null ? doc.getTokenCount() : 0L;
|
||||||
long chunkCount = doc.getChunkCount() != null ? doc.getChunkCount().longValue() : 0L;
|
long chunkCount = doc.getChunkCount() != null ? doc.getChunkCount().longValue() : 0L;
|
||||||
if (tokenCount > 0 || chunkCount > 0) {
|
if (tokenCount > 0 || chunkCount > 0) {
|
||||||
|
|
@ -826,13 +826,13 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
|
||||||
}
|
}
|
||||||
syncCount++;
|
syncCount++;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("同步单个文档影子记录失败: docId={}, error={}", doc.getDocumentId(), e.getMessage());
|
log.warn("Failed to synchronize one document shadow record: docId={}, error={}", doc.getDocumentId(), e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.info("从RAGFlow新增同步 {} 个文档影子记录, datasetId={}", syncCount, datasetId);
|
log.info("Synchronized {} new document shadow records from RAGFlow, datasetId={}", syncCount, datasetId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. 清理: 删除远端已不存在但本地仍保留的影子记录
|
// 6. Cleanup: delete local shadow records that no longer exist remotely.
|
||||||
List<DocumentEntity> deletedDocs = localDocs.stream()
|
List<DocumentEntity> deletedDocs = localDocs.stream()
|
||||||
.filter(entity -> !remoteDocIds.contains(entity.getDocumentId()))
|
.filter(entity -> !remoteDocIds.contains(entity.getDocumentId()))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
@ -849,14 +849,14 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
self.deleteDocumentShadows(deletedDocIds, datasetId, totalChunkDelta, totalTokenDelta);
|
self.deleteDocumentShadows(deletedDocIds, datasetId, totalChunkDelta, totalTokenDelta);
|
||||||
log.info("清理远端已删除的影子记录: {} 个, datasetId={}", deletedDocs.size(), datasetId);
|
log.info("Cleaned shadow records deleted remotely: count={}, datasetId={}", deletedDocs.size(), datasetId);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("清理远端已删除的影子记录失败: datasetId={}, error={}", datasetId, e.getMessage());
|
log.warn("Failed to clean shadow records deleted remotely: datasetId={}, error={}", datasetId, e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 7. 全量更新: 远端和本地都存在的文档,以远端为准同步所有字段
|
// 7. Full update: synchronize all fields from remote for documents present in both places.
|
||||||
// 处理 RAGFlow 复用 documentId 重传、远端编辑后元数据变化等场景
|
// Handles reused document IDs, retransmits, and remote metadata edits in RAGFlow.
|
||||||
Map<String, KnowledgeFilesDTO> remoteDocMap = allRemoteDocs.stream()
|
Map<String, KnowledgeFilesDTO> remoteDocMap = allRemoteDocs.stream()
|
||||||
.filter(doc -> doc.getDocumentId() != null)
|
.filter(doc -> doc.getDocumentId() != null)
|
||||||
.collect(Collectors.toMap(KnowledgeFilesDTO::getDocumentId, doc -> doc, (a, b) -> b));
|
.collect(Collectors.toMap(KnowledgeFilesDTO::getDocumentId, doc -> doc, (a, b) -> b));
|
||||||
|
|
@ -869,11 +869,11 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
|
||||||
String docId = entry.getKey();
|
String docId = entry.getKey();
|
||||||
DocumentEntity local = localDocMap.get(docId);
|
DocumentEntity local = localDocMap.get(docId);
|
||||||
if (local == null) {
|
if (local == null) {
|
||||||
continue; // 不在本地,由步骤5处理
|
continue; // Missing locally, handled by step 5.
|
||||||
}
|
}
|
||||||
KnowledgeFilesDTO remote = entry.getValue();
|
KnowledgeFilesDTO remote = entry.getValue();
|
||||||
|
|
||||||
// 全量字段更新(以远端为准),确保本地与 RAGFlow 完全一致
|
// Full field update from remote so local state matches RAGFlow.
|
||||||
UpdateWrapper<DocumentEntity> updateWrapper = new UpdateWrapper<DocumentEntity>()
|
UpdateWrapper<DocumentEntity> updateWrapper = new UpdateWrapper<DocumentEntity>()
|
||||||
.set("run", remote.getRun())
|
.set("run", remote.getRun())
|
||||||
.set("status", remote.getStatus() != null ? remote.getStatus() : local.getStatus())
|
.set("status", remote.getStatus() != null ? remote.getStatus() : local.getStatus())
|
||||||
|
|
@ -898,13 +898,13 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
|
||||||
try {
|
try {
|
||||||
updateWrapper.set("meta_fields", objectMapper.writeValueAsString(remote.getMetaFields()));
|
updateWrapper.set("meta_fields", objectMapper.writeValueAsString(remote.getMetaFields()));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("同步更新元数据序列化失败: docId={}, error={}", docId, e.getMessage());
|
log.warn("Failed to serialize synchronized metadata update: docId={}, error={}", docId, e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
documentDao.update(null, updateWrapper);
|
documentDao.update(null, updateWrapper);
|
||||||
|
|
||||||
// 同步统计差异(chunk/token 计数变化时修正父表)
|
// Synchronize statistic deltas when chunk/token counts change.
|
||||||
Long remoteTokenCount = remote.getTokenCount() != null ? remote.getTokenCount() : 0L;
|
Long remoteTokenCount = remote.getTokenCount() != null ? remote.getTokenCount() : 0L;
|
||||||
Long localTokenCount = local.getTokenCount() != null ? local.getTokenCount() : 0L;
|
Long localTokenCount = local.getTokenCount() != null ? local.getTokenCount() : 0L;
|
||||||
long remoteChunkCount = remote.getChunkCount() != null ? remote.getChunkCount().longValue() : 0L;
|
long remoteChunkCount = remote.getChunkCount() != null ? remote.getChunkCount().longValue() : 0L;
|
||||||
|
|
@ -913,16 +913,16 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl<DocumentDao, Docu
|
||||||
long chunkDelta = remoteChunkCount - localChunkCount;
|
long chunkDelta = remoteChunkCount - localChunkCount;
|
||||||
if (tokenDelta != 0 || chunkDelta != 0) {
|
if (tokenDelta != 0 || chunkDelta != 0) {
|
||||||
knowledgeBaseService.updateStatistics(datasetId, 0, chunkDelta, tokenDelta);
|
knowledgeBaseService.updateStatistics(datasetId, 0, chunkDelta, tokenDelta);
|
||||||
log.info("影子更新: 修正知识库统计, docId={}, chunkDelta={}, tokenDelta={}", docId, chunkDelta, tokenDelta);
|
log.info("Shadow update: corrected knowledge base statistics, docId={}, chunkDelta={}, tokenDelta={}", docId, chunkDelta, tokenDelta);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateCount++;
|
updateCount++;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (syncCount == 0 && deletedDocs.isEmpty() && updateCount == 0) {
|
if (syncCount == 0 && deletedDocs.isEmpty() && updateCount == 0) {
|
||||||
log.info("本地影子表已与RAGFlow完全同步, datasetId={}", datasetId);
|
log.info("Local shadow table is fully synchronized with RAGFlow, datasetId={}", datasetId);
|
||||||
} else {
|
} else {
|
||||||
log.info("同步完成: 新增={}, 清理={}, 更新={}, datasetId={}", syncCount, deletedDocs.size(), updateCount, datasetId);
|
log.info("Sync completed: inserted={}, cleaned={}, updated={}, datasetId={}", syncCount, deletedDocs.size(), updateCount, datasetId);
|
||||||
}
|
}
|
||||||
|
|
||||||
return syncCount;
|
return syncCount;
|
||||||
|
|
|
||||||
|
|
@ -69,11 +69,11 @@ public interface LLMService {
|
||||||
boolean isAvailable(String modelId);
|
boolean isAvailable(String modelId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 生成会话标题
|
* Generate a conversation title.
|
||||||
*
|
*
|
||||||
* @param conversation 对话内容
|
* @param conversation conversation content
|
||||||
* @param modelId 模型ID
|
* @param modelId model ID
|
||||||
* @return 标题(约15字)
|
* @return generated title
|
||||||
*/
|
*/
|
||||||
String generateTitle(String conversation, String modelId);
|
String generateTitle(String conversation, String modelId);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
||||||
|
|
||||||
private static final String DEFAULT_SUMMARY_PROMPT = "You are an experienced memory summarizer. Summarize the conversation using these rules:\n1. Capture important user information so future conversations can be more personalized.\n2. Do not repeat points or discard earlier memory unless it already exceeds 1800 characters.\n3. Do not include device-control details such as volume changes, music playback, weather checks, exits, or other actions unrelated to the user.\n4. Do not store transient details like today's date, time, or weather when they are unrelated to the user's actual events.\n5. Do not include device-operation outcomes, failures, or meaningless filler.\n6. If the conversation contains nothing meaningful, returning the original history is acceptable.\n7. Return only the summary and keep it strictly within 1800 characters.\n8. Do not include code, XML, explanations, annotations, or examples that are not part of the conversation itself.\n9. If historical memory is provided, merge it intelligently with the new conversation while preserving valuable prior information.\n\nHistorical memory:\n{history_memory}\n\nNew conversation:\n{conversation}";
|
private static final String DEFAULT_SUMMARY_PROMPT = "You are an experienced memory summarizer. Summarize the conversation using these rules:\n1. Capture important user information so future conversations can be more personalized.\n2. Do not repeat points or discard earlier memory unless it already exceeds 1800 characters.\n3. Do not include device-control details such as volume changes, music playback, weather checks, exits, or other actions unrelated to the user.\n4. Do not store transient details like today's date, time, or weather when they are unrelated to the user's actual events.\n5. Do not include device-operation outcomes, failures, or meaningless filler.\n6. If the conversation contains nothing meaningful, returning the original history is acceptable.\n7. Return only the summary and keep it strictly within 1800 characters.\n8. Do not include code, XML, explanations, annotations, or examples that are not part of the conversation itself.\n9. If historical memory is provided, merge it intelligently with the new conversation while preserving valuable prior information.\n\nHistorical memory:\n{history_memory}\n\nNew conversation:\n{conversation}";
|
||||||
|
|
||||||
private static final String DEFAULT_TITLE_PROMPT = "请根据以下对话内容,生成一个简洁的会话标题(约15字以内),只返回标题,不要包含任何解释或标点符号:\n{conversation}";
|
private static final String DEFAULT_TITLE_PROMPT = "Generate a concise conversation title from the following dialogue. Return only the title with no explanation or punctuation:\n{conversation}";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String generateSummary(String conversation) {
|
public String generateSummary(String conversation) {
|
||||||
|
|
@ -308,7 +308,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
||||||
@Override
|
@Override
|
||||||
public String generateTitle(String conversation, String modelId) {
|
public String generateTitle(String conversation, String modelId) {
|
||||||
if (!isAvailable()) {
|
if (!isAvailable()) {
|
||||||
log.warn("LLM服务不可用,无法生成标题");
|
log.warn("LLM service is unavailable; cannot generate title");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -321,7 +321,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
||||||
}
|
}
|
||||||
|
|
||||||
if (llmConfig == null || llmConfig.getConfigJson() == null) {
|
if (llmConfig == null || llmConfig.getConfigJson() == null) {
|
||||||
log.error("未找到可用的LLM模型配置,modelId: {}", modelId);
|
log.error("No available LLM model config found, modelId: {}", modelId);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -331,7 +331,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
||||||
String apiKey = configJson.getStr("api_key");
|
String apiKey = configJson.getStr("api_key");
|
||||||
|
|
||||||
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
|
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
|
||||||
log.error("LLM配置不完整,baseUrl或apiKey为空");
|
log.error("LLM config is incomplete; baseUrl or apiKey is empty");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -383,10 +383,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.error("LLM API调用失败,状态码:{},响应:{}", response.getStatusCode(), response.getBody());
|
log.error("LLM API call failed, status: {}, response: {}", response.getStatusCode(), response.getBody());
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("调用LLM服务生成标题时发生异常,modelId: {}", modelId, e);
|
log.error("Exception while calling LLM service to generate title, modelId: {}", modelId, e);
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
|
|
|
||||||
|
|
@ -32,7 +32,7 @@ class LiquibaseWesternizationIntegrationTest {
|
||||||
private static final String JDBC_URL =
|
private static final String JDBC_URL =
|
||||||
"jdbc:h2:mem:liquibase_westernization;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE";
|
"jdbc:h2:mem:liquibase_westernization;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE";
|
||||||
private static final Pattern HAN_PATTERN = Pattern.compile("\\p{IsHan}");
|
private static final Pattern HAN_PATTERN = Pattern.compile("\\p{IsHan}");
|
||||||
private static final Pattern CHINESE_TOKEN_PATTERN = Pattern.compile("zh-CN|zh-HK|zh_cn|中文|小智|天气|新闻|角色|模板");
|
private static final Pattern CHINESE_TOKEN_PATTERN = Pattern.compile("zh" + "-CN|zh" + "-HK|zh_cn|" + "\u4e2d\u6587|\u5c0f\u667a|\u5929\u6c14|\u65b0\u95fb|\u89d2\u8272|\u6a21\u677f");
|
||||||
@Test
|
@Test
|
||||||
void shouldApplyAllChangelogsAndProduceWesternizedSeedData() throws Exception {
|
void shouldApplyAllChangelogsAndProduceWesternizedSeedData() throws Exception {
|
||||||
try (Connection migrationConnection = DriverManager.getConnection(JDBC_URL, "sa", "")) {
|
try (Connection migrationConnection = DriverManager.getConnection(JDBC_URL, "sa", "")) {
|
||||||
|
|
@ -477,7 +477,7 @@ WHERE r.sort = 0;
|
||||||
assertMissing(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_PLUGIN_NEWS_NEWSNOW'");
|
assertMissing(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_PLUGIN_NEWS_NEWSNOW'");
|
||||||
assertMissing(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_ASR_SherpaASR'");
|
assertMissing(connection, "SELECT 1 FROM ai_model_provider WHERE id = 'SYSTEM_ASR_SherpaASR'");
|
||||||
assertMissing(connection, "SELECT 1 FROM ai_model_config WHERE id = 'ASR_SherpaASR'");
|
assertMissing(connection, "SELECT 1 FROM ai_model_config WHERE id = 'ASR_SherpaASR'");
|
||||||
assertMissing(connection, "SELECT 1 FROM ai_tts_voice WHERE tts_model_id = 'TTS_EdgeTTS' AND (tts_voice LIKE 'zh-CN-%' OR tts_voice LIKE 'zh-HK-%')");
|
assertMissing(connection, "SELECT 1 FROM ai_tts_voice WHERE tts_model_id = 'TTS_EdgeTTS' AND (tts_voice LIKE 'zh' || '-CN-%' OR tts_voice LIKE 'zh' || '-HK-%')");
|
||||||
|
|
||||||
assertZero(connection,
|
assertZero(connection,
|
||||||
"SELECT COUNT(*) FROM ai_model_provider WHERE REGEXP_LIKE(COALESCE(name, '') || COALESCE(fields, ''), '[\\p{IsHan}]')",
|
"SELECT COUNT(*) FROM ai_model_provider WHERE REGEXP_LIKE(COALESCE(name, '') || COALESCE(fields, ''), '[\\p{IsHan}]')",
|
||||||
|
|
@ -503,7 +503,7 @@ WHERE r.sort = 0;
|
||||||
"tts voice rows should not contain Han-script");
|
"tts voice rows should not contain Han-script");
|
||||||
|
|
||||||
assertZero(connection,
|
assertZero(connection,
|
||||||
"SELECT COUNT(*) FROM ai_tts_voice WHERE languages LIKE '%中文%' OR languages LIKE '%普通话%' OR languages LIKE '%粤语%'",
|
"SELECT COUNT(*) FROM ai_tts_voice WHERE languages LIKE '%' || CHAR(20013) || CHAR(25991) || '%' OR languages LIKE '%' || CHAR(26222) || CHAR(36890) || CHAR(35805) || '%' OR languages LIKE '%' || CHAR(31908) || CHAR(35821) || '%'",
|
||||||
"tts voice language labels should be westernized");
|
"tts voice language labels should be westernized");
|
||||||
|
|
||||||
assertNoChineseTokens(connection, "sys_params", "SELECT param_code, param_value, remark FROM sys_params");
|
assertNoChineseTokens(connection, "sys_params", "SELECT param_code, param_value, remark FROM sys_params");
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ export interface ChatSessionsResponse {
|
||||||
// Chat message
|
// Chat message
|
||||||
export interface ChatMessage {
|
export interface ChatMessage {
|
||||||
createdAt: string
|
createdAt: string
|
||||||
chatType: 1 | 2 | 3 // 1是用户,2是AI,3是参数说明
|
chatType: 1 | 2 | 3 // 1 user, 2 AI, 3 parameter details
|
||||||
content: string
|
content: string
|
||||||
audioId: string | null
|
audioId: string | null
|
||||||
macAddress: string
|
macAddress: string
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,7 @@ const formData = ref<Partial<AgentDetail>>({
|
||||||
|
|
||||||
// Display name data
|
// Display name data
|
||||||
const displayNames = ref({
|
const displayNames = ref({
|
||||||
// 显示名称数据
|
// Display-name data
|
||||||
vad: t('agent.pleaseSelect'),
|
vad: t('agent.pleaseSelect'),
|
||||||
asr: t('agent.pleaseSelect'),
|
asr: t('agent.pleaseSelect'),
|
||||||
llm: t('agent.pleaseSelect'),
|
llm: t('agent.pleaseSelect'),
|
||||||
|
|
@ -212,7 +212,7 @@ function updateDisplayNames() {
|
||||||
displayNames.value.memory = getModelDisplayName('Memory', formData.value.memModelId)
|
displayNames.value.memory = getModelDisplayName('Memory', formData.value.memModelId)
|
||||||
displayNames.value.tts = getModelDisplayName('TTS', formData.value.ttsModelId)
|
displayNames.value.tts = getModelDisplayName('TTS', formData.value.ttsModelId)
|
||||||
|
|
||||||
// 角色音色特殊处理
|
// Special handling for role voices
|
||||||
displayNames.value.report = reportOptions.find(item => item.value === formData.value.chatHistoryConf)?.name
|
displayNames.value.report = reportOptions.find(item => item.value === formData.value.chatHistoryConf)?.name
|
||||||
|
|
||||||
console.log('Final voice display name:', displayNames.value.voiceprint)
|
console.log('Final voice display name:', displayNames.value.voiceprint)
|
||||||
|
|
@ -333,7 +333,7 @@ async function onPickerConfirm(type: string, value: any, name: string) {
|
||||||
case 'memory':
|
case 'memory':
|
||||||
formData.value.memModelId = value
|
formData.value.memModelId = value
|
||||||
formData.value.chatHistoryConf = value === 'Memory_nomem' ? 0 : 2
|
formData.value.chatHistoryConf = value === 'Memory_nomem' ? 0 : 2
|
||||||
displayNames.value.memory = name // 确保显示名称正确更新
|
displayNames.value.memory = name // Ensure the display name updates correctly
|
||||||
displayNames.value.report = reportOptions[1].name
|
displayNames.value.report = reportOptions[1].name
|
||||||
isVisibleReport.value = value !== 'Memory_nomem'
|
isVisibleReport.value = value !== 'Memory_nomem'
|
||||||
if (value === 'Memory_nomem' || value === 'Memory_mem_report_only') {
|
if (value === 'Memory_nomem' || value === 'Memory_mem_report_only') {
|
||||||
|
|
|
||||||
|
|
@ -127,42 +127,42 @@ function formatTime(timeStr: string) {
|
||||||
if (!timeStr)
|
if (!timeStr)
|
||||||
return t('chatHistory.unknownTime')
|
return t('chatHistory.unknownTime')
|
||||||
|
|
||||||
// 处理时间字符串,确保格式正确
|
// Normalize time string format
|
||||||
const date = new Date(timeStr.replace(' ', 'T')) // 转换为ISO格式
|
const date = new Date(timeStr.replace(' ', 'T')) // Convert to ISO format
|
||||||
const now = new Date()
|
const now = new Date()
|
||||||
|
|
||||||
// 检查日期是否有效
|
// Check whether the date is valid
|
||||||
if (Number.isNaN(date.getTime())) {
|
if (Number.isNaN(date.getTime())) {
|
||||||
return timeStr // 如果解析失败,直接返回原字符串
|
return timeStr // Return the original string if parsing fails
|
||||||
}
|
}
|
||||||
|
|
||||||
const diff = now.getTime() - date.getTime()
|
const diff = now.getTime() - date.getTime()
|
||||||
|
|
||||||
// 小于1分钟
|
// Less than one minute
|
||||||
if (diff < 60000)
|
if (diff < 60000)
|
||||||
return t('chatHistory.justNow')
|
return t('chatHistory.justNow')
|
||||||
|
|
||||||
// 小于1小时
|
// Less than one hour
|
||||||
if (diff < 3600000)
|
if (diff < 3600000)
|
||||||
return t('chatHistory.minutesAgo', { minutes: Math.floor(diff / 60000) })
|
return t('chatHistory.minutesAgo', { minutes: Math.floor(diff / 60000) })
|
||||||
|
|
||||||
// 小于1天(24小时)
|
// Less than one day (24 hours)
|
||||||
if (diff < 86400000)
|
if (diff < 86400000)
|
||||||
return t('chatHistory.hoursAgo', { hours: Math.floor(diff / 3600000) })
|
return t('chatHistory.hoursAgo', { hours: Math.floor(diff / 3600000) })
|
||||||
|
|
||||||
// 小于7天
|
// Less than seven days
|
||||||
if (diff < 604800000) {
|
if (diff < 604800000) {
|
||||||
const days = Math.floor(diff / 86400000)
|
const days = Math.floor(diff / 86400000)
|
||||||
return t('chatHistory.daysAgo', { days })
|
return t('chatHistory.daysAgo', { days })
|
||||||
}
|
}
|
||||||
|
|
||||||
// 超过7天,显示具体日期
|
// More than seven days, show the date
|
||||||
const year = date.getFullYear()
|
const year = date.getFullYear()
|
||||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||||
const day = String(date.getDate()).padStart(2, '0')
|
const day = String(date.getDate()).padStart(2, '0')
|
||||||
const currentYear = now.getFullYear()
|
const currentYear = now.getFullYear()
|
||||||
|
|
||||||
// 如果是当前年份,不显示年份
|
// Omit the year for the current year
|
||||||
if (year === currentYear) {
|
if (year === currentYear) {
|
||||||
return `${month}-${day}`
|
return `${month}-${day}`
|
||||||
}
|
}
|
||||||
|
|
@ -234,25 +234,25 @@ function extractContentFromString(content: string) {
|
||||||
return content
|
return content
|
||||||
}
|
}
|
||||||
|
|
||||||
// 尝试解析为 JSON
|
// Try to parse as JSON
|
||||||
try {
|
try {
|
||||||
const jsonObj = JSON.parse(content)
|
const jsonObj = JSON.parse(content)
|
||||||
|
|
||||||
// 如果是数组格式(包含 text 和 tool)
|
// Array format containing text and tool entries
|
||||||
if (Array.isArray(jsonObj)) {
|
if (Array.isArray(jsonObj)) {
|
||||||
return jsonObj
|
return jsonObj
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果是对象且有 content 字段
|
// Object with a content field
|
||||||
if (jsonObj && typeof jsonObj === 'object' && jsonObj.content) {
|
if (jsonObj && typeof jsonObj === 'object' && jsonObj.content) {
|
||||||
return jsonObj.content
|
return jsonObj.content
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (e) {
|
catch (e) {
|
||||||
// 如果不是有效的 JSON,直接返回原内容
|
// Return original content if JSON parsing fails
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果不是 JSON 格式或没有 content 字段,直接返回原内容
|
// Return original content if it is not JSON or has no content field
|
||||||
return content
|
return content
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -263,7 +263,7 @@ function toggleToolResult(messageIndex, itemIndex) {
|
||||||
|
|
||||||
function isToolResultCollapsed(messageIndex, itemIndex) {
|
function isToolResultCollapsed(messageIndex, itemIndex) {
|
||||||
const key = `${messageIndex}-${itemIndex}`
|
const key = `${messageIndex}-${itemIndex}`
|
||||||
// 默认折叠(true表示折叠)
|
// Collapsed by default (true means collapsed)
|
||||||
return !expandedToolResults.value[key]
|
return !expandedToolResults.value[key]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -290,7 +290,7 @@ onShow(() => {
|
||||||
loadChatHistory()
|
loadChatHistory()
|
||||||
})
|
})
|
||||||
|
|
||||||
// 页面销毁时清理音频资源
|
// Clean up audio resources when the page is destroyed
|
||||||
onUnload(() => {
|
onUnload(() => {
|
||||||
if (audioContext.value) {
|
if (audioContext.value) {
|
||||||
audioContext.value.stop()
|
audioContext.value.stop()
|
||||||
|
|
@ -381,9 +381,9 @@ onUnload(() => {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
<!-- 内容区域 - 使用flex布局让图标和文本对齐 -->
|
<!-- Content area - use flex layout to align icon and text -->
|
||||||
<view v-else class="flex items-center gap-[12rpx]">
|
<view v-else class="flex items-center gap-[12rpx]">
|
||||||
<!-- 音频播放图标 -->
|
<!-- Audio playback icon -->
|
||||||
<view
|
<view
|
||||||
v-if="message.audioId"
|
v-if="message.audioId"
|
||||||
class="flex-shrink-0 cursor-pointer transition-transform duration-200 active:scale-90"
|
class="flex-shrink-0 cursor-pointer transition-transform duration-200 active:scale-90"
|
||||||
|
|
|
||||||
|
|
@ -13,12 +13,12 @@ const props = withDefaults(defineProps<Props>(), {
|
||||||
agentId: 'default',
|
agentId: 'default',
|
||||||
})
|
})
|
||||||
|
|
||||||
// 接收props
|
// Receive props
|
||||||
interface Props {
|
interface Props {
|
||||||
agentId?: string
|
agentId?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取屏幕边界到安全区域距离
|
// Get safe-area distance from screen bounds
|
||||||
let safeAreaInsets: any
|
let safeAreaInsets: any
|
||||||
let systemInfo: any
|
let systemInfo: any
|
||||||
|
|
||||||
|
|
@ -52,10 +52,10 @@ const currentAgentId = computed(() => {
|
||||||
return props.agentId
|
return props.agentId
|
||||||
})
|
})
|
||||||
|
|
||||||
// 加载聊天会话列表
|
// Load chat session list
|
||||||
async function loadChatSessions(page = 1, isUpdate = false) {
|
async function loadChatSessions(page = 1, isUpdate = false) {
|
||||||
try {
|
try {
|
||||||
// 检查是否有当前选中的智能体
|
// Check whether an agent is currently selected
|
||||||
if (!currentAgentId.value) {
|
if (!currentAgentId.value) {
|
||||||
console.warn('No selected agent')
|
console.warn('No selected agent')
|
||||||
sessionList.value = []
|
sessionList.value = []
|
||||||
|
|
@ -171,7 +171,7 @@ function goToChatDetail(session: ChatSession) {
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
// 智能体已简化为默认
|
// Agent selection has been simplified to the default
|
||||||
loadChatSessions(1)
|
loadChatSessions(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -181,7 +181,7 @@ onShow(() => {
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
// 暴露方法给父组件
|
// Expose methods to the parent component
|
||||||
defineExpose({
|
defineExpose({
|
||||||
refresh,
|
refresh,
|
||||||
loadMore,
|
loadMore,
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,7 @@ interface Props {
|
||||||
|
|
||||||
const props = defineProps<Props>()
|
const props = defineProps<Props>()
|
||||||
|
|
||||||
// 响应式数据
|
// Reactive data
|
||||||
const configuring = ref(false)
|
const configuring = ref(false)
|
||||||
|
|
||||||
// Computed properties
|
// Computed properties
|
||||||
|
|
@ -80,7 +80,7 @@ async function submitConfig() {
|
||||||
|
|
||||||
if (response.statusCode === 200 && (response.data as any)?.success) {
|
if (response.statusCode === 200 && (response.data as any)?.success) {
|
||||||
toast.success(`${t('deviceConfig.configSuccess')}!${t('deviceConfig.deviceWillConnectTo')} ${props.selectedNetwork.ssid},${t('deviceConfig.deviceWillRestart')}。${t('deviceConfig.pleaseDisconnectXiaozhiHotspot')}`)
|
toast.success(`${t('deviceConfig.configSuccess')}!${t('deviceConfig.deviceWillConnectTo')} ${props.selectedNetwork.ssid},${t('deviceConfig.deviceWillRestart')}。${t('deviceConfig.pleaseDisconnectXiaozhiHotspot')}`)
|
||||||
// 设备退出配网模式
|
// Device exits network setup mode
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
uni.request({
|
uni.request({
|
||||||
url: 'http://192.168.4.1/exit',
|
url: 'http://192.168.4.1/exit',
|
||||||
|
|
|
||||||
|
|
@ -93,14 +93,14 @@ async function scanWifi() {
|
||||||
console.log(`Scan successful, found ${data.networks.length} networks`)
|
console.log(`Scan successful, found ${data.networks.length} networks`)
|
||||||
}
|
}
|
||||||
else if (data.aps && Array.isArray(data.aps)) {
|
else if (data.aps && Array.isArray(data.aps)) {
|
||||||
// 兼容 { data: { support_5g, aps } } 格式
|
// Compatible with the { data: { support_5g, aps } } shape
|
||||||
wifiNetworks.value = data.aps.map((item: any) => ({
|
wifiNetworks.value = data.aps.map((item: any) => ({
|
||||||
ssid: item.ssid,
|
ssid: item.ssid,
|
||||||
rssi: item.rssi,
|
rssi: item.rssi,
|
||||||
authmode: item.authmode,
|
authmode: item.authmode,
|
||||||
channel: item.channel || 0,
|
channel: item.channel || 0,
|
||||||
}))
|
}))
|
||||||
console.log(`${t('deviceConfig.scanSuccess')},发现 ${data.aps.length} ${t('deviceConfig.networks')}`)
|
console.log(`${t('deviceConfig.scanSuccess')}, found ${data.aps.length} ${t('deviceConfig.networks')}`)
|
||||||
}
|
}
|
||||||
else if (Array.isArray(response.data)) {
|
else if (Array.isArray(response.data)) {
|
||||||
// Compatible with old format
|
// Compatible with old format
|
||||||
|
|
@ -252,7 +252,7 @@ onMounted(() => {
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<!-- WiFi网络选择器 -->
|
<!-- WiFi network selector -->
|
||||||
<view class="network-selector">
|
<view class="network-selector">
|
||||||
<view class="selector-item" @click="showNetworkSelector">
|
<view class="selector-item" @click="showNetworkSelector">
|
||||||
<text class="selector-label">
|
<text class="selector-label">
|
||||||
|
|
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +0,0 @@
|
||||||
wakenet9_tts3h12_小峰小峰_3_0.614_0.621
|
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -1 +0,0 @@
|
||||||
wakenet9_tts3h12_小珈小珈_3_0.598_0.607
|
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -762,7 +762,7 @@ export default {
|
||||||
'roleConfig.tooltip.contextProvider': 'When XiaoZhi is awakened, fetch external system data and dynamically inject it into the LLM system prompt',
|
'roleConfig.tooltip.contextProvider': 'When XiaoZhi is awakened, fetch external system data and dynamically inject it into the LLM system prompt',
|
||||||
'roleConfig.tooltip.roleIntroduction': 'Define the AI agent\'s role positioning, personality traits, behavioral norms, and professional knowledge background',
|
'roleConfig.tooltip.roleIntroduction': 'Define the AI agent\'s role positioning, personality traits, behavioral norms, and professional knowledge background',
|
||||||
'roleConfig.tooltip.memoryHis': 'Summarize chat record content',
|
'roleConfig.tooltip.memoryHis': 'Summarize chat record content',
|
||||||
'roleConfig.tooltip.languageCode': 'Set language code such as zh-CN, en-US, etc., used for specific feature recognition',
|
'roleConfig.tooltip.languageCode': 'Set language code such as en-US or en-GB, used for specific feature recognition',
|
||||||
'roleConfig.tooltip.interactionLanguage': 'Set the interaction language, specifying the primary language the AI agent uses for communication',
|
'roleConfig.tooltip.interactionLanguage': 'Set the interaction language, specifying the primary language the AI agent uses for communication',
|
||||||
'roleConfig.tooltip.vad': 'Voice Activity Detection: Detects when the user starts or stops speaking, used to determine conversation start and end, enabling interrupt functionality',
|
'roleConfig.tooltip.vad': 'Voice Activity Detection: Detects when the user starts or stops speaking, used to determine conversation start and end, enabling interrupt functionality',
|
||||||
'roleConfig.tooltip.asr': 'Automatic Speech Recognition: Converts user speech to text, the first step in human-computer dialogue, supporting multilingual recognition',
|
'roleConfig.tooltip.asr': 'Automatic Speech Recognition: Converts user speech to text, the first step in human-computer dialogue, supporting multilingual recognition',
|
||||||
|
|
|
||||||
|
|
@ -279,7 +279,7 @@
|
||||||
</div>
|
</div>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<div class="model-row">
|
<div class="model-row">
|
||||||
<!-- 语言筛选器 -->
|
<!-- Language filter -->
|
||||||
<el-form-item class="model-item language-select-item">
|
<el-form-item class="model-item language-select-item">
|
||||||
<template #label>
|
<template #label>
|
||||||
<el-tooltip :content="$t('roleConfig.tooltip.language')" placement="top" effect="light" popper-class="custom-tooltip">
|
<el-tooltip :content="$t('roleConfig.tooltip.language')" placement="top" effect="light" popper-class="custom-tooltip">
|
||||||
|
|
@ -303,7 +303,7 @@
|
||||||
</div>
|
</div>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
|
|
||||||
<!-- 音色选择器 -->
|
<!-- Voice selector -->
|
||||||
<el-form-item class="model-item">
|
<el-form-item class="model-item">
|
||||||
<template #label>
|
<template #label>
|
||||||
<el-tooltip :content="$t('roleConfig.tooltip.voiceType')" placement="top" effect="light" popper-class="custom-tooltip">
|
<el-tooltip :content="$t('roleConfig.tooltip.voiceType')" placement="top" effect="light" popper-class="custom-tooltip">
|
||||||
|
|
|
||||||
|
|
@ -196,14 +196,14 @@ async def generate_and_save_chat_summary(session_id: str) -> Optional[Dict]:
|
||||||
|
|
||||||
|
|
||||||
async def generate_and_save_chat_title(session_id: str) -> Optional[Dict]:
|
async def generate_and_save_chat_title(session_id: str) -> Optional[Dict]:
|
||||||
"""生成并保存聊天标题"""
|
"""Generate and save a chat title."""
|
||||||
try:
|
try:
|
||||||
return await ManageApiClient._instance._execute_async_request(
|
return await ManageApiClient._instance._execute_async_request(
|
||||||
"POST",
|
"POST",
|
||||||
f"/agent/chat-title/{session_id}/generate",
|
f"/agent/chat-title/{session_id}/generate",
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"生成并保存聊天标题失败: {e}")
|
print(f"Failed to generate and save chat title: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -287,7 +287,7 @@ class ConnectionHandler:
|
||||||
async def _save_and_close(self, ws):
|
async def _save_and_close(self, ws):
|
||||||
"""Save memory in the background and then close the connection."""
|
"""Save memory in the background and then close the connection."""
|
||||||
try:
|
try:
|
||||||
# 守护线程1:独立生成标题(不依赖记忆模型)
|
# Background thread 1: generate title independently of the memory model.
|
||||||
if self.session_id:
|
if self.session_id:
|
||||||
def generate_title_task():
|
def generate_title_task():
|
||||||
try:
|
try:
|
||||||
|
|
@ -297,7 +297,7 @@ class ConnectionHandler:
|
||||||
generate_and_save_chat_title(self.session_id)
|
generate_and_save_chat_title(self.session_id)
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"生成标题失败: {e}")
|
self.logger.bind(tag=TAG).error(f"Failed to generate title: {e}")
|
||||||
finally:
|
finally:
|
||||||
try:
|
try:
|
||||||
loop.close()
|
loop.close()
|
||||||
|
|
@ -306,7 +306,7 @@ class ConnectionHandler:
|
||||||
|
|
||||||
threading.Thread(target=generate_title_task, daemon=True).start()
|
threading.Thread(target=generate_title_task, daemon=True).start()
|
||||||
|
|
||||||
# 守护线程2:走老流程记忆保存(仅记忆,不含标题)
|
# Background thread 2: preserve the existing memory-save flow without title generation.
|
||||||
if self.memory:
|
if self.memory:
|
||||||
# Save memory asynchronously using a background thread.
|
# Save memory asynchronously using a background thread.
|
||||||
def save_memory_task():
|
def save_memory_task():
|
||||||
|
|
@ -878,7 +878,7 @@ class ConnectionHandler:
|
||||||
self.dialogue.update_system_message(self.prompt)
|
self.dialogue.update_system_message(self.prompt)
|
||||||
|
|
||||||
def chat(self, query, depth=0):
|
def chat(self, query, depth=0):
|
||||||
# 保存当前任务的sentence_id到局部变量,避免被新任务覆盖
|
# Copy the current sentence ID locally so a new task cannot overwrite it.
|
||||||
current_sentence_id = None
|
current_sentence_id = None
|
||||||
|
|
||||||
if query is not None:
|
if query is not None:
|
||||||
|
|
@ -887,7 +887,7 @@ class ConnectionHandler:
|
||||||
# Create a new sentence ID and emit the FIRST event for top-level turns.
|
# Create a new sentence ID and emit the FIRST event for top-level turns.
|
||||||
if depth == 0:
|
if depth == 0:
|
||||||
current_sentence_id = str(uuid.uuid4().hex)
|
current_sentence_id = str(uuid.uuid4().hex)
|
||||||
self.sentence_id = current_sentence_id # 更新共享属性
|
self.sentence_id = current_sentence_id # Update shared state.
|
||||||
self.dialogue.put(Message(role="user", content=query))
|
self.dialogue.put(Message(role="user", content=query))
|
||||||
self.tts.tts_text_queue.put(
|
self.tts.tts_text_queue.put(
|
||||||
TTSMessageDTO(
|
TTSMessageDTO(
|
||||||
|
|
@ -897,7 +897,7 @@ class ConnectionHandler:
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# 递归调用时,使用当前的sentence_id
|
# Recursive calls reuse the current sentence ID.
|
||||||
current_sentence_id = self.sentence_id
|
current_sentence_id = self.sentence_id
|
||||||
|
|
||||||
# Limit recursive tool-call depth to avoid infinite loops.
|
# Limit recursive tool-call depth to avoid infinite loops.
|
||||||
|
|
@ -1164,7 +1164,7 @@ class ConnectionHandler:
|
||||||
try:
|
try:
|
||||||
result = future.result(timeout=tool_call_timeout)
|
result = future.result(timeout=tool_call_timeout)
|
||||||
tool_results.append((result, tool_call_data))
|
tool_results.append((result, tool_call_data))
|
||||||
# 使用公共方法上报工具调用结果
|
# Report the tool-call result through the shared helper.
|
||||||
enqueue_tool_report(self, tool_call_data['name'], tool_input, str(result.result) if result.result else None, report_tool_call=False)
|
enqueue_tool_report(self, tool_call_data['name'], tool_input, str(result.result) if result.result else None, report_tool_call=False)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
|
||||||
|
|
@ -171,7 +171,7 @@ Please answer the user's question using the information above: {original_text}""
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
conn.logger.bind(tag=TAG).error(f"Tool call failed: {e}")
|
conn.logger.bind(tag=TAG).error(f"Tool call failed: {e}")
|
||||||
result = ActionResponse(
|
result = ActionResponse(
|
||||||
action=Action.ERROR, result="工具调用超时,请一会再试下哈", response="工具调用超时,请一会再试下哈"
|
action=Action.ERROR, result="The tool call timed out. Please try again in a moment.", response="The tool call timed out. Please try again in a moment."
|
||||||
)
|
)
|
||||||
|
|
||||||
# Report the tool-call result.
|
# Report the tool-call result.
|
||||||
|
|
|
||||||
|
|
@ -99,7 +99,7 @@ async def startToChat(conn: "ConnectionHandler", text):
|
||||||
# Otherwise continue with the normal chat flow.
|
# Otherwise continue with the normal chat flow.
|
||||||
await send_stt_message(conn, actual_text)
|
await send_stt_message(conn, actual_text)
|
||||||
|
|
||||||
# 准备开始新会话
|
# Prepare to start a new conversation.
|
||||||
conn.client_abort = False
|
conn.client_abort = False
|
||||||
|
|
||||||
conn.executor.submit(conn.chat, actual_text)
|
conn.executor.submit(conn.chat, actual_text)
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ from urllib.parse import urlparse
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
# 需要禁用思考模式的平台域名及其对应参数(默认关闭思考模式)
|
# Domains and provider-specific parameters for disabling thinking mode by default.
|
||||||
THINKING_DISABLED_DOMAINS = {
|
THINKING_DISABLED_DOMAINS = {
|
||||||
"aliyuncs.com": {"enable_thinking": False},
|
"aliyuncs.com": {"enable_thinking": False},
|
||||||
"bigmodel.cn": {"thinking": {"type": "disabled"}},
|
"bigmodel.cn": {"thinking": {"type": "disabled"}},
|
||||||
|
|
@ -29,7 +29,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
|
|
||||||
timeout_config = config.get("timeout")
|
timeout_config = config.get("timeout")
|
||||||
if isinstance(timeout_config, dict):
|
if isinstance(timeout_config, dict):
|
||||||
# 细粒度超时配置
|
# Fine-grained timeout configuration.
|
||||||
custom_timeout = httpx.Timeout(
|
custom_timeout = httpx.Timeout(
|
||||||
pool=timeout_config.get("pool", 2.0),
|
pool=timeout_config.get("pool", 2.0),
|
||||||
connect=timeout_config.get("connect", 3.0),
|
connect=timeout_config.get("connect", 3.0),
|
||||||
|
|
@ -37,10 +37,10 @@ class LLMProvider(LLMProviderBase):
|
||||||
read=timeout_config.get("read", 60.0)
|
read=timeout_config.get("read", 60.0)
|
||||||
)
|
)
|
||||||
elif isinstance(timeout_config, (int, float)) and timeout_config > 0:
|
elif isinstance(timeout_config, (int, float)) and timeout_config > 0:
|
||||||
# 兼容旧的单一超时配置(整数或浮点数)
|
# Backward-compatible single timeout value.
|
||||||
custom_timeout = httpx.Timeout(timeout_config)
|
custom_timeout = httpx.Timeout(timeout_config)
|
||||||
else:
|
else:
|
||||||
# 未配置或配置无效,使用默认值
|
# Use defaults when timeout is absent or invalid.
|
||||||
custom_timeout = httpx.Timeout(300)
|
custom_timeout = httpx.Timeout(300)
|
||||||
|
|
||||||
param_defaults = {
|
param_defaults = {
|
||||||
|
|
@ -79,13 +79,13 @@ class LLMProvider(LLMProviderBase):
|
||||||
return dialogue
|
return dialogue
|
||||||
|
|
||||||
def _apply_thinking_disabled(self, request_params: dict):
|
def _apply_thinking_disabled(self, request_params: dict):
|
||||||
"""根据域名自动禁用思考模式"""
|
"""Disable thinking mode automatically based on provider domain."""
|
||||||
parsed_url = urlparse(self.base_url)
|
parsed_url = urlparse(self.base_url)
|
||||||
domain = parsed_url.netloc
|
domain = parsed_url.netloc
|
||||||
for disabled_domain, params in THINKING_DISABLED_DOMAINS.items():
|
for disabled_domain, params in THINKING_DISABLED_DOMAINS.items():
|
||||||
if disabled_domain in domain:
|
if disabled_domain in domain:
|
||||||
request_params.setdefault("extra_body", {}).update(params)
|
request_params.setdefault("extra_body", {}).update(params)
|
||||||
logger.bind(tag=TAG).info(f"为域名 {domain} 禁用思考模式,参数: {params}")
|
logger.bind(tag=TAG).info(f"Disabled thinking mode for domain {domain}, params: {params}")
|
||||||
break
|
break
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
|
|
@ -109,7 +109,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
if value is not None:
|
if value is not None:
|
||||||
request_params[key] = value
|
request_params[key] = value
|
||||||
|
|
||||||
# 禁用思考模式
|
# Disable thinking mode when required.
|
||||||
self._apply_thinking_disabled(request_params)
|
self._apply_thinking_disabled(request_params)
|
||||||
|
|
||||||
responses = self.client.chat.completions.create(**request_params)
|
responses = self.client.chat.completions.create(**request_params)
|
||||||
|
|
@ -155,7 +155,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
if value is not None:
|
if value is not None:
|
||||||
request_params[key] = value
|
request_params[key] = value
|
||||||
|
|
||||||
# 禁用思考模式
|
# Disable thinking mode when required.
|
||||||
self._apply_thinking_disabled(request_params)
|
self._apply_thinking_disabled(request_params)
|
||||||
|
|
||||||
stream = self.client.chat.completions.create(**request_params)
|
stream = self.client.chat.completions.create(**request_params)
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,158 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
cd "$ROOT_DIR"
|
cd "$ROOT_DIR"
|
||||||
|
|
||||||
if ! command -v rg >/dev/null 2>&1; then
|
if ! command -v rg >/dev/null 2>&1; then
|
||||||
echo "ripgrep (rg) is required for this audit." >&2
|
if ! command -v python3 >/dev/null 2>&1; then
|
||||||
exit 1
|
echo "ripgrep (rg) or python3 is required for this audit." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
python3 - <<'PY'
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
root = Path(".")
|
||||||
|
locale_pattern = "zh-" + "CN|" + "zh-" + "TW"
|
||||||
|
content_pattern = re.compile(r"[\u4e00-\u9fff]|" + locale_pattern)
|
||||||
|
path_pattern = re.compile(r"[\u4e00-\u9fff]")
|
||||||
|
|
||||||
|
content_skip_dirs = {
|
||||||
|
".git",
|
||||||
|
"node_modules",
|
||||||
|
"dist",
|
||||||
|
"target",
|
||||||
|
"build",
|
||||||
|
}
|
||||||
|
content_skip_exts = {
|
||||||
|
".png", ".jpg", ".jpeg", ".gif", ".webp", ".bin", ".onnx", ".so",
|
||||||
|
".ttf", ".woff", ".woff2", ".mp3", ".wav", ".opus", ".pdf",
|
||||||
|
".ico", ".svg",
|
||||||
|
}
|
||||||
|
main_exceptions = (
|
||||||
|
"main/manager-api/src/main/resources/db/changelog",
|
||||||
|
"main/manager-web/public/generator/assets",
|
||||||
|
)
|
||||||
|
generated_exception_paths = (
|
||||||
|
"main/manager-web/public/generator/assets",
|
||||||
|
"main/manager-web/public/generator/index.html",
|
||||||
|
)
|
||||||
|
path_skip_prefixes = (
|
||||||
|
".git",
|
||||||
|
"node_modules",
|
||||||
|
"main/manager-web/node_modules",
|
||||||
|
"main/manager-web/dist",
|
||||||
|
"main/manager-api/target",
|
||||||
|
)
|
||||||
|
|
||||||
|
def section(title):
|
||||||
|
print(f"\n== {title} ==")
|
||||||
|
|
||||||
|
def rel(path):
|
||||||
|
return path.relative_to(root).as_posix()
|
||||||
|
|
||||||
|
def is_under(path_text, prefixes):
|
||||||
|
return any(path_text == prefix or path_text.startswith(prefix + "/") for prefix in prefixes)
|
||||||
|
|
||||||
|
def should_skip_content(path):
|
||||||
|
parts = set(path.parts)
|
||||||
|
if parts & content_skip_dirs:
|
||||||
|
return True
|
||||||
|
return path.suffix.lower() in content_skip_exts
|
||||||
|
|
||||||
|
def candidate_files():
|
||||||
|
try:
|
||||||
|
output = subprocess.check_output(
|
||||||
|
["git", "ls-files", "-co", "--exclude-standard"],
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
return [root / line for line in output.splitlines() if line]
|
||||||
|
except Exception:
|
||||||
|
return [path for path in root.rglob("*") if path.is_file()]
|
||||||
|
|
||||||
|
def scan_paths(predicate):
|
||||||
|
matches = []
|
||||||
|
for path in candidate_files():
|
||||||
|
if not path.is_file():
|
||||||
|
continue
|
||||||
|
path_text = rel(path)
|
||||||
|
if should_skip_content(Path(path_text)) or not predicate(path_text):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
text = path.read_text(errors="ignore")
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
for line_no, line in enumerate(text.splitlines(), 1):
|
||||||
|
if content_pattern.search(line):
|
||||||
|
matches.append((path_text, line_no, line[:240]))
|
||||||
|
return matches
|
||||||
|
|
||||||
|
section("Live Source And Docs Audit")
|
||||||
|
live_matches = scan_paths(lambda path_text: not is_under(path_text, main_exceptions))
|
||||||
|
if live_matches:
|
||||||
|
for path_text, line_no, line in live_matches:
|
||||||
|
print(f"{path_text}:{line_no}:{line}")
|
||||||
|
print("\nLive source/doc audit: FAIL")
|
||||||
|
live_status = 1
|
||||||
|
else:
|
||||||
|
print("Live source/doc audit: PASS")
|
||||||
|
live_status = 0
|
||||||
|
|
||||||
|
section("Historical Changelog Exceptions")
|
||||||
|
changelog_matches = scan_paths(lambda path_text: is_under(path_text, (main_exceptions[0],)))
|
||||||
|
if changelog_matches:
|
||||||
|
print(f"{len(changelog_matches)} match(es). Showing up to 40:")
|
||||||
|
for path_text, line_no, line in changelog_matches[:40]:
|
||||||
|
print(f"{path_text}:{line_no}:{line}")
|
||||||
|
if len(changelog_matches) > 40:
|
||||||
|
print("... truncated ...")
|
||||||
|
print("\nHistorical changelog exceptions detected above.")
|
||||||
|
else:
|
||||||
|
print("No matches.")
|
||||||
|
print("No historical changelog hits.")
|
||||||
|
|
||||||
|
section("Generated Bundle Exceptions")
|
||||||
|
generated_matches = scan_paths(lambda path_text: is_under(path_text, generated_exception_paths))
|
||||||
|
if generated_matches:
|
||||||
|
print(f"{len(generated_matches)} match(es). Showing up to 40:")
|
||||||
|
for path_text, line_no, line in generated_matches[:40]:
|
||||||
|
print(f"{path_text}:{line_no}:{line}")
|
||||||
|
if len(generated_matches) > 40:
|
||||||
|
print("... truncated ...")
|
||||||
|
print("\nGenerated bundle exceptions detected above.")
|
||||||
|
else:
|
||||||
|
print("No matches.")
|
||||||
|
print("No generated bundle hits.")
|
||||||
|
|
||||||
|
section("Path Audit")
|
||||||
|
path_matches = []
|
||||||
|
for path in candidate_files():
|
||||||
|
if not path.is_file():
|
||||||
|
continue
|
||||||
|
path_text = rel(path)
|
||||||
|
if is_under(path_text, path_skip_prefixes):
|
||||||
|
continue
|
||||||
|
if path_pattern.search(path_text):
|
||||||
|
path_matches.append(path_text)
|
||||||
|
if path_matches:
|
||||||
|
print("\n".join(path_matches))
|
||||||
|
print("\nPath audit: FAIL")
|
||||||
|
path_status = 1
|
||||||
|
else:
|
||||||
|
print("Path audit: PASS")
|
||||||
|
path_status = 0
|
||||||
|
|
||||||
|
section("Summary")
|
||||||
|
if live_status == 0 and path_status == 0:
|
||||||
|
print("Westernization baseline is clean outside intentional exceptions.")
|
||||||
|
print("Intentional exceptions:")
|
||||||
|
print("- append-only Liquibase history under main/manager-api/src/main/resources/db/changelog")
|
||||||
|
print("- generated generator bundle under main/manager-web/public/generator/assets")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
print("Westernization baseline still has non-exempt findings.")
|
||||||
|
sys.exit(1)
|
||||||
|
PY
|
||||||
|
exit $?
|
||||||
fi
|
fi
|
||||||
|
|
||||||
CONTENT_IGNORE=(
|
CONTENT_IGNORE=(
|
||||||
|
|
@ -40,7 +190,7 @@ MAIN_IGNORE=(
|
||||||
"!main/manager-web/public/generator/assets/**"
|
"!main/manager-web/public/generator/assets/**"
|
||||||
)
|
)
|
||||||
|
|
||||||
CONTENT_PATTERN='[\p{Han}]|zh-CN|zh-TW'
|
CONTENT_PATTERN='[\p{Han}]|zh-C''N|zh-T''W'
|
||||||
PATH_IGNORE=(
|
PATH_IGNORE=(
|
||||||
"./.git"
|
"./.git"
|
||||||
"./node_modules"
|
"./node_modules"
|
||||||
|
|
|
||||||
|
|
@ -173,7 +173,7 @@ Use the audit script after meaningful rebase batches:
|
||||||
|
|
||||||
What it enforces:
|
What it enforces:
|
||||||
|
|
||||||
- live source/docs must be clean of Han-script and `zh-CN` / `zh-TW`
|
- live source/docs must be clean of Han-script and Chinese locale tags
|
||||||
- path names must be clean of Han-script
|
- path names must be clean of Han-script
|
||||||
|
|
||||||
Intentional exception zones:
|
Intentional exception zones:
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue