fix(stream): isolate cancelled chat and TTS turns

This commit is contained in:
koala553 2026-11-11 16:24:34 +08:00
parent 6275a83e3a
commit f43eccab4f
8 changed files with 494 additions and 90 deletions

View file

@ -1052,17 +1052,24 @@ class ConnectionHandler:
# 更新系统prompt至上下文
self.dialogue.update_system_message(self.prompt)
def chat(self, query, depth=0):
# 保存当前任务的sentence_id到局部变量,避免被新任务覆盖
current_sentence_id = None
def chat(self, query, depth=0, current_sentence_id=None):
# 递归和线程池任务必须保留原始轮次,不能认领新的共享 sentence_id。
if current_sentence_id is None:
current_sentence_id = uuid.uuid4().hex if depth == 0 else self.sentence_id
if depth == 0:
self.sentence_id = current_sentence_id
def cancelled():
return self.client_abort or current_sentence_id != self.sentence_id
if cancelled():
return True
if query is not None:
self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
# 为最顶层时新建会话ID和发送FIRST请求
if depth == 0:
current_sentence_id = str(uuid.uuid4().hex)
self.sentence_id = current_sentence_id # 更新共享属性
self.dialogue.put(Message(role="user", content=query))
self.tts.tts_text_queue.put(
TTSMessageDTO(
@ -1071,9 +1078,6 @@ class ConnectionHandler:
content_type=ContentType.ACTION,
)
)
else:
# 递归调用时,使用当前的sentence_id
current_sentence_id = self.sentence_id
# 设置最大递归深度,避免无限循环,可根据实际需求调整
MAX_DEPTH = 5
@ -1118,6 +1122,9 @@ class ConnectionHandler:
)
memory_str = future.result()
if cancelled():
return True
# 仅在该说话人首次出现时把身份注入 system,之后靠对话历史首轮保留,
# 避免每轮在 system 重复出现名字诱导模型反复称呼
speaker_for_system = None
@ -1126,6 +1133,10 @@ class ConnectionHandler:
self.system_introduced_speakers.add(cs)
speaker_for_system = cs
cancel_kwargs = (
{"cancel_check": cancelled}
if getattr(self.llm, "supports_cancel_check", False) else {}
)
if self.intent_type == "function_call" and functions is not None:
# 使用支持functions的streaming接口
llm_responses = self.llm.response_with_functions(
@ -1134,6 +1145,7 @@ class ConnectionHandler:
memory_str, self.config.get("voiceprint", {}), speaker_for_system
),
functions=functions,
**cancel_kwargs,
)
else:
llm_responses = self.llm.response(
@ -1141,24 +1153,14 @@ class ConnectionHandler:
self.dialogue.get_llm_dialogue_with_memory(
memory_str, self.config.get("voiceprint", {}), speaker_for_system
),
**cancel_kwargs,
)
except Exception as e:
if cancelled():
return True
self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
return None
# 修复 barge-in 竞态:上一轮 TTS 播放被打断时,设备发来的 abort 消息可能在本轮
# LLM 流建立之后才到达(abortHandle 会把 client_abort 置为 True)。若不清掉这个
# 残留标志,本轮回答会在首个分片处被误判为"已打断"而提前退出——表现为只播第一
# 句甚至完全没有声音,且服务端没有任何报错。
# 只在顶层轮次(depth == 0,即用户新的一次提问)的流开始前清理一次;本轮流式期间
# 新到达的 abort 仍会即时置位并正常打断。递归调用(depth > 0,工具调用后继续生成)
# 不清理,避免把本轮工具执行期间产生的打断吞掉。
if depth == 0 and self.client_abort:
self.logger.bind(tag=TAG).debug(
"清理上一轮残留的打断标志,避免误断本轮 LLM 流"
)
self.client_abort = False
# 处理流式响应
tool_call_flag = False
# 支持多个并行工具调用 - 使用列表存储
@ -1167,7 +1169,7 @@ class ConnectionHandler:
emotion_flag = True
try:
for response in llm_responses:
if self.client_abort:
if cancelled():
break
if self.intent_type == "function_call" and functions is not None:
content, tools_call = response
@ -1232,6 +1234,8 @@ class ConnectionHandler:
)
)
except Exception as e:
if cancelled():
return True
self.logger.bind(tag=TAG).error(f"LLM stream processing error: {e}")
self.tts.tts_text_queue.put(
TTSMessageDTO(
@ -1250,6 +1254,21 @@ class ConnectionHandler:
)
)
return
finally:
close_stream = getattr(llm_responses, "close", None)
if close_stream is not None:
try:
close_stream()
except Exception as e:
self.logger.bind(tag=TAG).debug(f"关闭 LLM 流失败: {e}")
self.logger.bind(tag=TAG).debug(
f"CHAT_STREAM_END turn={current_sentence_id} interrupted={cancelled()}"
)
# 中断后不能执行已缓存的工具调用、写残缺历史或发 LAST。
if cancelled():
return True
# 处理function call
if tool_call_flag:
bHasError = False
@ -1340,6 +1359,8 @@ class ConnectionHandler:
# 收集所有工具调用的 Future
futures_with_data = []
for tool_call_data in tool_calls_list:
if cancelled():
return True
self.logger.bind(tag=TAG).debug(
f"function_name={tool_call_data['name']}, function_id={tool_call_data['id']}, function_arguments={tool_call_data['arguments']}"
)
@ -1348,12 +1369,13 @@ class ConnectionHandler:
tool_input = json.loads(tool_call_data.get("arguments") or "{}")
enqueue_tool_report(self, tool_call_data['name'], tool_input)
future = asyncio.run_coroutine_threadsafe(
self.func_handler.handle_llm_function_call(
self, tool_call_data
),
self.loop,
)
async def invoke_tool(data=tool_call_data):
# 提交到事件循环后也可能已换轮,在真正执行前再次判断。
if cancelled():
return None
return await self.func_handler.handle_llm_function_call(self, data)
future = asyncio.run_coroutine_threadsafe(invoke_tool(), self.loop)
futures_with_data.append((future, tool_call_data, tool_input))
# 工具调用超时时间,可配置,默认30秒
@ -1364,6 +1386,8 @@ class ConnectionHandler:
for future, tool_call_data, tool_input in futures_with_data:
try:
result = future.result(timeout=tool_call_timeout)
if cancelled() or result is None:
return True
tool_results.append((result, tool_call_data))
# 使用公共方法上报工具调用结果
enqueue_tool_report(self, tool_call_data['name'], tool_input, str(result.result) if result.result else None, report_tool_call=False)
@ -1381,10 +1405,17 @@ class ConnectionHandler:
enqueue_tool_report(self, tool_call_data['name'], tool_input, str(e), report_tool_call=False)
# 统一处理工具调用结果
if cancelled():
return True
if tool_results:
self._handle_function_result(tool_results, depth=depth, streamed_text=streamed_text)
self._handle_function_result(
tool_results, depth=depth, streamed_text=streamed_text,
current_sentence_id=current_sentence_id,
)
# 存储对话内容
if cancelled():
return True
if len(response_message) > 0:
text_buff = "".join(response_message)
self.tts.store_tts_text(current_sentence_id, text_buff)
@ -1407,11 +1438,20 @@ class ConnectionHandler:
return True
def _handle_function_result(self, tool_results, depth, streamed_text=""):
def _handle_function_result(self, tool_results, depth, streamed_text="", current_sentence_id=None):
current_sentence_id = current_sentence_id or self.sentence_id
def cancelled():
return self.client_abort or current_sentence_id != self.sentence_id
if cancelled():
return
need_llm_tools = []
record_tools = []
for result, tool_call_data in tool_results:
if cancelled():
return
if result.action in [
Action.RESPONSE,
Action.NOTFOUND,
@ -1423,8 +1463,8 @@ class ConnectionHandler:
f"Skipping duplicate TTS for tool {tool_call_data['name']}, already streamed"
)
else:
self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text)
self.tts.store_tts_text(self.sentence_id, text)
self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text, sentence_id=current_sentence_id)
self.tts.store_tts_text(current_sentence_id, text)
self.dialogue.put(Message(role="assistant", content=text))
elif result.action == Action.REQLLM:
need_llm_tools.append((result, tool_call_data))
@ -1434,6 +1474,8 @@ class ConnectionHandler:
pass
# Action.RECORD:写入完整工具调用链(assistant(tool_calls) → tool(result) → assistant(response))
if cancelled():
return
# 模型从历史中学到工具调用模式,不额外调用LLM
if record_tools:
# 构造 assistant 消息(含 tool_calls),记录"模型调用了哪些工具"
@ -1513,7 +1555,7 @@ class ConnectionHandler:
)
)
self.chat(None, depth=depth + 1)
self.chat(None, depth=depth + 1, current_sentence_id=current_sentence_id)
def _report_worker(self):
"""聊天记录上报工作线程"""

View file

@ -1,6 +1,7 @@
import time
import json
import asyncio
import uuid
from typing import TYPE_CHECKING
if TYPE_CHECKING:
@ -102,9 +103,11 @@ async def startToChat(conn: "ConnectionHandler", text):
await send_stt_message(conn, actual_text)
# 准备开始新会话
# 在提交前确定轮次,避免线程池调度顺序让旧请求覆盖新轮次。
sentence_id = uuid.uuid4().hex
conn.sentence_id = sentence_id
conn.client_abort = False
conn.executor.submit(conn.chat, actual_text)
conn.executor.submit(conn.chat, actual_text, current_sentence_id=sentence_id)
async def no_voice_close_connect(conn: "ConnectionHandler", have_voice):

View file

@ -17,8 +17,9 @@ PRE_BUFFER_COUNT = 2 # 首段发送时不入队的帧数,避免流控延迟
async def sendAudioMessage(conn: "ConnectionHandler", sentenceType, audios, text, sentence_id=None):
sentence_id = sentence_id or conn.sentence_id
# 跳过旧句子残留音频
if sentence_id is not None and sentence_id != conn.sentence_id:
if conn.client_abort or sentence_id != conn.sentence_id:
return
if conn.tts.tts_audio_first_sentence:
@ -34,13 +35,17 @@ async def sendAudioMessage(conn: "ConnectionHandler", sentenceType, audios, text
== conn.sentence_id
):
conn.audio_rate_controller.add_message(
lambda: send_tts_message(conn, "sentence_start", text)
lambda: send_tts_message(conn, "sentence_start", text, sentence_id)
)
else:
# 新句子或流控器未初始化,立即发送
await send_tts_message(conn, "sentence_start", text)
await send_tts_message(conn, "sentence_start", text, sentence_id)
if conn.client_abort or sentence_id != conn.sentence_id:
return
await sendAudio(conn, audios)
if conn.client_abort or sentence_id != conn.sentence_id:
return
# 发送句子开始消息
if sentenceType is not SentenceType.MIDDLE:
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}")
@ -48,7 +53,9 @@ async def sendAudioMessage(conn: "ConnectionHandler", sentenceType, audios, text
# 发送结束消息(如果是最后一个文本)
# 通话需要维持speaking状态
if not conn.calling and sentenceType == SentenceType.LAST:
await send_tts_message(conn, "stop", None)
await send_tts_message(conn, "stop", None, sentence_id)
if conn.client_abort or sentence_id != conn.sentence_id:
return
if conn.close_after_chat:
await conn.close()
@ -218,7 +225,7 @@ def _start_background_sender(conn: "ConnectionHandler", rate_controller, flow_co
async def send_callback(packet):
# 检查是否应该中止
if conn.client_abort:
if conn.client_abort or flow_control["sentence_id"] != conn.sentence_id:
raise asyncio.CancelledError("客户端已中止")
conn.last_activity_time = time.time() * 1000
@ -242,7 +249,7 @@ async def _send_audio_with_rate_control(
send_delay_ms: 自定义发送间隔(毫秒)。
"""
for packet in audio_list:
if conn.client_abort:
if conn.client_abort or flow_control["sentence_id"] != conn.sentence_id:
return
conn.last_activity_time = time.time() * 1000
@ -262,6 +269,8 @@ async def _do_send_audio(conn: "ConnectionHandler", opus_packet, flow_control):
"""
执行实际的音频发送
"""
if conn.client_abort or flow_control["sentence_id"] != conn.sentence_id:
return
packet_index = flow_control.get("packet_count", 0)
sequence = flow_control.get("sequence", 0)
@ -279,8 +288,10 @@ async def _do_send_audio(conn: "ConnectionHandler", opus_packet, flow_control):
flow_control["sequence"] = sequence + 1
async def send_tts_message(conn: "ConnectionHandler", state, text=None):
async def send_tts_message(conn: "ConnectionHandler", state, text=None, sentence_id=None):
"""发送 TTS 状态消息"""
if sentence_id is not None and (conn.client_abort or sentence_id != conn.sentence_id):
return
if text is None and state == "sentence_start":
return
message = {"type": "tts", "state": state, "session_id": conn.session_id}
@ -303,7 +314,7 @@ async def send_tts_message(conn: "ConnectionHandler", state, text=None):
await _wait_for_audio_completion(conn)
# 检查是否是当前轮次
if current_sentence_id != conn.sentence_id:
if current_sentence_id != conn.sentence_id or conn.client_abort:
return
# 停止音频发送循环(仅在流控器已初始化时调用)

View file

@ -26,6 +26,8 @@ THINKING_DISABLED_MODEL_EXCLUSIONS = {
class LLMProvider(LLMProviderBase):
supports_cancel_check = True
def __init__(self, config):
self.model_name = config.get("model_name")
# 可选实例级思考强度: off/disabled/none/disable | low/medium/high | 空/其他=按域名默认
@ -118,6 +120,9 @@ class LLMProvider(LLMProviderBase):
break
def response(self, session_id, dialogue, **kwargs):
cancel_check = kwargs.get("cancel_check", lambda: False)
if cancel_check():
return
dialogue = self.normalize_dialogue(dialogue)
request_params = {
@ -146,6 +151,8 @@ class LLMProvider(LLMProviderBase):
is_active = True
try:
for chunk in responses:
if cancel_check():
break
try:
delta = chunk.choices[0].delta if getattr(chunk, "choices", None) else None
content = getattr(delta, "content", "") if delta else ""
@ -164,6 +171,9 @@ class LLMProvider(LLMProviderBase):
responses.close()
def response_with_functions(self, session_id, dialogue, functions=None, **kwargs):
cancel_check = kwargs.get("cancel_check", lambda: False)
if cancel_check():
return
dialogue = self.normalize_dialogue(dialogue)
request_params = {
@ -191,6 +201,8 @@ class LLMProvider(LLMProviderBase):
try:
for chunk in stream:
if cancel_check():
break
if getattr(chunk, "choices", None):
delta = chunk.choices[0].delta
content = getattr(delta, "content", "")

View file

@ -119,6 +119,15 @@ class TTSProviderBase(ABC):
logger.bind(tag=TAG).debug(f"推送数据到队列里面帧数~~ {len(opus_data)}")
self.tts_audio_queue.put((SentenceType.MIDDLE, opus_data, None, getattr(self, 'current_sentence_id', None)))
def opus_handler_for_sentence(self, sentence_id):
"""捕获来源轮次,编码回调不得用共享 ID 给旧音频重新贴标签。"""
def handle(opus_data):
if self.conn.client_abort or sentence_id != self.conn.sentence_id:
return
self.tts_audio_queue.put((SentenceType.MIDDLE, opus_data, None, sentence_id))
return handle
def handle_audio_file(self, file_audio: bytes, text):
self.before_stop_play_files.append((file_audio, text))
@ -377,6 +386,7 @@ class TTSProviderBase(ABC):
# 过滤旧消息:检查sentence_id是否匹配
if message.sentence_id != self.conn.sentence_id:
continue
opus_handler = self.opus_handler_for_sentence(message.sentence_id)
if message.sentence_type == SentenceType.FIRST:
self.current_sentence_id = message.sentence_id
self.tts_stop_request = False
@ -388,16 +398,16 @@ class TTSProviderBase(ABC):
self.tts_text_buff.append(message.content_detail)
segment_text = self._get_segment_text()
if segment_text:
self.to_tts_stream(segment_text, opus_handler=self.handle_opus)
self.to_tts_stream(segment_text, opus_handler=opus_handler)
elif ContentType.FILE == message.content_type:
self._process_remaining_text_stream(opus_handler=self.handle_opus)
self._process_remaining_text_stream(opus_handler=opus_handler)
tts_file = message.content_file
if tts_file and os.path.exists(tts_file):
self._process_audio_file_stream(
tts_file, callback=self.handle_opus
tts_file, callback=opus_handler
)
if message.sentence_type == SentenceType.LAST:
self._process_remaining_text_stream(opus_handler=self.handle_opus)
self._process_remaining_text_stream(opus_handler=opus_handler)
self.tts_audio_queue.put(
(message.sentence_type, [], message.content_detail, message.sentence_id)
)
@ -434,6 +444,9 @@ class TTSProviderBase(ABC):
enqueue_text, enqueue_audio = None, []
continue
if sentence_id is not None and sentence_id != self.conn.sentence_id:
continue
# 收到下一个文本开始或会话结束时进行上报
if sentence_type is not SentenceType.MIDDLE:
if self.report_on_last:
@ -613,11 +626,16 @@ class TTSProviderBase(ABC):
):
os.remove(tts_file)
def _process_before_stop_play_files(self):
def _process_before_stop_play_files(self, sentence_id=None):
sentence_id = sentence_id or getattr(self, 'current_sentence_id', None)
if sentence_id is not None and (
self.conn.client_abort or sentence_id != self.conn.sentence_id
):
return
for audio_datas, text in self.before_stop_play_files:
self.tts_audio_queue.put((SentenceType.MIDDLE, audio_datas, text, getattr(self, 'current_sentence_id', None)))
self.tts_audio_queue.put((SentenceType.MIDDLE, audio_datas, text, sentence_id))
self.before_stop_play_files.clear()
self.tts_audio_queue.put((SentenceType.LAST, [], None, getattr(self, 'current_sentence_id', None)))
self.tts_audio_queue.put((SentenceType.LAST, [], None, sentence_id))
def _process_remaining_text_stream(
self, opus_handler: Callable[[bytes], None] = None

View file

@ -278,12 +278,16 @@ class TTSProvider(TTSProviderBase):
try:
message = self.tts_text_queue.get(timeout=1)
# 旧消息不能取消/结束已经开始的新会话。
if message.sentence_id != self.conn.sentence_id:
continue
if self.conn.client_abort:
try:
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
if self.enable_ws_reuse:
asyncio.run_coroutine_threadsafe(
self.cancel_session(self.conn.sentence_id),
self.cancel_session(message.sentence_id),
loop=self.conn.loop,
)
else:
@ -305,11 +309,6 @@ class TTSProvider(TTSProviderBase):
)
if message.sentence_type == SentenceType.FIRST:
# 重置流式处理状态
self.reset_stream_state()
# 重置 opus 流式编码器跨轮残留
if hasattr(self, "opus_encoder") and self.opus_encoder:
self.opus_encoder.reset_state()
# 初始化参数
try:
if not getattr(self.conn, "sentence_id", None):
@ -318,7 +317,7 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).debug("开始启动TTS会话...")
future = asyncio.run_coroutine_threadsafe(
self.start_session(self.conn.sentence_id),
self.start_session(message.sentence_id),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
@ -335,7 +334,7 @@ class TTSProvider(TTSProviderBase):
f"开始发送TTS文本: {message.content_detail}"
)
future = asyncio.run_coroutine_threadsafe(
self.text_to_speak(message.content_detail, None),
self.text_to_speak(message.content_detail, None, message.sentence_id),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
@ -354,7 +353,7 @@ class TTSProvider(TTSProviderBase):
try:
logger.bind(tag=TAG).debug("开始结束TTS会话...")
future = asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
self.finish_session(message.sentence_id),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
@ -370,8 +369,11 @@ class TTSProvider(TTSProviderBase):
)
continue
async def text_to_speak(self, text, _):
async def text_to_speak(self, text, _, sentence_id=None):
"""发送文本到TTS服务"""
sentence_id = sentence_id or getattr(self, "current_sentence_id", None)
if self.conn.client_abort or sentence_id != self.conn.sentence_id:
return
try:
# 建立新连接
if self.ws is None:
@ -388,7 +390,9 @@ class TTSProvider(TTSProviderBase):
# 发送每个确定的文本片段
for txt in confirmed_texts:
if txt and self.ws:
await self.send_text(self.voice, txt, self.conn.sentence_id)
if self.conn.client_abort or sentence_id != self.conn.sentence_id:
return
await self.send_text(self.voice, txt, sentence_id)
return
except Exception as e:
@ -402,17 +406,34 @@ class TTSProvider(TTSProviderBase):
raise
async def start_session(self, session_id):
if self.conn.client_abort or session_id != self.conn.sentence_id:
return
logger.bind(tag=TAG).debug(f"开始会话~~{session_id}")
try:
# 上个会话处于激活状态时关闭上个连接新建链接
if self.activate_session:
await self.close()
# 在事件循环中先等待旧接收任务退出,再复位共享编码器。
previous_sentence_id = getattr(self, "current_sentence_id", None)
await self._cancel_monitor_task(
keep_connection=self.enable_ws_reuse and not self.activate_session
)
if self.conn.client_abort or session_id != self.conn.sentence_id:
return
if previous_sentence_id and previous_sentence_id != session_id:
self.clear_tts_text(previous_sentence_id)
self.current_sentence_id = session_id
self.reset_stream_state()
if getattr(self, "opus_encoder", None):
self.opus_encoder.reset_state()
# 设置会话激活标志
self.activate_session = True
# 确保连接建立
await self._ensure_connection()
if self.conn.client_abort or session_id != self.conn.sentence_id:
return
# 复用连接时,旧接收任务也已经退出,需要启动新的监听任务。
if self._monitor_task is None or self._monitor_task.done():
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
header = Header(
message_type=FULL_CLIENT_REQUEST,
@ -434,12 +455,14 @@ class TTSProvider(TTSProviderBase):
raise
async def finish_session(self, session_id):
if self.conn.client_abort or session_id != self.conn.sentence_id:
return
logger.bind(tag=TAG).debug(f"关闭会话~~{session_id}")
try:
if self.ws:
# 句尾替换词滑动窗口残留先发出去
if self._pending_prefix:
await self.text_to_speak(self._pending_prefix, None)
await self.text_to_speak(self._pending_prefix, None, session_id)
header = Header(
message_type=FULL_CLIENT_REQUEST,
message_type_specific_flags=MsgTypeFlagWithEvent,
@ -459,6 +482,8 @@ class TTSProvider(TTSProviderBase):
raise
async def cancel_session(self,session_id):
if session_id != getattr(self, "current_sentence_id", None):
return
logger.bind(tag=TAG).debug(f"取消会话,释放服务端资源~~{session_id}")
try:
if self.ws:
@ -507,8 +532,10 @@ class TTSProvider(TTSProviderBase):
break
# 只处理当前活跃会话的响应;旧会话事件不影响当前 activate_session
if res.optional.sessionId and self.conn.sentence_id != res.optional.sessionId:
sentence_id = res.optional.sessionId or getattr(self, "current_sentence_id", None)
if self.conn.client_abort or sentence_id != self.conn.sentence_id:
continue
opus_handler = self.opus_handler_for_sentence(sentence_id)
if res.optional.event == EVENT_SessionCanceled:
logger.bind(tag=TAG).debug(f"释放服务端资源成功~~")
@ -524,23 +551,23 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).debug(f"句子语音生成开始: {self.tts_text}")
# 将TTS服务返回的替换后文本还原为原始文本,用于字幕显示
display_text = self._restore_original_text(self.tts_text)
self.tts_audio_queue.put((SentenceType.FIRST, [], display_text))
self.tts_audio_queue.put((SentenceType.FIRST, [], display_text, sentence_id))
elif (
res.optional.event == EVENT_TTSResponse
and res.header.message_type == AUDIO_ONLY_RESPONSE
):
# 处理seed-tts-2.0文本字幕
if self.resource_type:
tts_text = self.get_tts_text(self.conn.sentence_id)
tts_text = self.get_tts_text(sentence_id)
if tts_text:
logger.bind(tag=TAG).info(
f"句子语音生成成功: {tts_text}"
)
self.tts_audio_queue.put(
(SentenceType.FIRST, [], tts_text)
(SentenceType.FIRST, [], tts_text, sentence_id)
)
self.clear_tts_text(self.conn.sentence_id)
self.wav_to_opus_data_audio_raw_stream(res.payload, callback=self.handle_opus)
self.clear_tts_text(sentence_id)
self.wav_to_opus_data_audio_raw_stream(res.payload, callback=opus_handler)
elif not self.resource_type and res.optional.event == EVENT_TTSSentenceEnd:
logger.bind(tag=TAG).info(f"句子语音生成成功:{self.tts_text}")
elif res.optional.event == EVENT_SessionFinished:
@ -548,10 +575,12 @@ class TTSProvider(TTSProviderBase):
# 句尾冲刷流式 opus 编码器不足一帧的 PCM 残量
if hasattr(self, "opus_encoder") and self.opus_encoder:
self.wav_to_opus_data_audio_raw_stream(
b"", is_end=True, callback=self.handle_opus
b"", is_end=True, callback=opus_handler
)
self.activate_session = False
self._process_before_stop_play_files()
if self.conn.client_abort or sentence_id != self.conn.sentence_id:
continue
self._process_before_stop_play_files(sentence_id)
# 非复用模式下,会话结束后发送 FinishConnection
if not self.enable_ws_reuse:
await self.finish_connection()
@ -566,7 +595,7 @@ class TTSProvider(TTSProviderBase):
break
finally:
# 退出时关闭连接并清理引用
if self.ws:
if self.ws and not getattr(self, "_keep_connection_on_cancel", False):
try:
await self.ws.close()
except:
@ -739,8 +768,9 @@ class TTSProvider(TTSProviderBase):
def wav_to_opus_data_audio_raw_stream(self, raw_data_var, is_end=False, callback: Callable[[Any], Any]=None):
return self.opus_encoder.encode_pcm_to_opus_stream(raw_data_var, is_end, callback=callback)
async def _cancel_monitor_task(self):
async def _cancel_monitor_task(self, keep_connection=False):
"""取消监听任务"""
self._keep_connection_on_cancel = keep_connection
if self._monitor_task and not self._monitor_task.done():
self._monitor_task.cancel()
try:
@ -750,6 +780,7 @@ class TTSProvider(TTSProviderBase):
except Exception as e:
logger.bind(tag=TAG).warning(f"取消监听任务错误: {e}")
self._monitor_task = None
self._keep_connection_on_cancel = False
def to_tts(self, text: str) -> list:
"""非流式生成音频数据,用于生成音频及测试场景

View file

@ -1,18 +1,10 @@
"""回归测试:barge-in 打断后残留的 client_abort 会误断新一轮 LLM 流。
问题(issue #3437):上一轮 TTS 播放被用户打断(barge-in)后,设备发来的 abort
消息可能在新一轮 LLM 流建立之后才到达 ``core/handle/abortHandle.py``,那里会把
``conn.client_abort`` 置为 True。而 ``core/handle/receiveAudioHandle.py`` 里的
清理发生在 ``conn.executor.submit(conn.chat, ...)`` 之前,于是这个"针对上一轮"
的标志会残留到新一轮的流式循环里:``chat()`` 在首个分片处 ``if self.client_abort:
break``,新一轮回答只播第一句(或完全没有声音),服务端没有任何报错。
本文件用最小限度的假连接对象直接驱动 ``ConnectionHandler.chat()``:不加载任何模型、
不连网络、不碰音频设备,只验证"进入流式循环前清理残留标志"这一行为。
"""
"""确定时序的取消/换轮回归;驱动真实 chat,不连接模型或音频设备。"""
from __future__ import annotations
import queue
from types import SimpleNamespace
import pytest
from core.connection import ConnectionHandler
from core.utils.dialogue import Dialogue, Message
@ -87,12 +79,13 @@ def _sent_texts(conn):
return texts
def test_stale_abort_from_previous_turn_does_not_kill_new_answer():
"""上一轮残留的 client_abort 不应让新一轮回答只剩第一句。"""
def test_chat_does_not_clear_abort():
"""chat 无法判断 abort 归属,必须尊重取消;仅新轮入口清理。"""
conn = _make_conn(["第一句。", "第二句。"], stale_abort=True)
assert ConnectionHandler.chat(conn, "念一首诗") is True
assert _sent_texts(conn) == ["第一句。", "第二句。"]
assert conn.client_abort is True
assert _sent_texts(conn) == []
def test_abort_during_current_stream_still_interrupts():
@ -109,3 +102,152 @@ def test_no_abort_delivers_whole_answer():
assert ConnectionHandler.chat(conn, "数数") is True
assert _sent_texts(conn) == ["一", "二", "三"]
@pytest.mark.parametrize("replace_turn", [False, True])
def test_cancellation_before_first_chunk_closes_stream_without_history_or_last(replace_turn):
conn = _make_conn([])
closed = []
def response(*args, **kwargs):
try:
if replace_turn:
conn.sentence_id = "new-turn"
else:
conn.client_abort = True
yield "不能播报"
finally:
closed.append(True)
conn.llm.response = response
assert conn.chat("旧问题") is True
assert closed == [True]
items = list(conn.tts.tts_text_queue.queue)
assert len(items) == 1 # 只有生成前的 FIRST,没有 TEXT/LAST
assert not conn.tts.stored_text
assert all(m["role"] != "assistant" for m in conn.dialogue.get_llm_dialogue())
def test_cancel_during_memory_wait_is_preserved(monkeypatch):
conn = _make_conn(["不能复活"])
conn.memory = SimpleNamespace(query_memory=lambda query: None)
conn.loop = None
def result():
conn.client_abort = True
return "memory"
monkeypatch.setattr("core.connection.asyncio.run_coroutine_threadsafe",
lambda *args: SimpleNamespace(result=result))
assert conn.chat("问题") is True
assert conn.client_abort is True
assert _sent_texts(conn) == []
def test_delayed_old_worker_cannot_claim_new_turn():
conn = _make_conn(["新回答"])
conn.sentence_id = "new-turn"
assert conn.chat("旧问题", current_sentence_id="old-turn") is True
assert conn.sentence_id == "new-turn"
assert conn.tts.tts_text_queue.empty()
assert conn.chat("新问题", current_sentence_id="new-turn") is True
assert _sent_texts(conn) == ["新回答"]
def test_old_worker_cannot_clear_new_turn_abort():
conn = _make_conn(["不能复活"], stale_abort=True)
conn.sentence_id = "new-turn"
assert conn.chat("旧问题", current_sentence_id="old-turn") is True
assert conn.client_abort is True
assert conn.sentence_id == "new-turn"
assert conn.tts.tts_text_queue.empty()
def test_audio_entry_assigns_turn_before_submitting_worker(monkeypatch):
import asyncio
from unittest.mock import AsyncMock, Mock
from core.handle import receiveAudioHandle
conn = _make_conn(["新回答"], stale_abort=True)
conn.need_bind = False
conn.max_output_size = 0
conn.client_is_speaking = False
conn.executor = SimpleNamespace(submit=Mock())
monkeypatch.setattr(receiveAudioHandle, "handle_user_intent", AsyncMock(return_value=False))
monkeypatch.setattr(receiveAudioHandle, "send_stt_message", AsyncMock())
asyncio.run(receiveAudioHandle.startToChat(conn, "新问题"))
args, kwargs = conn.executor.submit.call_args
assert kwargs["current_sentence_id"] == conn.sentence_id
assert conn.client_abort is False
args[0](args[1], **kwargs)
assert _sent_texts(conn) == ["新回答"]
def test_recursive_chat_keeps_original_turn():
conn = _make_conn(["不能回答"])
conn.sentence_id = "new-turn"
assert conn.chat(None, depth=1, current_sentence_id="old-turn") is True
assert conn.sentence_id == "new-turn"
assert conn.tts.tts_text_queue.empty()
def test_tool_continuation_passes_original_turn():
from plugins_func.register import Action, ActionResponse
conn = _make_conn([])
conn.sentence_id = "original-turn"
calls = []
conn.chat = lambda *args, **kwargs: calls.append((args, kwargs))
conn._handle_function_result(
[(ActionResponse(action=Action.REQLLM, result="tool result"),
{"id": "tool-id", "name": "tool", "arguments": "{}"})],
depth=0, current_sentence_id="original-turn",
)
assert calls == [((None,), {"depth": 1, "current_sentence_id": "original-turn"})]
def test_stale_stream_error_is_silent():
conn = _make_conn([])
def response(*args, **kwargs):
conn.sentence_id = "new-turn"
raise RuntimeError("old stream failed")
yield
conn.llm.response = response
assert conn.chat("旧问题") is True
assert len(list(conn.tts.tts_text_queue.queue)) == 1
assert _sent_texts(conn) == []
def test_cancelled_tool_call_is_not_dispatched():
conn = _make_conn([])
conn.intent_type = "function_call"
conn.func_handler = SimpleNamespace(get_functions=lambda: [])
def response(*args, **kwargs):
yield '<tool_call>{"name":"dangerous","arguments":{}}', None
conn.client_abort = True
yield "", None
conn.llm.response_with_functions = response
assert conn.chat("调用工具") is True
assert not conn.tts.stored_text
def test_cancel_callback_can_end_stream_without_yielding():
conn = _make_conn([])
conn.llm.supports_cancel_check = True
closed = []
def response(*args, cancel_check):
conn.sentence_id = "new-turn"
assert cancel_check()
closed.append(True)
return
yield
conn.llm.response = response
assert conn.chat("旧问题") is True
assert closed == [True]
assert len(list(conn.tts.tts_text_queue.queue)) == 1

View file

@ -0,0 +1,145 @@
"""Exercise real provider callbacks with deterministic turn changes, without network/audio."""
import asyncio
import queue
import threading
from types import SimpleNamespace
from unittest.mock import Mock, AsyncMock
import pytest
from core.providers.tts import huoshan_double_stream as huoshan
from core.providers.tts.dto.dto import SentenceType
from core.providers.llm.openai.openai import LLMProvider
from core.handle.sendAudioHandle import sendAudioMessage, _start_background_sender
@pytest.mark.parametrize("resource_type", [False, True])
@pytest.mark.parametrize("switch_turn", [False, True])
def test_huoshan_encoding_callback_keeps_original_turn(resource_type, switch_turn):
provider = huoshan.TTSProvider.__new__(huoshan.TTSProvider)
conn = SimpleNamespace(sentence_id="A", client_abort=False, stop_event=threading.Event())
provider.conn = conn
provider.current_sentence_id = "A"
provider.tts_audio_queue = queue.Queue()
provider.resource_type = resource_type
provider._sentence_text_map = {"A": "old subtitle", "B": "new subtitle"}
provider.print_response = Mock()
provider.ws = SimpleNamespace(recv=AsyncMock(return_value=b"pcm"), close=AsyncMock())
provider.parser_response = lambda msg: SimpleNamespace(
optional=SimpleNamespace(event=huoshan.EVENT_TTSResponse, sessionId="A"),
header=SimpleNamespace(message_type=huoshan.AUDIO_ONLY_RESPONSE), payload=b"pcm",
)
def encode(data, callback):
if switch_turn:
conn.sentence_id = "B"
provider.current_sentence_id = "B"
callback(b"opus")
conn.stop_event.set()
provider.wav_to_opus_data_audio_raw_stream = encode
asyncio.run(provider._start_monitor_tts_response())
items = list(provider.tts_audio_queue.queue)
audio = [item for item in items if item[0] == SentenceType.MIDDLE]
assert audio == ([] if switch_turn else [(SentenceType.MIDDLE, b"opus", None, "A")])
assert all(len(item) == 4 and item[3] == "A" for item in items)
assert provider._sentence_text_map["B"] == "new subtitle"
def test_huoshan_waits_for_receiver_before_resetting_encoder():
provider = huoshan.TTSProvider.__new__(huoshan.TTSProvider)
provider.conn = SimpleNamespace(sentence_id="B", client_abort=False)
provider.current_sentence_id = "A"
provider._sentence_text_map = {"A": "old", "B": "new"}
provider.enable_ws_reuse = True
provider.activate_session = False
provider._monitor_task = None
order = []
async def cancel(**kwargs):
order.append("receiver stopped")
provider._cancel_monitor_task = cancel
provider.reset_stream_state = lambda: order.append("stream reset")
provider.opus_encoder = SimpleNamespace(reset_state=lambda: order.append("encoder reset"))
provider._ensure_connection = AsyncMock()
provider.ws = object()
provider.voice = "voice"
provider.get_payload_bytes = Mock(return_value=b"{}")
provider.send_event = AsyncMock()
asyncio.run(provider.start_session("B"))
assert order == ["receiver stopped", "stream reset", "encoder reset"]
assert provider.current_sentence_id == "B"
assert provider._sentence_text_map == {"B": "new"}
def test_stale_audio_and_last_do_not_send_or_close_new_turn():
conn = SimpleNamespace(sentence_id="B", client_abort=False, close=AsyncMock())
for kind in (SentenceType.FIRST, SentenceType.MIDDLE, SentenceType.LAST):
asyncio.run(sendAudioMessage(conn, kind, b"opus", "old", "A"))
conn.close.assert_not_awaited()
def test_background_sender_checks_turn_again_at_send_time():
conn = SimpleNamespace(sentence_id="B", client_abort=False)
controller = Mock()
_start_background_sender(conn, controller, {"sentence_id": "A"})
callback = controller.start_sending.call_args.args[0]
with pytest.raises(asyncio.CancelledError):
asyncio.run(callback(b"old opus"))
@pytest.mark.parametrize("reuse", [False, True])
def test_huoshan_receiver_cancellation_respects_connection_reuse(reuse):
async def scenario():
provider = huoshan.TTSProvider.__new__(huoshan.TTSProvider)
provider.conn = SimpleNamespace(stop_event=threading.Event())
waiting = asyncio.Event()
async def recv():
waiting.set()
await asyncio.Future()
ws = SimpleNamespace(recv=recv, close=AsyncMock())
provider.ws = ws
provider._monitor_task = asyncio.create_task(provider._start_monitor_tts_response())
await waiting.wait()
await provider._cancel_monitor_task(keep_connection=reuse)
assert provider._monitor_task is None
if reuse:
assert provider.ws is ws
ws.close.assert_not_awaited()
else:
assert provider.ws is None
ws.close.assert_awaited_once()
asyncio.run(scenario())
@pytest.mark.parametrize("functions", [False, True])
def test_openai_closes_http_stream_when_cancelled(functions):
provider = LLMProvider.__new__(LLMProvider)
provider.normalize_dialogue = lambda dialogue: dialogue
provider.model_name = "fake"
for attr in ("max_tokens", "temperature", "top_p", "frequency_penalty"):
setattr(provider, attr, None)
provider._apply_thinking_disabled = lambda params: None
cancelled = False
def chunks():
nonlocal cancelled
# Empty/think chunks must also check cancellation at the HTTP layer.
cancelled = True
yield SimpleNamespace(choices=[])
pytest.fail("provider continued consuming cancelled stream")
stream = Mock()
stream.__iter__ = Mock(return_value=chunks())
create = Mock(return_value=stream)
provider.client = SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=create)))
response = provider.response_with_functions if functions else provider.response
assert list(response("session", [], cancel_check=lambda: cancelled)) == []
stream.close.assert_called_once()
create.reset_mock()
assert list(response("session", [], cancel_check=lambda: True)) == []
create.assert_not_called()