xiaozhi-esp32-server/main/xiaozhi-server/tests/test_chat_turn_cancellation.py
Allen 5825c4ebaf 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(应用层心跳),
同一开关不应被两套机制共用。
2026-11-26 15:00:10 +08:00

40 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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