merge: sync upstream main 2026-10-13 (16 commits)

# Conflicts:
#	Dockerfile-server-base
#	main/manager-web/src/router/index.js
#	main/xiaozhi-server/config/manage_api_client.py
#	main/xiaozhi-server/core/handle/receiveAudioHandle.py
This commit is contained in:
lapy 2026-10-13 11:48:47 +01:00
commit a80ff5084b
6 changed files with 455 additions and 170 deletions

View file

@ -3,4 +3,40 @@ updates:
- package-ecosystem: pip - package-ecosystem: pip
directory: /main/xiaozhi-server directory: /main/xiaozhi-server
schedule: schedule:
interval: weekly interval: monthly
open-pull-requests-limit: 5
groups:
ai-services:
patterns:
- "openai*"
- "google-generativeai"
- "dashscope"
- "baidu-aip"
- "cozepy"
- "markitdown"
- "mem0ai"
- "powermem"
ai-models:
patterns:
- "funasr"
- "vosk"
- "silero_vad"
- "opuslib_next"
- "sherpa_onnx"
- "modelscope"
web-stack:
patterns:
- "httpx"
- "aiohttp"
- "aiohttp_cors"
- "requests"
- "pysocks"
everything-else:
patterns:
- "*"
ignore:
- dependency-name: "torch"
- dependency-name: "torchaudio"
- dependency-name: "numpy"
- dependency-name: "portalocker"
- dependency-name: "websockets"

View file

@ -81,10 +81,6 @@ const routes = [
name: 'ParamsManagement', name: 'ParamsManagement',
component: function () { component: function () {
return import('../views/ParamsManagement.vue') return import('../views/ParamsManagement.vue')
},
meta: {
requiresAuth: true,
title: 'Parameter Management'
} }
}, },
{ {
@ -92,22 +88,13 @@ const routes = [
name: 'KnowledgeBaseManagement', name: 'KnowledgeBaseManagement',
component: function () { component: function () {
return import('../views/KnowledgeBaseManagement.vue') return import('../views/KnowledgeBaseManagement.vue')
},
meta: {
requiresAuth: true,
title: 'Knowledge Base'
} }
}, },
{ {
path: '/server-side-management', path: '/server-side-management',
name: 'ServerSideManager', name: 'ServerSideManager',
component: function () { component: function () {
return import('../views/ServerSideManager.vue') return import('../views/ServerSideManager.vue')
},
meta: {
requiresAuth: true,
title: 'Server Management'
} }
}, },
{ {
@ -115,10 +102,6 @@ const routes = [
name: 'OtaManagement', name: 'OtaManagement',
component: function () { component: function () {
return import('../views/OtaManagement.vue') return import('../views/OtaManagement.vue')
},
meta: {
requiresAuth: true,
title: 'OTA Management'
} }
}, },
{ {
@ -126,10 +109,6 @@ const routes = [
name: 'VoiceResourceManagement', name: 'VoiceResourceManagement',
component: function () { component: function () {
return import('../views/VoiceResourceManagement.vue') return import('../views/VoiceResourceManagement.vue')
},
meta: {
requiresAuth: true,
title: 'Voice Resource'
} }
}, },
{ {
@ -137,10 +116,6 @@ const routes = [
name: 'VoiceCloneManagement', name: 'VoiceCloneManagement',
component: function () { component: function () {
return import('../views/VoiceCloneManagement.vue') return import('../views/VoiceCloneManagement.vue')
},
meta: {
requiresAuth: true,
title: 'Voice Clone'
} }
}, },
{ {
@ -165,7 +140,7 @@ const routes = [
return import('../views/AgentTemplateManagement.vue') return import('../views/AgentTemplateManagement.vue')
} }
}, },
// Add template quick config route // Add template quick-config route
{ {
path: '/template-quick-config', path: '/template-quick-config',
name: 'TemplateQuickConfig', name: 'TemplateQuickConfig',
@ -173,16 +148,12 @@ const routes = [
return import('../views/TemplateQuickConfig.vue') return import('../views/TemplateQuickConfig.vue')
} }
}, },
// Function config page route // Feature configuration page route
{ {
path: '/feature-management', path: '/feature-management',
name: 'FeatureManagement', name: 'FeatureManagement',
component: function () { component: function () {
return import('../views/FeatureManagement.vue') return import('../views/FeatureManagement.vue')
},
meta: {
requiresAuth: true,
title: 'Feature Configuration'
} }
}, },
// Replacement word management // Replacement word management
@ -191,22 +162,14 @@ const routes = [
name: 'ReplacementWordManagement', name: 'ReplacementWordManagement',
component: function () { component: function () {
return import('../views/ReplacementWordManagement.vue') return import('../views/ReplacementWordManagement.vue')
},
meta: {
requiresAuth: true,
title: 'Replacement Word Management'
} }
}, },
// Contacts management page route // Address book management page route
{ {
path: '/address-book-management', path: '/address-book-management',
name: 'AddressBookManagement', name: 'AddressBookManagement',
component: function () { component: function () {
return import('../views/AddressBookManagement.vue') return import('../views/AddressBookManagement.vue')
},
meta: {
requiresAuth: true,
title: 'Address Book Management'
} }
}, },
] ]
@ -215,12 +178,12 @@ const router = new VueRouter({
routes routes
}) })
// Globally handle duplicate navigation by refreshing the page // Handle duplicate navigation globally by refreshing the page
const originalPush = VueRouter.prototype.push const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) { VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => { return originalPush.call(this, location).catch(err => {
if (err.name === 'NavigationDuplicated') { if (err.name === 'NavigationDuplicated') {
// If duplicate navigation, refresh page // If duplicate navigation, refresh the page
window.location.reload() window.location.reload()
} else { } else {
// Throw other errors normally // Throw other errors normally
@ -229,21 +192,27 @@ VueRouter.prototype.push = function push(location) {
}) })
} }
// Routes requiring login // Whitelist of routes accessible without login
const protectedRoutes = ['home', 'RoleConfig', 'DeviceManagement', 'UserManagement', 'ModelConfig', 'KnowledgeBaseManagement', 'KnowledgeFileUpload', 'AddressBookManagement'] const anonRouteNames = new Set(['login', 'Register', 'RetrievePassword', 'welcome'])
// Route Guard // Route guard
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
// Check if the route requires protection const token = localStorage.getItem('token');
if (protectedRoutes.includes(to.name)) { const isAnonRoute = anonRouteNames.has(to.name);
// Get token from localStorage
const token = localStorage.getItem('token') if (isAnonRoute && token) {
if (!token) { next({ name: 'home', replace: true })
// Not logged in, redirecting to login page return
next({ name: 'login', query: { redirect: to.fullPath } })
return
}
} }
if (!isAnonRoute && !token) {
next({
name: 'login',
replace: true
})
return
}
next() next()
}) })

View file

@ -1,13 +1,18 @@
import os import os
import base64 import base64
import asyncio
import functools import functools
import threading import threading
import traceback
from typing import Optional, Dict from typing import Optional, Dict
import httpx import httpx
TAG = __name__ TAG = __name__
# _retry_wait slice granularity: after safe_close we finish within ~100ms; polling overhead is negligible
_RETRY_WAIT_SLICE = 0.1
class DeviceNotFoundException(Exception): class DeviceNotFoundException(Exception):
pass pass
@ -16,18 +21,21 @@ class DeviceNotFoundException(Exception):
class DeviceBindException(Exception): class DeviceBindException(Exception):
def __init__(self, bind_code): def __init__(self, bind_code):
self.bind_code = bind_code self.bind_code = bind_code
super().__init__(f"Device bind error, bind code: {bind_code}") super().__init__(f"Device binding exception, Binding code: {bind_code}")
class ManageApiShutdownError(Exception):
"""Terminal error raised when safe_close interrupts a retry wait; __cause__ keeps the last failure reason."""
class ManageApiClient: class ManageApiClient:
_instance = None _instance = None
_instance_lock = threading.Lock() _instance_lock = threading.Lock() # guards reads/writes of _instance and _closed
_async_clients = {} # One client per event loop
_secret = None _secret = None
_closed = False # Set to True after safe_close(); no new connections will be created after closure. _closed = False # set to True by safe_close(); no new connections are created after closing
def __new__(cls, config): def __new__(cls, config):
"""Singleton ensures a single global instance and supports config injection.""" """Singleton pattern ensures a globally unique instance and supports passing config parameters."""
with cls._instance_lock: with cls._instance_lock:
if cls._instance is None: if cls._instance is None:
cls._instance = super().__new__(cls) cls._instance = super().__new__(cls)
@ -36,93 +44,97 @@ class ManageApiClient:
@classmethod @classmethod
def _init_client(cls, config): def _init_client(cls, config):
"""Initialize configuration (client creation is deferred).""" """Initialize configuration (lazy client creation)"""
cls.config = config.get("manager-api") cls.config = config.get("manager-api")
if not cls.config: if not cls.config:
raise Exception("manager-api configuration is missing") raise Exception("manager-api configuration error")
if not cls.config.get("url") or not cls.config.get("secret"): if not cls.config.get("url") or not cls.config.get("secret"):
raise Exception("manager-api url or secret is invalid") raise Exception("manager-api url or secret configuration error")
if "your_" in cls.config.get("secret", "").lower(): if "your_" in cls.config.get("secret", "").lower():
raise Exception("Please configure manager-api secret first") raise Exception("Please configure the manager-api secret first")
cls._secret = cls.config.get("secret") cls._secret = cls.config.get("secret")
cls.max_retries = cls.config.get("max_retries", 6) # Max retries cls.max_retries = cls.config.get("max_retries", 6) # Maximum retry count
cls.retry_delay = cls.config.get("retry_delay", 10) # Initial retry delay (seconds) cls.retry_delay = cls.config.get("retry_delay", 10) # Initial retry delay(seconds)
# Defer AsyncClient creation until first use # Do not create the AsyncClient here; defer creation until actually used
cls._async_clients = {}
cls._closed = False cls._closed = False
@classmethod @classmethod
async def _ensure_async_client(cls): def _build_client(cls) -> httpx.AsyncClient:
"""Ensure async client exists (one per event loop).""" """Build the AsyncClient dedicated to one business request (including its retries).
import asyncio
try: Constraint: the caller closes it via ``async with`` inside the same loop; caching across requests is prohibited; construction happens outside the lock so concurrent requests do not block the event loop.
loop = asyncio.get_running_loop() """
loop_id = id(loop) with cls._instance_lock:
if cls._closed:
with cls._instance_lock: raise Exception("ManageApiClient is closed; no new HTTP client is created")
if cls._closed: base_url = cls.config.get("url")
raise Exception("ManageApiClient is closed; no new HTTP client can be created") secret = cls._secret
if loop_id not in cls._async_clients: timeout = cls.config.get("timeout", 30)
limits = httpx.Limits(max_keepalive_connections=0) return httpx.AsyncClient(
cls._async_clients[loop_id] = httpx.AsyncClient( base_url=base_url,
base_url=cls.config.get("url"), headers={
headers={ "User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})",
"User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})", "Accept": "application/json",
"Accept": "application/json", "Authorization": "Bearer " + secret,
"Authorization": "Bearer " + cls._secret, },
}, timeout=timeout,
timeout=cls.config.get("timeout", 30), # Connection reuse is limited to this request; keepalive_expiry dynamically covers retry_delay,
limits=limits, # preventing pooled connections from expiring during retry waits.
trust_env=False, limits=httpx.Limits(
) max_keepalive_connections=1,
return cls._async_clients[loop_id] keepalive_expiry=max(30, cls.retry_delay + 5),
except RuntimeError: ),
# No running loop trust_env=False,
raise Exception("Must be called from an async context") # verify=True builds the TLS context on demand: httpcore mutates the passed-in
# context in place (unlocked), so a shared singleton would race on concurrent handshakes.
verify=True,
)
@classmethod @classmethod
async def _async_request(cls, method: str, endpoint: str, **kwargs) -> Dict: async def _async_request(
"""Send a single async HTTP request and process the response.""" cls, client: httpx.AsyncClient, method: str, endpoint: str, **kwargs
# Ensure client exists ) -> Dict:
client = await cls._ensure_async_client() """Execute a single request on the given client; release back to the connection pool immediately after reading the response."""
endpoint = endpoint.lstrip("/") endpoint = endpoint.lstrip("/")
response = None response = None
try: try:
response = await client.request(method, endpoint, **kwargs) response = await client.request(method, endpoint, **kwargs)
response.raise_for_status() response.raise_for_status()
result = response.json() result = response.json()
# Handle API business errors
if result.get("code") == 10041: if result.get("code") == 10041:
raise DeviceNotFoundException(result.get("msg")) raise DeviceNotFoundException(result.get("msg"))
elif result.get("code") == 10042: elif result.get("code") == 10042:
raise DeviceBindException(result.get("msg")) raise DeviceBindException(result.get("msg"))
elif result.get("code") != 0: elif result.get("code") != 0:
raise Exception(f"API error: {result.get('msg', 'Unknown error')}") raise Exception(f"API returned an error: {result.get('msg', 'Unknown error')}")
return result.get("data")
# Return success data
return result.get("data") if result.get("code") == 0 else None
finally: finally:
# Ensure response is closed (even on exceptions)
if response is not None: if response is not None:
await response.aclose() try:
await response.aclose()
except Exception:
# Constraint: release errors must be swallowed so they do not mask business exceptions or break retry logic
pass
@classmethod @classmethod
def _should_retry(cls, exception: Exception) -> bool: def _should_retry(cls, exception: Exception) -> bool:
"""Determine whether an exception should trigger retry.""" """Determine if exception should be retried"""
# Network-related errors # Network-related errors
if isinstance( if isinstance(
exception, (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError) exception, (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError)
): ):
return True return True
# HTTP status errors # RemoteProtocolError: only retry the "without sending a response" variant (request not
# sent, safe). Truncated variants may have been processed already; do not retry.
if isinstance(exception, httpx.RemoteProtocolError):
return "without sending a response" in str(exception)
# HTTP status code error
if isinstance(exception, httpx.HTTPStatusError): if isinstance(exception, httpx.HTTPStatusError):
status_code = exception.response.status_code status_code = exception.response.status_code
return status_code in [408, 429, 500, 502, 503, 504] return status_code in [408, 429, 500, 502, 503, 504]
@ -130,93 +142,121 @@ class ManageApiClient:
return False return False
@classmethod @classmethod
async def _execute_async_request(cls, method: str, endpoint: str, **kwargs) -> Dict: async def _retry_wait(cls):
"""Async request executor with retries.""" """Retry wait interruptible by safe_close() (polls _closed every _RETRY_WAIT_SLICE seconds).
import asyncio
retry_count = 0 Constraint: never sleep the full retry_delay in one shot, otherwise shutdown would
wait out the entire retry cycle.
while retry_count <= cls.max_retries: """
try: remaining = cls.retry_delay
# Execute request while remaining > 0 and not cls._closed:
return await cls._async_request(method, endpoint, **kwargs) step = min(_RETRY_WAIT_SLICE, remaining)
except Exception as e: await asyncio.sleep(step)
# Decide whether to retry remaining -= step
if retry_count < cls.max_retries and cls._should_retry(e):
retry_count += 1
print(
f"{method} {endpoint} async request failed. Retrying in {cls.retry_delay:.1f}s (attempt {retry_count})"
)
await asyncio.sleep(cls.retry_delay)
continue
else:
# No retry; re-raise
raise
@classmethod @classmethod
def _get_instance(cls): async def _execute_async_request(cls, method: str, endpoint: str, **kwargs) -> Dict:
"""Thread-safely get singleton instance reference """Business request executor with a retry mechanism.
Callers should use the returned local reference instead of re-reading after null check Constraint: the client is built once for the whole retry sequence and closed via
ManageApiClient._instance: even if safe_close() subsequently sets _instance ``async with``; safe_close does not cancel an in-flight attempt, it only interrupts
Set to None; the acquired reference still points to the original object, eliminating the "null check after, the retry wait (raising ManageApiShutdownError).
Use TOCTOU race window where previous instance was nullified """
client = cls._build_client()
async with client:
retry_count = 0
while retry_count <= cls.max_retries:
try:
# Execute asynchronous request
return await cls._async_request(client, method, endpoint, **kwargs)
except Exception as e:
# Determine if retry is needed
if retry_count < cls.max_retries and cls._should_retry(e):
retry_count += 1
print(
f"{method} {endpoint} async request failed. Retrying in {cls.retry_delay:.1f}s (attempt {retry_count})"
)
await cls._retry_wait()
if cls._closed:
# The terminal state must stay distinguishable: a bare raise would disguise the
# shutdown early-exit as network jitter and mask the offline signal
raise ManageApiShutdownError(
f"safe_close interrupted the retry wait: {e}") from e
continue
else:
# Do not retry, Throw exception directly
raise
@classmethod
def _get_instance(cls) -> Optional["ManageApiClient"]:
"""Thread-safely obtain a reference to the singleton instance.
Constraint: callers keep the returned local reference; never re-read _instance after a null check (TOCTOU window).
""" """
with cls._instance_lock: with cls._instance_lock:
return cls._instance return cls._instance
@classmethod @classmethod
def safe_close(cls): def safe_close(cls):
"""Safely close all async connection pools.""" """Close entry point; in-flight requests release their clients inside their own event loops.
import asyncio
Already-started requests are not cancelled; pending retry waits are interrupted,
skipping the remaining retries (see _retry_wait).
"""
with cls._instance_lock: with cls._instance_lock:
cls._closed = True cls._closed = True
clients = list(cls._async_clients.values())
cls._async_clients.clear()
cls._instance = None cls._instance = None
for client in clients:
try:
asyncio.run(client.aclose())
except Exception:
pass
def api_guard(error_msg: str = None, raise_when_closed: bool = False): def api_guard(error_msg: str = None, raise_when_closed: bool = False):
"""Inject a stable client instance and avoid shutdown races for API calls.""" """Decorator: uniform singleton lookup, null check and exception fallback.
- Fetches the instance once via _get_instance() and injects it as the decorated
function's first parameter, eliminating the TOCTOU race against safe_close();
- If the instance is uninitialized or closed: raise an explicit exception when
raise_when_closed=True (startup paths), otherwise return None silently (daemon threads);
- When error_msg is set, request exceptions are caught, logged and None is returned;
when it is None, exceptions propagate to the caller.
"""
def decorator(func): def decorator(func):
@functools.wraps(func) @functools.wraps(func)
async def wrapper(*args, **kwargs): async def wrapper(*args, **kwargs):
instance = ManageApiClient._get_instance() instance = ManageApiClient._get_instance()
if instance is None: if instance is None:
if raise_when_closed: if raise_when_closed:
raise Exception("ManageApiClient is not initialized or has been closed") raise Exception("ManageApiClient is uninitialized or closed")
return None return None
if error_msg is None: if error_msg is None:
return await func(instance, *args, **kwargs) return await func(instance, *args, **kwargs)
try: try:
return await func(instance, *args, **kwargs) return await func(instance, *args, **kwargs)
except Exception as exc: except Exception as e:
print(f"{error_msg}: {exc}") # Constraint: log the full stack trace for httpx/ValueError parsing failures (the
# message alone hides context); keep other paths to a one-line log
if isinstance(e, (httpx.HTTPError, ValueError)):
print(f"{error_msg}: {e}\n{traceback.format_exc()}")
else:
print(f"{error_msg}: {e}")
return None return None
return wrapper return wrapper
return decorator return decorator
@api_guard(raise_when_closed=True) @api_guard(raise_when_closed=True)
async def get_server_config(instance) -> Optional[Dict]: async def get_server_config(instance) -> Optional[Dict]:
"""Fetch server base config.""" """Get server base configuration"""
return await instance._execute_async_request( return await instance._execute_async_request("POST", "/config/server-base")
"POST", "/config/server-base"
)
@api_guard(raise_when_closed=True) @api_guard(raise_when_closed=True)
async def get_agent_models( async def get_agent_models(
instance, mac_address: str, client_id: str, selected_module: Dict instance, mac_address: str, client_id: str, selected_module: Dict
) -> Optional[Dict]: ) -> Optional[Dict]:
"""Fetch agent model config.""" """Get agent model configuration"""
return await instance._execute_async_request( return await instance._execute_async_request(
"POST", "POST",
"/config/agent-models", "/config/agent-models",
@ -228,9 +268,9 @@ async def get_agent_models(
) )
@api_guard("Failed to get correction words") @api_guard("Failed to get replacement words")
async def get_correct_words(instance, mac_address: str) -> Optional[Dict]: async def get_correct_words(instance, mac_address: str) -> Optional[Dict]:
"""Fetch agent correction words.""" """Get agent replacement words"""
return await instance._execute_async_request( return await instance._execute_async_request(
"POST", "/config/correct-words", "POST", "/config/correct-words",
json={"macAddress": mac_address} json={"macAddress": mac_address}
@ -239,26 +279,32 @@ async def get_correct_words(instance, mac_address: str) -> Optional[Dict]:
@api_guard("Failed to generate and save chat summary") @api_guard("Failed to generate and save chat summary")
async def generate_and_save_chat_summary(instance, session_id: str) -> Optional[Dict]: async def generate_and_save_chat_summary(instance, session_id: str) -> Optional[Dict]:
"""Generate and save chat summary.""" """Generate and save chat summary (daemon thread; returns None silently when the service is closing)."""
return await instance._execute_async_request("POST", f"/agent/chat-summary/{session_id}/save") return await instance._execute_async_request(
"POST",
f"/agent/chat-summary/{session_id}/save",
)
@api_guard("Failed to generate and save chat title") @api_guard("Failed to generate and save chat title")
async def generate_and_save_chat_title(instance, session_id: str) -> Optional[Dict]: async def generate_and_save_chat_title(instance, session_id: str) -> Optional[Dict]:
"""Generate and save a chat title.""" """Generate and save chat title (daemon thread; returns None silently when the service is closing)."""
return await instance._execute_async_request("POST", f"/agent/chat-title/{session_id}/generate") return await instance._execute_async_request(
"POST",
f"/agent/chat-title/{session_id}/generate",
)
@api_guard("TTS report failed") @api_guard("TTS report failed")
async def report( async def report(
instance, mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time instance, mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time
) -> Optional[Dict]: ) -> Optional[Dict]:
"""Async chat history report.""" """Report chat history asynchronously"""
if not content: if not content:
return None return None
return await instance._execute_async_request( return await instance._execute_async_request(
"POST", "POST",
f"/agent/chat-history/report", "/agent/chat-history/report",
json={ json={
"macAddress": mac_address, "macAddress": mac_address,
"sessionId": session_id, "sessionId": session_id,
@ -272,9 +318,9 @@ async def report(
) )
@api_guard("Address-book lookup failed") @api_guard("Contact lookup failed")
async def lookup_address_book(instance, caller_mac: str, nickname: str) -> Optional[Dict]: async def lookup_address_book(instance, caller_mac: str, nickname: str) -> Optional[Dict]:
"""Look up a target device by nickname.""" """Look up the target device by nickname"""
return await instance._execute_async_request( return await instance._execute_async_request(
"GET", "GET",
f"/device/address-book/lookup?callerMac={caller_mac}&nickname={nickname}", f"/device/address-book/lookup?callerMac={caller_mac}&nickname={nickname}",

View file

@ -55,14 +55,25 @@ async def startToChat(conn: "ConnectionHandler", text):
data = json.loads(text) data = json.loads(text)
if "speaker" in data and "content" in data: if "speaker" in data and "content" in data:
speaker_name = data["speaker"] speaker_name = data["speaker"]
language_tag = data["language"] actual_content = data["content"]
actual_text = data["content"]
conn.logger.bind(tag=TAG).info( conn.logger.bind(tag=TAG).info(
f"Parsed speaker information: {speaker_name}" f"Parsed speaker information: {speaker_name}"
) )
# Keep the original JSON payload for downstream use. # Keep the {"speaker":...} JSON only on the speaker's first
actual_text = text # appearance so the model greets them naturally once; later
# turns degrade to plain text so the recurring name does not
# push the model to keep addressing them every turn.
if speaker_name not in conn.introduced_speakers:
conn.introduced_speakers.add(speaker_name)
actual_text = text
else:
actual_text = actual_content
elif "content" in data:
# FunASR-style payloads return {"content","language","emotion"}:
# hand only the recognized text to the LLM, otherwise the raw
# JSON would enter the conversation history.
actual_text = data["content"]
except (json.JSONDecodeError, KeyError): except (json.JSONDecodeError, KeyError):
# Fall back to the original text if parsing fails. # Fall back to the original text if parsing fails.
pass pass

View file

@ -1,6 +1,7 @@
import os import os
import uuid import uuid
import edge_tts import edge_tts
import edge_tts.communicate # 显式 import,下方要给本模块的 WSS_URL 重新赋值
from datetime import datetime from datetime import datetime
from core.providers.tts.base import TTSProviderBase from core.providers.tts.base import TTSProviderBase
from config.logger import setup_logging from config.logger import setup_logging
@ -8,6 +9,20 @@ from config.logger import setup_logging
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
# 微软 2026-10 起对 legacy 消费者接口返回 403,edge-tts 7.2.8 仍走
# speech.platform.bing.com 走不通。上游 PR rany2/edge-tts#491 切到
# api.msedgeservices.com 修好,但 7.2.8 仍是 PyPI 最新版本,临时把 WSS_URL 顶住。
# TODO(7.2.9): 升 edge-tts ≥ 7.2.9 后删掉这段 monkey patch。
_NEW_WSS_URL = (
"wss://api.msedgeservices.com/tts/cognitiveservices/websocket/v1"
f"?Ocp-Apim-Subscription-Key={edge_tts.constants.TRUSTED_CLIENT_TOKEN}"
)
# communicate.py 第 35 行 `from .constants import WSS_URL` 会在 import 时把
# WSS_URL 复制成本模块局部名,只改 edge_tts.constants.WSS_URL 不会生效。
# __stream() 走 LEGB 找的是 edge_tts.communicate.WSS_URL,所以这里两个都要改。
edge_tts.constants.WSS_URL = _NEW_WSS_URL
edge_tts.communicate.WSS_URL = _NEW_WSS_URL
class TTSProvider(TTSProviderBase): class TTSProvider(TTSProviderBase):
TTS_PARAM_CONFIG = [ TTS_PARAM_CONFIG = [

View file

@ -0,0 +1,208 @@
"""ManageApiClient lifecycle regression tests: run directly with unittest; no app/model/network.
Excluded from the pytest suite: the mock layer in tests/conftest.py (global patches of
asyncio.sleep and httpx.AsyncClient at import time) conflicts with the timing assertions
and MockTransport injection in this file; __test__ = False keeps pytest from collecting it,
so run it directly with unittest.
Usage: python -B tests/test_manage_api_client_lifecycle.py -v
"""
__test__ = False
import asyncio
from concurrent.futures import ThreadPoolExecutor
import gc
import importlib.util
import os
from pathlib import Path
import unittest
from unittest.mock import patch
import weakref
import httpx
class ManageApiClientLifecycleTest(unittest.IsolatedAsyncioTestCase):
def setUp(self):
source = Path(os.environ.get('CLIENT_UNDER_TEST', str(
Path(__file__).resolve().parents[1] / 'config/manage_api_client.py')))
spec = importlib.util.spec_from_file_location('_lifecycle_client', source)
self.api = importlib.util.module_from_spec(spec)
spec.loader.exec_module(self.api)
self.cls = self.api.ManageApiClient
self.cls({'manager-api': {'url': 'http://offline.invalid/xiaozhi',
'secret': 'synthetic-test', 'max_retries': 1, 'retry_delay': 0}})
self.clients = []
self.requests = []
self.real_client = httpx.AsyncClient
def transport(self, handler):
def factory(**kwargs):
async def handle(request):
self.requests.append(request)
return await handler(request)
client = self.real_client(transport=httpx.MockTransport(handle), **kwargs)
self.clients.append(client)
return client
return patch.object(self.api.httpx, 'AsyncClient', side_effect=factory)
async def asyncTearDown(self):
try:
self.assertTrue(all(c.is_closed for c in self.clients), 'client escaped its request')
finally:
for client in self.clients:
if not client.is_closed:
await client.aclose()
self.cls.safe_close()
async def test_success_preserves_url_headers_and_payload(self):
async def handle(request):
self.assertEqual(str(request.url), 'http://offline.invalid/xiaozhi/report')
self.assertEqual(request.headers['authorization'], 'Bearer synthetic-test')
self.assertEqual(request.content, b'{"value":123}')
return httpx.Response(200, json={'code': 0, 'data': {'ok': True}})
with self.transport(handle):
self.assertEqual(await self.cls._execute_async_request('POST', '/report',
json={'value': 123}), {'ok': True})
async def test_retry_reuses_client_until_request_ends(self):
"""Retries reuse the same client (same pooled keep-alive connection) and it is
closed only after the whole business request finishes: the client lifecycle is
aligned with the business request, not with a single attempt."""
async def handle(request):
if len(self.requests) == 1:
return httpx.Response(503)
# the first client is still serving the second attempt (not closed early)
self.assertFalse(self.clients[0].is_closed)
return httpx.Response(200, json={'code': 0, 'data': True})
with self.transport(handle):
self.assertTrue(await self.cls._execute_async_request('POST', '/report'))
self.assertEqual(len(self.clients), 1)
self.assertTrue(self.clients[0].is_closed)
async def test_timeout_exhaustion_reuses_client_until_request_ends(self):
async def handle(request):
raise httpx.ReadTimeout('synthetic timeout', request=request)
with self.transport(handle), self.assertRaises(httpx.ReadTimeout):
await self.cls._execute_async_request('POST', '/report')
self.assertEqual(len(self.clients), 1)
self.assertTrue(self.clients[0].is_closed)
async def test_remote_protocol_error_without_response_triggers_retry(self):
"""Stale keep-alive case: the response never started, so retrying is safe."""
async def handle(request):
if len(self.requests) == 1:
raise httpx.RemoteProtocolError(
'Server disconnected without sending a response.',
request=request)
return httpx.Response(200, json={'code': 0, 'data': True})
with self.transport(handle):
self.assertTrue(await self.cls._execute_async_request('POST', '/report'))
self.assertEqual(len(self.requests), 2)
async def test_remote_protocol_error_incomplete_body_not_retried(self):
"""Response truncated mid-flight: the server likely already processed the request,
so retrying the non-idempotent POST would duplicate it; must fail directly."""
async def handle(request):
raise httpx.RemoteProtocolError(
'Peer closed connection without sending complete message body '
'(discarded 10 of 100 read bytes)', request=request)
with self.transport(handle), self.assertRaises(httpx.RemoteProtocolError):
await self.cls._execute_async_request('POST', '/report')
self.assertEqual(len(self.requests), 1)
async def test_nonretryable_http_error(self):
async def handle(request):
return httpx.Response(403)
with self.transport(handle), self.assertRaises(httpx.HTTPStatusError):
await self.cls._execute_async_request('POST', '/report')
self.assertEqual(len(self.clients), 1)
async def test_business_error_and_invalid_json_release_client(self):
for response, error in [
(httpx.Response(200, json={'code': 10041, 'msg': 'missing'}), self.api.DeviceNotFoundException),
(httpx.Response(200, json={'code': 10042, 'msg': 'bind'}), self.api.DeviceBindException),
(httpx.Response(200, content=b'not-json'), ValueError),
]:
async def handle(request):
return response
with self.transport(handle), self.assertRaises(error):
await self.cls._execute_async_request('POST', '/report')
self.assertTrue(self.clients[-1].is_closed)
self.assertEqual(len(self.clients), 3)
async def test_cancellation_does_not_close_concurrent_request(self):
entered = [asyncio.Event(), asyncio.Event()]
release = asyncio.Event()
async def handle(request):
index = len(self.requests) - 1
entered[index].set()
await release.wait()
return httpx.Response(200, json={'code': 0, 'data': True})
with self.transport(handle):
first = asyncio.create_task(self.cls._execute_async_request('POST', '/first'))
await asyncio.wait_for(entered[0].wait(), 2)
second = asyncio.create_task(self.cls._execute_async_request('POST', '/second'))
await asyncio.wait_for(entered[1].wait(), 2)
first.cancel()
with self.assertRaises(asyncio.CancelledError):
await first
self.assertTrue(self.clients[0].is_closed)
self.assertFalse(self.clients[1].is_closed)
release.set()
self.assertTrue(await asyncio.wait_for(second, 2))
async def test_shutdown_allows_inflight_cleanup_and_blocks_report_entry(self):
async def handle(request):
self.cls.safe_close()
return httpx.Response(200, json={'code': 0, 'data': True})
with self.transport(handle):
self.assertTrue(await self.api.report('device', 'session', 1, 'text', None, 0))
self.assertIsNone(await self.api.report('device', 'session', 1, 'later', None, 0))
with self.assertRaisesRegex(Exception, 'is closed'):
await self.cls._execute_async_request('POST', '/report')
self.assertEqual(len(self.clients), 1)
async def test_safe_close_interrupts_retry_backoff(self):
"""safe_close interrupts the retry wait: the started attempt runs to completion,
no new attempt is issued, and it terminates with ManageApiShutdownError
(distinguishable from a retry-exhausted network error)."""
async def handle(request):
return httpx.Response(503)
original_delay = self.cls.retry_delay
self.cls.retry_delay = 5.0 # setUp default 0 would not show the interruption
try:
with self.transport(handle):
task = asyncio.create_task(
self.cls._execute_async_request('POST', '/report'))
await asyncio.sleep(0.2) # let it enter the retry wait
self.cls.safe_close()
with self.assertRaises(self.api.ManageApiShutdownError) as ctx:
await task
self.assertIsInstance(ctx.exception.__cause__, httpx.HTTPStatusError)
# only the first attempt: the retry wait was interrupted, no new attempt issued
self.assertEqual(len(self.clients), 1)
self.assertEqual(len(self.requests), 1)
finally:
self.cls.retry_delay = original_delay
async def test_many_temporary_loops_leave_no_open_clients(self):
async def handle(request):
return httpx.Response(200, json={'code': 0, 'data': True})
def report_once(_):
return asyncio.run(self.cls._execute_async_request('POST', '/report'))
with self.transport(handle), ThreadPoolExecutor(max_workers=5) as pool:
results = list(pool.map(report_once, range(100)))
self.assertTrue(all(results))
self.assertEqual(len(self.clients), 100)
self.assertTrue(all(c.is_closed for c in self.clients))
# Cache regression guard: once the test drops its strong references the client must be
# GC-collectable; reintroducing any class-level cache (id(loop) dict /
# WeakKeyDictionary) would leave survivors > 0
refs = [weakref.ref(c) for c in self.clients]
self.clients.clear()
gc.collect()
self.assertEqual(sum(ref() is not None for ref in refs), 0)
if __name__ == '__main__':
unittest.main()