mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
fix(ws): 同设备会话收敛、空识别反馈与按轮次判废(#3526 #3000 #3437)
- 新增 DeviceSessionRegistry:同一 device-id 新连接建立时登记并返回旧会话, 服务端主动 abort + 清队列 + close,目标 5 秒内收敛;旧会话结束时只在 自己仍是登记对象时注销,避免把新会话删掉(#3526) - ConnectionHandler.close() 可重复调用(新连接/超时任务可能同时触发), 取消后台初始化任务、给上报线程投毒丸、清空 asr_audio 与队列、 断开 websocket 引用,减少断开重连后的残留(#3000) - ASR 最终文本为空:静音只记日志;检测到有人说话时下发"没听清,请再说一遍", 不再静默丢弃(#3526) - chat() 流式循环改为按轮次判废(abort 或 sentence_id 已被新轮次接管), 避免上一轮 TTS 遗留的迟到 abort 误杀新一轮回答;中断时不写残缺历史、 不发 LAST,并在 finally 关闭底层流(#3437) 主体改动来自上游仓库对象库中已存在的 commit 28463250(作者 agent <agent@local>, 2026-11-23)。它挂在 #3526 / #3000 / #3437 的 referenced 事件上,但既没有分支 也没有 PR,因此一直没被合入。本次提交时移除了该 commit 附带的一组 WebSocket keepalive 配置:上游已在 #3573 / #3575 合入 enable_websocket_ping(应用层心跳), 同一开关不应被两套机制共用。
This commit is contained in:
parent
242a701984
commit
5825c4ebaf
9 changed files with 484 additions and 3 deletions
|
|
@ -185,6 +185,9 @@ class ConnectionHandler:
|
||||||
int(self.config.get("close_connection_no_voice_time", 120)) + 60
|
int(self.config.get("close_connection_no_voice_time", 120)) + 60
|
||||||
) # 在原来第一道关闭的基础上加60秒,进行二道关闭
|
) # 在原来第一道关闭的基础上加60秒,进行二道关闭
|
||||||
self.timeout_task = None
|
self.timeout_task = None
|
||||||
|
# 后台初始化任务句柄与重复清理保护(#3000)
|
||||||
|
self._background_init_task = None
|
||||||
|
self._close_started = False
|
||||||
|
|
||||||
# {"mcp":true} 表示启用MCP功能
|
# {"mcp":true} 表示启用MCP功能
|
||||||
self.features = None
|
self.features = None
|
||||||
|
|
@ -247,7 +250,9 @@ class ConnectionHandler:
|
||||||
self.logger.bind(tag=TAG).info(f"配置输出音频采样率为: {self.sample_rate}")
|
self.logger.bind(tag=TAG).info(f"配置输出音频采样率为: {self.sample_rate}")
|
||||||
|
|
||||||
# 在后台初始化配置和组件(完全不阻塞主循环)
|
# 在后台初始化配置和组件(完全不阻塞主循环)
|
||||||
asyncio.create_task(self._background_initialize())
|
self._background_init_task = asyncio.create_task(
|
||||||
|
self._background_initialize()
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async for message in self.websocket:
|
async for message in self.websocket:
|
||||||
|
|
@ -1054,6 +1059,20 @@ class ConnectionHandler:
|
||||||
# 更新系统prompt至上下文
|
# 更新系统prompt至上下文
|
||||||
self.dialogue.update_system_message(self.prompt)
|
self.dialogue.update_system_message(self.prompt)
|
||||||
|
|
||||||
|
def _is_turn_cancelled(self, current_sentence_id) -> bool:
|
||||||
|
"""本轮是否应停止流式输出。
|
||||||
|
|
||||||
|
用户打断(client_abort)应即时生效;但 abort 也可能是上一轮 TTS 遗留的
|
||||||
|
迟到消息(barge-in 竞态),此时 sentence_id 已被新一轮覆盖,只应判废旧轮。
|
||||||
|
因此不能靠"流开始前清标志"(会吞掉真实打断),而是按轮次判废(#3437)。
|
||||||
|
"""
|
||||||
|
if self.client_abort:
|
||||||
|
return True
|
||||||
|
return (
|
||||||
|
current_sentence_id is not None
|
||||||
|
and current_sentence_id != self.sentence_id
|
||||||
|
)
|
||||||
|
|
||||||
def chat(self, query, depth=0, speaker=None):
|
def chat(self, query, depth=0, speaker=None):
|
||||||
# speaker: 本轮声纹身份快照,随工具调用下传
|
# speaker: 本轮声纹身份快照,随工具调用下传
|
||||||
# 保存当前任务的sentence_id到局部变量,避免被新任务覆盖
|
# 保存当前任务的sentence_id到局部变量,避免被新任务覆盖
|
||||||
|
|
@ -1167,9 +1186,11 @@ class ConnectionHandler:
|
||||||
tool_calls_list = [] # 格式: [{"id": "", "name": "", "arguments": ""}]
|
tool_calls_list = [] # 格式: [{"id": "", "name": "", "arguments": ""}]
|
||||||
content_arguments = ""
|
content_arguments = ""
|
||||||
emotion_flag = True
|
emotion_flag = True
|
||||||
|
interrupted = False
|
||||||
try:
|
try:
|
||||||
for response in llm_responses:
|
for response in llm_responses:
|
||||||
if self.client_abort:
|
if self._is_turn_cancelled(current_sentence_id):
|
||||||
|
interrupted = True
|
||||||
break
|
break
|
||||||
if self.intent_type == "function_call" and functions is not None:
|
if self.intent_type == "function_call" and functions is not None:
|
||||||
content, tools_call = response
|
content, tools_call = response
|
||||||
|
|
@ -1252,6 +1273,18 @@ class ConnectionHandler:
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
finally:
|
||||||
|
# 中断或正常结束都释放底层流式响应,避免 HTTP 流悬挂(#3437)
|
||||||
|
try:
|
||||||
|
llm_responses.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if interrupted:
|
||||||
|
self.logger.bind(tag=TAG).info(
|
||||||
|
f"本轮回答已取消(用户打断或已有新一轮接管)turn={current_sentence_id},"
|
||||||
|
f"跳过历史写入与收尾"
|
||||||
|
)
|
||||||
|
return False
|
||||||
# 处理function call
|
# 处理function call
|
||||||
if tool_call_flag:
|
if tool_call_flag:
|
||||||
bHasError = False
|
bHasError = False
|
||||||
|
|
@ -1556,7 +1589,11 @@ class ConnectionHandler:
|
||||||
self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态")
|
self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态")
|
||||||
|
|
||||||
async def close(self, ws=None):
|
async def close(self, ws=None):
|
||||||
"""资源清理方法"""
|
"""资源清理方法(可重复调用:同设备重连时会被新连接、超时任务同时触发)"""
|
||||||
|
if getattr(self, "_close_started", False):
|
||||||
|
self.logger.bind(tag=TAG).debug("连接资源已清理过,跳过重复清理")
|
||||||
|
return
|
||||||
|
self._close_started = True
|
||||||
try:
|
try:
|
||||||
# 清理 VAD 连接资源
|
# 清理 VAD 连接资源
|
||||||
if (
|
if (
|
||||||
|
|
@ -1586,6 +1623,18 @@ class ConnectionHandler:
|
||||||
pass
|
pass
|
||||||
self.timeout_task = None
|
self.timeout_task = None
|
||||||
|
|
||||||
|
# 取消后台初始化任务:连接已断开就没必要再拉模型/查配置(#3000)
|
||||||
|
if (
|
||||||
|
getattr(self, "_background_init_task", None)
|
||||||
|
and not self._background_init_task.done()
|
||||||
|
):
|
||||||
|
self._background_init_task.cancel()
|
||||||
|
try:
|
||||||
|
await self._background_init_task
|
||||||
|
except (asyncio.CancelledError, Exception):
|
||||||
|
pass
|
||||||
|
self._background_init_task = None
|
||||||
|
|
||||||
# 取消AEC缓存清理任务
|
# 取消AEC缓存清理任务
|
||||||
if hasattr(self, "_aec_cache_cleanup_task") and self._aec_cache_cleanup_task and not self._aec_cache_cleanup_task.done():
|
if hasattr(self, "_aec_cache_cleanup_task") and self._aec_cache_cleanup_task and not self._aec_cache_cleanup_task.done():
|
||||||
self._aec_cache_cleanup_task.cancel()
|
self._aec_cache_cleanup_task.cancel()
|
||||||
|
|
@ -1616,6 +1665,22 @@ class ConnectionHandler:
|
||||||
# 清空任务队列
|
# 清空任务队列
|
||||||
self.clear_queues()
|
self.clear_queues()
|
||||||
|
|
||||||
|
# 上报线程收到毒丸后退出;清空 ASR 缓冲与队列,避免断开重连残留(#3000)
|
||||||
|
if self.report_thread is not None and self.report_thread.is_alive():
|
||||||
|
try:
|
||||||
|
self.report_queue.put(None)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self.report_thread = None
|
||||||
|
try:
|
||||||
|
self.asr_audio.clear()
|
||||||
|
while True:
|
||||||
|
self.asr_audio_queue.get_nowait()
|
||||||
|
except queue.Empty:
|
||||||
|
pass
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
# 关闭WebSocket连接
|
# 关闭WebSocket连接
|
||||||
try:
|
try:
|
||||||
if ws:
|
if ws:
|
||||||
|
|
@ -1666,6 +1731,8 @@ class ConnectionHandler:
|
||||||
f"关闭线程池时出错: {executor_error}"
|
f"关闭线程池时出错: {executor_error}"
|
||||||
)
|
)
|
||||||
self.executor = None
|
self.executor = None
|
||||||
|
# 断开对 WebSocket 的引用,避免事件循环/传输层对象被长期持有(#3000)
|
||||||
|
self.websocket = None
|
||||||
self.logger.bind(tag=TAG).info("连接资源已释放")
|
self.logger.bind(tag=TAG).info("连接资源已释放")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"关闭连接时出错: {e}")
|
self.logger.bind(tag=TAG).error(f"关闭连接时出错: {e}")
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,8 @@ from config.logger import setup_logging
|
||||||
from core.providers.asr.dto.dto import InterfaceType
|
from core.providers.asr.dto.dto import InterfaceType
|
||||||
from core.handle.receiveAudioHandle import startToChat
|
from core.handle.receiveAudioHandle import startToChat
|
||||||
from core.handle.reportHandle import enqueue_asr_report
|
from core.handle.reportHandle import enqueue_asr_report
|
||||||
|
from core.handle.sendAudioHandle import send_stt_message
|
||||||
|
from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType
|
||||||
from core.utils.util import remove_punctuation_and_length
|
from core.utils.util import remove_punctuation_and_length
|
||||||
from core.utils.voiceprint_provider import SpeakerIdentification
|
from core.utils.voiceprint_provider import SpeakerIdentification
|
||||||
from core.handle.receiveAudioHandle import handleAudioMessage
|
from core.handle.receiveAudioHandle import handleAudioMessage
|
||||||
|
|
@ -28,6 +30,9 @@ if TYPE_CHECKING:
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
# 有实音但识别为空时的提示语(#3526)
|
||||||
|
EMPTY_ASR_PROMPT = "没听清,请再说一遍。"
|
||||||
|
|
||||||
|
|
||||||
class ASRProviderBase(ABC):
|
class ASRProviderBase(ABC):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|
@ -175,12 +180,50 @@ class ASRProviderBase(ABC):
|
||||||
enqueue_asr_report(conn, enhanced_text, audio_snapshot)
|
enqueue_asr_report(conn, enhanced_text, audio_snapshot)
|
||||||
# 使用自定义模块进行上报
|
# 使用自定义模块进行上报
|
||||||
await startToChat(conn, enhanced_text, speaker=speaker)
|
await startToChat(conn, enhanced_text, speaker=speaker)
|
||||||
|
else:
|
||||||
|
# 空识别:静音只记日志;确实检测到有人说话时给一句提示,
|
||||||
|
# 否则用户只会觉得"我说完了小智没反应"(#3526)
|
||||||
|
await self.notify_empty_asr(conn, bool(getattr(conn, "client_have_voice", False)))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
|
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
|
||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}")
|
logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}")
|
||||||
|
|
||||||
|
async def notify_empty_asr(self, conn: "ConnectionHandler", had_voice: bool):
|
||||||
|
"""ASR 最终文本为空时的收尾:静音场景只记日志,有实音则提示用户重说一次。"""
|
||||||
|
if not had_voice:
|
||||||
|
logger.bind(tag=TAG).info("识别到空文本(静音),跳过本轮")
|
||||||
|
return
|
||||||
|
logger.bind(tag=TAG).info("识别到空文本但检测到有人说话,提示用户重说")
|
||||||
|
try:
|
||||||
|
await send_stt_message(conn, EMPTY_ASR_PROMPT)
|
||||||
|
sentence_id = str(uuid.uuid4().hex)
|
||||||
|
conn.tts.tts_text_queue.put(
|
||||||
|
TTSMessageDTO(
|
||||||
|
sentence_id=sentence_id,
|
||||||
|
sentence_type=SentenceType.FIRST,
|
||||||
|
content_type=ContentType.ACTION,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
conn.tts.tts_text_queue.put(
|
||||||
|
TTSMessageDTO(
|
||||||
|
sentence_id=sentence_id,
|
||||||
|
sentence_type=SentenceType.MIDDLE,
|
||||||
|
content_type=ContentType.TEXT,
|
||||||
|
content_detail=EMPTY_ASR_PROMPT,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
conn.tts.tts_text_queue.put(
|
||||||
|
TTSMessageDTO(
|
||||||
|
sentence_id=sentence_id,
|
||||||
|
sentence_type=SentenceType.LAST,
|
||||||
|
content_type=ContentType.ACTION,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"发送空识别提示失败: {e}")
|
||||||
|
|
||||||
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
|
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
|
||||||
"""构建包含说话人信息的文本(仅用于纯文本ASR)"""
|
"""构建包含说话人信息的文本(仅用于纯文本ASR)"""
|
||||||
if speaker_name and speaker_name.strip():
|
if speaker_name and speaker_name.strip():
|
||||||
|
|
|
||||||
46
main/xiaozhi-server/core/utils/device_session_registry.py
Normal file
46
main/xiaozhi-server/core/utils/device_session_registry.py
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceSessionRegistry:
|
||||||
|
"""(device-id → 活跃 ConnectionHandler) 注册表。
|
||||||
|
|
||||||
|
同一台设备重连时,新连接必须先让旧会话收敛:否则两条 ConnectionHandler
|
||||||
|
同时存在,会出现回复串台、丢回复,旧会话的 ASR/LLM/TTS 继续占用下游连接,
|
||||||
|
直到 120s+60s 的静默超时才被回收(#3526)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._handlers: Dict[str, Any] = {}
|
||||||
|
self._lock = asyncio.Lock()
|
||||||
|
|
||||||
|
async def bind(self, device_id: Optional[str], handler: Any) -> Optional[Any]:
|
||||||
|
"""登记新会话并返回被顶替的旧会话(没有则返回 None)。"""
|
||||||
|
if not device_id:
|
||||||
|
return None
|
||||||
|
async with self._lock:
|
||||||
|
old = self._handlers.get(device_id)
|
||||||
|
if old is handler:
|
||||||
|
return None
|
||||||
|
self._handlers[device_id] = handler
|
||||||
|
return old
|
||||||
|
|
||||||
|
async def release(self, device_id: Optional[str], handler: Any) -> bool:
|
||||||
|
"""会话结束时注销;只有自己仍是登记对象时才移除,避免误删新会话。"""
|
||||||
|
if not device_id:
|
||||||
|
return False
|
||||||
|
async with self._lock:
|
||||||
|
if self._handlers.get(device_id) is handler:
|
||||||
|
self._handlers.pop(device_id, None)
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get(self, device_id: Optional[str]) -> Optional[Any]:
|
||||||
|
if not device_id:
|
||||||
|
return None
|
||||||
|
return self._handlers.get(device_id)
|
||||||
|
|
||||||
|
def active_count(self) -> int:
|
||||||
|
return len(self._handlers)
|
||||||
|
|
@ -35,6 +35,7 @@ from config.config_loader import get_config_from_api_async
|
||||||
from core.auth import AuthManager, AuthenticationError
|
from core.auth import AuthManager, AuthenticationError
|
||||||
from core.utils.modules_initialize import initialize_modules
|
from core.utils.modules_initialize import initialize_modules
|
||||||
from core.utils.util import check_vad_update, check_asr_update
|
from core.utils.util import check_vad_update, check_asr_update
|
||||||
|
from core.utils.device_session_registry import DeviceSessionRegistry
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
@ -68,6 +69,9 @@ class WebSocketServer:
|
||||||
expire_seconds = auth_config.get("expire_seconds", None)
|
expire_seconds = auth_config.get("expire_seconds", None)
|
||||||
self.auth = AuthManager(secret_key=secret_key, expire_seconds=expire_seconds)
|
self.auth = AuthManager(secret_key=secret_key, expire_seconds=expire_seconds)
|
||||||
|
|
||||||
|
# 同一 device-id 只保留一个活跃会话(#3526)
|
||||||
|
self.device_sessions = DeviceSessionRegistry()
|
||||||
|
|
||||||
async def start(self):
|
async def start(self):
|
||||||
server_config = self.config["server"]
|
server_config = self.config["server"]
|
||||||
host = server_config.get("ip", "0.0.0.0")
|
host = server_config.get("ip", "0.0.0.0")
|
||||||
|
|
@ -127,11 +131,17 @@ class WebSocketServer:
|
||||||
self._intent,
|
self._intent,
|
||||||
self, # 传入server实例
|
self, # 传入server实例
|
||||||
)
|
)
|
||||||
|
# 同设备重连:先关掉旧会话,避免两条会话并存(#3526)
|
||||||
|
device_id = websocket.request.headers.get("device-id")
|
||||||
|
stale = await self.device_sessions.bind(device_id, handler)
|
||||||
|
if stale is not None and stale is not handler:
|
||||||
|
await self._close_stale_session(device_id, stale)
|
||||||
try:
|
try:
|
||||||
await handler.handle_connection(websocket)
|
await handler.handle_connection(websocket)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"处理连接时出错: {e}")
|
self.logger.bind(tag=TAG).error(f"处理连接时出错: {e}")
|
||||||
finally:
|
finally:
|
||||||
|
await self.device_sessions.release(device_id, handler)
|
||||||
# 强制关闭连接(如果还没有关闭的话)
|
# 强制关闭连接(如果还没有关闭的话)
|
||||||
try:
|
try:
|
||||||
# 安全地检查WebSocket状态并关闭
|
# 安全地检查WebSocket状态并关闭
|
||||||
|
|
@ -147,6 +157,22 @@ class WebSocketServer:
|
||||||
f"服务器端强制关闭连接时出错: {close_error}"
|
f"服务器端强制关闭连接时出错: {close_error}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def _close_stale_session(self, device_id, handler, timeout: float = 5.0):
|
||||||
|
"""主动收敛被顶替的旧会话,目标 5 秒内关闭(#3526)。"""
|
||||||
|
try:
|
||||||
|
self.logger.bind(tag=TAG).info(
|
||||||
|
f"设备 {device_id} 建立新连接,主动关闭旧会话 {handler.session_id}"
|
||||||
|
)
|
||||||
|
handler.client_abort = True
|
||||||
|
handler.clear_queues()
|
||||||
|
await asyncio.wait_for(handler.close(handler.websocket), timeout=timeout)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
self.logger.bind(tag=TAG).warning(
|
||||||
|
f"关闭设备 {device_id} 旧会话超时(>{timeout:g}s),继续处理新连接"
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"关闭设备 {device_id} 旧会话失败: {e}")
|
||||||
|
|
||||||
async def _http_response(self, websocket, request_headers):
|
async def _http_response(self, websocket, request_headers):
|
||||||
# 检查是否为 WebSocket 升级请求
|
# 检查是否为 WebSocket 升级请求
|
||||||
if request_headers.headers.get("connection", "").lower() == "upgrade":
|
if request_headers.headers.get("connection", "").lower() == "upgrade":
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,63 @@
|
||||||
|
import asyncio
|
||||||
|
import queue
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from core.providers.asr import base as asr_base
|
||||||
|
from core.providers.asr.base import ASRProviderBase
|
||||||
|
|
||||||
|
|
||||||
|
class DummyASR(ASRProviderBase):
|
||||||
|
async def speech_to_text(self, opus_data, session_id, artifacts=None):
|
||||||
|
return "", None
|
||||||
|
|
||||||
|
|
||||||
|
def _make_conn(have_voice):
|
||||||
|
tts_queue = queue.Queue()
|
||||||
|
return SimpleNamespace(
|
||||||
|
client_have_voice=have_voice,
|
||||||
|
tts=SimpleNamespace(tts_text_queue=tts_queue),
|
||||||
|
session_id="s-1",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_silence_only_logs(monkeypatch):
|
||||||
|
sent = []
|
||||||
|
|
||||||
|
async def fake_send_stt(conn, text):
|
||||||
|
sent.append(text)
|
||||||
|
|
||||||
|
monkeypatch.setattr(asr_base, "send_stt_message", fake_send_stt)
|
||||||
|
conn = _make_conn(have_voice=False)
|
||||||
|
asyncio.run(DummyASR().notify_empty_asr(conn, had_voice=False))
|
||||||
|
assert sent == []
|
||||||
|
assert conn.tts.tts_text_queue.empty()
|
||||||
|
|
||||||
|
|
||||||
|
def test_voice_with_empty_asr_prompts_user(monkeypatch):
|
||||||
|
sent = []
|
||||||
|
|
||||||
|
async def fake_send_stt(conn, text):
|
||||||
|
sent.append(text)
|
||||||
|
|
||||||
|
monkeypatch.setattr(asr_base, "send_stt_message", fake_send_stt)
|
||||||
|
conn = _make_conn(have_voice=True)
|
||||||
|
asyncio.run(DummyASR().notify_empty_asr(conn, had_voice=True))
|
||||||
|
|
||||||
|
assert sent == [asr_base.EMPTY_ASR_PROMPT]
|
||||||
|
kinds = []
|
||||||
|
while not conn.tts.tts_text_queue.empty():
|
||||||
|
kinds.append(conn.tts.tts_text_queue.get_nowait())
|
||||||
|
# FIRST / MIDDLE / LAST 三个消息,且同一 sentence_id
|
||||||
|
assert [m.sentence_type.name for m in kinds] == ["FIRST", "MIDDLE", "LAST"]
|
||||||
|
assert len({m.sentence_id for m in kinds}) == 1
|
||||||
|
assert kinds[1].content_detail == asr_base.EMPTY_ASR_PROMPT
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_failure_does_not_raise(monkeypatch):
|
||||||
|
async def boom(conn, text):
|
||||||
|
raise RuntimeError("ws gone")
|
||||||
|
|
||||||
|
monkeypatch.setattr(asr_base, "send_stt_message", boom)
|
||||||
|
conn = _make_conn(have_voice=True)
|
||||||
|
# 不应向上抛异常影响连接
|
||||||
|
asyncio.run(DummyASR().notify_empty_asr(conn, had_voice=True))
|
||||||
|
|
@ -0,0 +1,73 @@
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
from core.utils.device_session_registry import DeviceSessionRegistry
|
||||||
|
|
||||||
|
|
||||||
|
class FakeHandler:
|
||||||
|
def __init__(self, name):
|
||||||
|
self.name = name
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"FakeHandler({self.name})"
|
||||||
|
|
||||||
|
|
||||||
|
def test_same_device_rebind_returns_old_handler():
|
||||||
|
async def run():
|
||||||
|
reg = DeviceSessionRegistry()
|
||||||
|
first, second = FakeHandler("first"), FakeHandler("second")
|
||||||
|
assert await reg.bind("dev-1", first) is None
|
||||||
|
assert await reg.bind("dev-1", second) is first
|
||||||
|
assert reg.get("dev-1") is second
|
||||||
|
assert reg.active_count() == 1
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
|
|
||||||
|
|
||||||
|
def test_bind_without_device_id_is_noop():
|
||||||
|
async def run():
|
||||||
|
reg = DeviceSessionRegistry()
|
||||||
|
handler = FakeHandler("h")
|
||||||
|
assert await reg.bind(None, handler) is None
|
||||||
|
assert await reg.bind("", handler) is None
|
||||||
|
assert reg.active_count() == 0
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
|
|
||||||
|
|
||||||
|
def test_rebind_same_handler_returns_none():
|
||||||
|
async def run():
|
||||||
|
reg = DeviceSessionRegistry()
|
||||||
|
handler = FakeHandler("h")
|
||||||
|
await reg.bind("dev-1", handler)
|
||||||
|
assert await reg.bind("dev-1", handler) is None
|
||||||
|
assert reg.get("dev-1") is handler
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
|
|
||||||
|
|
||||||
|
def test_release_only_removes_own_handler():
|
||||||
|
async def run():
|
||||||
|
reg = DeviceSessionRegistry()
|
||||||
|
old, new = FakeHandler("old"), FakeHandler("new")
|
||||||
|
await reg.bind("dev-1", old)
|
||||||
|
await reg.bind("dev-1", new)
|
||||||
|
# 旧会话收尾时不得把新会话从注册表里删掉
|
||||||
|
assert await reg.release("dev-1", old) is False
|
||||||
|
assert reg.get("dev-1") is new
|
||||||
|
assert await reg.release("dev-1", new) is True
|
||||||
|
assert reg.get("dev-1") is None
|
||||||
|
assert reg.active_count() == 0
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
|
|
||||||
|
|
||||||
|
def test_devices_are_isolated():
|
||||||
|
async def run():
|
||||||
|
reg = DeviceSessionRegistry()
|
||||||
|
a, b = FakeHandler("a"), FakeHandler("b")
|
||||||
|
await reg.bind("dev-a", a)
|
||||||
|
await reg.bind("dev-b", b)
|
||||||
|
assert reg.active_count() == 2
|
||||||
|
assert reg.get("dev-a") is a and reg.get("dev-b") is b
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
40
main/xiaozhi-server/tests/test_chat_turn_cancellation.py
Normal file
40
main/xiaozhi-server/tests/test_chat_turn_cancellation.py
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
|
|
||||||
|
def _handler(client_abort=False, sentence_id=None):
|
||||||
|
# 只测纯判定逻辑,不触发 __init__ 里的重资源初始化
|
||||||
|
h = ConnectionHandler.__new__(ConnectionHandler)
|
||||||
|
h.client_abort = client_abort
|
||||||
|
h.sentence_id = sentence_id
|
||||||
|
return h
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_turn_is_not_cancelled():
|
||||||
|
h = _handler(sentence_id="turn-b")
|
||||||
|
assert h._is_turn_cancelled("turn-b") is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_user_abort_cancels_current_turn():
|
||||||
|
h = _handler(client_abort=True, sentence_id="turn-b")
|
||||||
|
assert h._is_turn_cancelled("turn-b") is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_stale_abort_from_previous_turn_does_not_kill_new_turn():
|
||||||
|
# 上一轮 TTS 的迟到 abort 已置位,但新一轮已接管(sentence_id 已更新):
|
||||||
|
# 旧轮(turn-a)判废,新轮(turn-b)不受影响 —— #3437 的核心断言
|
||||||
|
h = _handler(client_abort=True, sentence_id="turn-b")
|
||||||
|
assert h._is_turn_cancelled("turn-a") is True
|
||||||
|
h.client_abort = False
|
||||||
|
assert h._is_turn_cancelled("turn-b") is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_turn_replaced_by_newer_turn_stops_old_turn():
|
||||||
|
h = _handler(sentence_id="turn-c")
|
||||||
|
assert h._is_turn_cancelled("turn-b") is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_none_sentence_id_only_abort_matters():
|
||||||
|
h = _handler(sentence_id="turn-b")
|
||||||
|
assert h._is_turn_cancelled(None) is False
|
||||||
|
h.client_abort = True
|
||||||
|
assert h._is_turn_cancelled(None) is True
|
||||||
|
|
@ -0,0 +1,58 @@
|
||||||
|
import asyncio
|
||||||
|
import queue
|
||||||
|
import threading
|
||||||
|
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
|
|
||||||
|
class _Logger:
|
||||||
|
def bind(self, **kwargs):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def info(self, *a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
warning = error = debug = info
|
||||||
|
|
||||||
|
|
||||||
|
def _bare_handler():
|
||||||
|
h = ConnectionHandler.__new__(ConnectionHandler) # 跳过 __init__ 的重资源初始化
|
||||||
|
h.logger = _Logger()
|
||||||
|
h.stop_event = threading.Event()
|
||||||
|
h.timeout_task = None
|
||||||
|
h._background_init_task = None
|
||||||
|
h._close_started = False
|
||||||
|
h.tts = None
|
||||||
|
h.asr = None
|
||||||
|
h.executor = None
|
||||||
|
h.report_thread = None
|
||||||
|
h.report_queue = queue.Queue()
|
||||||
|
h.asr_audio = []
|
||||||
|
h.asr_audio_queue = queue.Queue()
|
||||||
|
h.websocket = object()
|
||||||
|
return h
|
||||||
|
|
||||||
|
|
||||||
|
def test_close_is_idempotent():
|
||||||
|
h = _bare_handler()
|
||||||
|
|
||||||
|
async def run():
|
||||||
|
await h.close()
|
||||||
|
assert h._close_started is True
|
||||||
|
assert h.websocket is None
|
||||||
|
await h.close() # 第二次应直接返回,不再重复释放
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
|
|
||||||
|
|
||||||
|
def test_close_drains_asr_buffers():
|
||||||
|
h = _bare_handler()
|
||||||
|
h.asr_audio.extend([b"a", b"b"])
|
||||||
|
h.asr_audio_queue.put(b"x")
|
||||||
|
|
||||||
|
async def run():
|
||||||
|
await h.close()
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
|
assert h.asr_audio == []
|
||||||
|
assert h.asr_audio_queue.empty()
|
||||||
65
main/xiaozhi-server/tests/test_ws_session_convergence.py
Normal file
65
main/xiaozhi-server/tests/test_ws_session_convergence.py
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
from core.websocket_server import WebSocketServer
|
||||||
|
from core.utils.device_session_registry import DeviceSessionRegistry
|
||||||
|
|
||||||
|
|
||||||
|
class _Logger:
|
||||||
|
def bind(self, **kwargs):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def info(self, *args, **kwargs):
|
||||||
|
pass
|
||||||
|
|
||||||
|
warning = error = debug = info
|
||||||
|
|
||||||
|
|
||||||
|
class FakeHandler:
|
||||||
|
def __init__(self, name="old"):
|
||||||
|
self.session_id = name
|
||||||
|
self.client_abort = False
|
||||||
|
self.cleared = False
|
||||||
|
self.closed = False
|
||||||
|
self.websocket = object()
|
||||||
|
|
||||||
|
def clear_queues(self):
|
||||||
|
self.cleared = True
|
||||||
|
|
||||||
|
async def close(self, ws=None):
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
|
||||||
|
def _server():
|
||||||
|
srv = WebSocketServer.__new__(WebSocketServer) # 跳过 __init__ 的组件初始化
|
||||||
|
srv.logger = _Logger()
|
||||||
|
srv.device_sessions = DeviceSessionRegistry()
|
||||||
|
return srv
|
||||||
|
|
||||||
|
|
||||||
|
def test_stale_session_is_aborted_cleared_and_closed():
|
||||||
|
srv = _server()
|
||||||
|
old = FakeHandler("old")
|
||||||
|
|
||||||
|
async def run():
|
||||||
|
await srv._close_stale_session("dev-1", old)
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
|
assert old.client_abort is True
|
||||||
|
assert old.cleared is True
|
||||||
|
assert old.closed is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_stale_session_close_error_is_swallowed():
|
||||||
|
srv = _server()
|
||||||
|
|
||||||
|
class Boom(FakeHandler):
|
||||||
|
async def close(self, ws=None):
|
||||||
|
raise RuntimeError("ws already gone")
|
||||||
|
|
||||||
|
old = Boom("boom")
|
||||||
|
|
||||||
|
async def run():
|
||||||
|
await srv._close_stale_session("dev-1", old)
|
||||||
|
|
||||||
|
asyncio.run(run()) # 不向上抛,新连接不受影响
|
||||||
|
assert old.client_abort is True
|
||||||
Loading…
Reference in a new issue