HEL-877: wire the audited .12 voice base into the one CyberGril chat chain as backend-only code (no deploy, no real voice call) - new independent src/cybergril/voice module: session+router add POST /api/voice/session / DELETE end / GET honest status on the unified instance (server-side room + dedicated cybergril-voice-agent dispatch + short-TTL join token via zero-new-dependency livekit_wire HS256/Twirp matching the installed SDK's wire format verified claim-for-claim on the .12 agent venv stdin-only; keys never reach the browser; unconfigured/no-profile/TTS-down refuse honestly and capabilities.voice stays false), chat_api_client speaks the exact real.ts RealChatAdapter protocol (per-turn health epoch, bounded 409 resync, robust incremental SSE parsing across multibyte/CRLF/multi-data chunk splits, fixed turn_id idempotency, immediate HTTP-stream close on barge-in without waiting for the next ASR final), llm_chat_api is a livekit llm.LLM adapter whose only backend is POST /api/chat so persona/mood/dyad/memory/life-sharing/budget gates and the one same-turn chat_lock govern text and voice identically (phi spoken verbatim via ChatChunk, never archived, no receipt), receipt.py confirms a sharing receipt only after real SDK playback completion with every negative (interrupted/failed/mid-playout/phi/incomplete/stale-epoch) fail-closed and exactly once per turn, stt_funasr/tts_cosyvoice reuse the proven .12 adapters verbatim with provenance, worker.py assembles the dedicated worker (independent voice_state_cybergril.json so D1 stays undecided, no second persona, cg.subtitle data-channel contract for the visual lead, CG-011 proactive seam left as an explicit no-op hook, built-in health port 8082); app.py keeps a minimal registration with voice_service injection for isolated tests; deployment drafts only (config/voice.example.yaml, worker.env.example, restart_cybergril.sh.example with exact-pattern process matching, serve_dual_8360_8361.py keeping HTTP 8360 and the HTTPS voice entry on ONE process sharing state/locks, runbook-hel877-voice.md contract+startup+rollback incl. the >=6GB GPU precondition and the do-not-copy historical fuser warning) - verification: 281 pytest pass on 3.11 venv + requirements.lock after merging the chief engineer's mid-flight HEL-874 rework e978e87 in full (parallel work preserved), verify_hel877_voice_chain.py 8/8 offline full-chain incl. socket-level barge-in fail-close and text/voice mutual same-gate cancellation, real-SDK check on the .12 livekit-agents 1.8.8 venv 8/8 ALL PASS via SSH stdin with zero writes zero network, dual-port single-process smoke on loopback 18360/18361 with a throwaway self-signed cert then stopped, ruff clean on all new code, dual-target requirement checks pass vs origin/hel-870-assembly (current tip e978e87) and origin/main with handoff-HEL-877.json; zero real LLM/embed/TTS/ASR requests, no mic/camera, no downloads/installs, no service start/stop, no 4080 access, no third-account or profile writes, web/ untouched, not merged, not deployed
Co-authored-by: multica-agent <github@multica.ai> ## HEL-877 交付摘要(R5 后台施工,未部署未合并) - 新独立模块 src/cybergril/voice/:专属 livekit worker(agent_name=cybergril-voice-agent,复用 .12 FunASR/CosyVoice/silero 底座,不 fork 不另搭平台,无第二人格/记忆,不直连 LLM);llm_chat_api 适配器与文字前端 real.ts 同协议走 POST /api/chat(epoch 409 有界重同步、SSE 分片、turn_id 幂等、打断即断流);/api/voice/session 建房+专属派发+短时限 token 全服务端(密钥不进浏览器;缺配置/无档案/TTS 停机诚实拒绝;capabilities.voice 不伪造);receipt 仅在 SDK 真实播放完成后确认(打断/失败/φ 轮/旧 epoch 全 fail-closed)。 - 部署草案:/opt/voice-agent-cybergril 目录、worker 健康端口 8082、HTTP 8360 + HTTPS 8361 同进程双入口(deploy/voice/serve_dual_8360_8361.py,共用同一状态/锁)、启动顺序含 TTS GPU≥6GB 前置与回滚;本卡未执行任何启停。契约(开关/字幕/失败/打断/挂断 + CG-011 主动开口接缝)见 docs/runbook-hel877-voice.md §3。 - 自测(零真实请求):281 pytest 全过(含语音 25 例:socket 级打断断流、SSE 边界、重放零调用、文字/语音同门互打断、回执全负例、token 房间隔离);scripts/verify_hel877_voice_chain.py 8/8;.12 agent venv(livekit-agents 1.8.8)真 SDK 检查 8/8(stdin-only 零写入零网络);双端口同进程本地冒烟通过;ruff 干净;需求检查双目标通过(含 handoff-HEL-877.json)。 - 施工中总工 HEL-874(e978e87)推上同分支,本卡已完整并入,不覆盖并行成果。未验证如实列明:端到端语音(TTS 停机/GPU 3.9GB<5.6GB)、真 LiveKit server 的 dispatch/delete、移动端实机——待接线/审核卡真机验收,未经真实验收不称 R5 完成。
This commit is contained in:
@@ -0,0 +1,352 @@
|
||||
"""ChatApi adapter and receipt-gate tests (HEL-877) — real adapter code against
|
||||
the real unified API (fake LLM provider, ASGI/local-socket transports) plus
|
||||
scripted-SSE unit cases. Zero network beyond 127.0.0.1."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import uvicorn
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
|
||||
from test_r2 import R2LLM # noqa: E402
|
||||
|
||||
from cybergril.api.app import create_app # noqa: E402
|
||||
from cybergril.life.runtime import LifeConfig # noqa: E402
|
||||
from cybergril.think.router import build_router # noqa: E402
|
||||
from cybergril.think.scenes import Tier # noqa: E402
|
||||
from cybergril.voice.chat_api_client import ( # noqa: E402
|
||||
ChatApiClient,
|
||||
ChatApiConnectionError,
|
||||
_sse_frames,
|
||||
)
|
||||
from cybergril.voice.receipt import ReceiptSender, TurnLedger, should_ack # noqa: E402
|
||||
|
||||
CREATE = {"name": "语音适配", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api(tmp_path):
|
||||
provider = R2LLM()
|
||||
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
|
||||
# file-backed: uvicorn's lifespan in the live-server tests re-opens the same
|
||||
# database (":memory:" would hand it a second, empty store)
|
||||
app = create_app(db_path=tmp_path / "adapter.db", router=router,
|
||||
life_config=LifeConfig(enabled=True, poll_seconds=3600),
|
||||
semantic_mode="stub")
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/companion", json=CREATE)
|
||||
epoch = client.get("/api/health").json()["epoch"]
|
||||
yield app, provider, epoch
|
||||
provider.mode = ""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def voice(api):
|
||||
app, provider, epoch = api
|
||||
client = ChatApiClient("http://asgi", transport=httpx.ASGITransport(app=app))
|
||||
return client, provider, epoch
|
||||
|
||||
|
||||
async def test_consecutive_multi_turn_stream_and_receipt(voice):
|
||||
client, provider, epoch = voice
|
||||
deltas_seen: list[str] = []
|
||||
turn1 = await client.send_turn("第一句你好", on_delta=deltas_seen.append)
|
||||
turn2 = await client.send_turn("第二句还在", on_delta=deltas_seen.append)
|
||||
assert turn1.completed and turn2.completed
|
||||
assert turn1.text == provider.reply and turn2.text == provider.reply
|
||||
assert turn1.turn_id != turn2.turn_id
|
||||
assert "".join(deltas_seen) == turn1.text + turn2.text
|
||||
assert turn1.receipt and turn2.receipt
|
||||
assert turn1.receipt["turn_id"] == turn1.turn_id
|
||||
assert turn2.receipt["epoch"] == epoch
|
||||
|
||||
|
||||
async def test_completed_turn_replay_adds_no_model_calls(voice):
|
||||
client, provider, _ = voice
|
||||
turn_id = str(uuid4())
|
||||
first = await client.send_turn("重放测试", turn_id=turn_id)
|
||||
calls = len(provider.calls)
|
||||
second = await client.send_turn("重放测试", turn_id=turn_id)
|
||||
assert len(provider.calls) == calls, "replay must not call the model again"
|
||||
assert second.completed and second.text == first.text
|
||||
assert second.receipt, "replay still carries the receipt"
|
||||
|
||||
|
||||
async def test_chat_error_yields_phi_without_receipt(voice):
|
||||
client, provider, _ = voice
|
||||
provider.mode = "error"
|
||||
turn = await client.send_turn("这次会失败")
|
||||
assert turn.completed is False
|
||||
assert turn.error_phi and "没接上话" in turn.error_phi
|
||||
assert turn.receipt is None
|
||||
provider.mode = ""
|
||||
|
||||
|
||||
async def test_epoch_409_resync_bounded(voice):
|
||||
client, _, epoch = voice
|
||||
# server already at `epoch`; claim a stale one -> 409 -> resync once -> done
|
||||
turn = await client.send_turn("旧纪元重同步", epoch=epoch + 999)
|
||||
assert turn.completed and turn.epoch == epoch
|
||||
|
||||
|
||||
async def test_epoch_409_never_loops_on_garbage(voice):
|
||||
client, _, _ = voice
|
||||
# a server that always answers 409 without a usable epoch must not loop
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/api/health":
|
||||
return httpx.Response(200, json={"epoch": 1})
|
||||
return httpx.Response(409, json={"detail": "no epoch here"})
|
||||
|
||||
stubborn = ChatApiClient("http://x", transport=httpx.MockTransport(handler))
|
||||
with pytest.raises(httpx.HTTPStatusError):
|
||||
await stubborn.send_turn("永不重试")
|
||||
|
||||
|
||||
async def test_broken_stream_raises_connection_error():
|
||||
"""The SSE connection itself dies before any terminal frame."""
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/api/health":
|
||||
return httpx.Response(200, json={"epoch": 1})
|
||||
return httpx.Response(
|
||||
200, headers={"content-type": "text/event-stream"},
|
||||
content=b'data: {"t": "chat.delta", "epoch": 1, "turn_id": "' + b"t" * 36 +
|
||||
b'", "delta": "\\u4f60"}\n\n', # stream then simply ends
|
||||
)
|
||||
|
||||
client = ChatApiClient("http://x", transport=httpx.MockTransport(handler))
|
||||
with pytest.raises(ChatApiConnectionError):
|
||||
await client.send_turn("断流")
|
||||
|
||||
|
||||
async def test_voice_turn_cancels_active_text_turn_same_gate(api):
|
||||
"""Voice and text contend through the server's one same-turn gate."""
|
||||
app, provider, _ = api
|
||||
|
||||
async def slow_text() -> None:
|
||||
text_client = ChatApiClient("http://asgi", transport=httpx.ASGITransport(app=app))
|
||||
with pytest.raises((ChatApiConnectionError, Exception)):
|
||||
await text_client.send_turn("文字说一半")
|
||||
|
||||
provider.mode = "slow"
|
||||
task = asyncio.create_task(slow_text())
|
||||
await asyncio.sleep(1.0) # the text turn is active and hanging after its first delta
|
||||
provider.mode = "" # its generator stays parked; the voice turn can complete fast
|
||||
voice_client = ChatApiClient("http://asgi", transport=httpx.ASGITransport(app=app))
|
||||
turn = await voice_client.send_turn("语音插进来")
|
||||
assert turn.completed
|
||||
provider.mode = "" # (already reset above; kept for clarity on early exits)
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
|
||||
rows = app.state.store.query(
|
||||
"SELECT role, text, status, turn_id FROM chat_message ORDER BY id"
|
||||
)
|
||||
slow = [m for m in rows if m["text"] == "文字说一半"]
|
||||
assert slow and slow[0]["status"] == "cancelled", "barge-in cancels the text row"
|
||||
assert not [m for m in rows if m["role"] == "companion" and m["turn_id"] == slow[0]["turn_id"]], \
|
||||
"no phantom companion row for the aborted text turn"
|
||||
assert any(m["role"] == "companion" and m["turn_id"] == turn.turn_id and m["status"] == "sent"
|
||||
for m in rows), "the voice turn itself completes as her archived reply"
|
||||
|
||||
|
||||
# ── SSE parser unit cases: chunk boundaries ──────────────────────────────────
|
||||
|
||||
|
||||
class _FakeResponse:
|
||||
def __init__(self, chunks: list[bytes]):
|
||||
self._chunks = chunks
|
||||
|
||||
async def aiter_bytes(self):
|
||||
for chunk in self._chunks:
|
||||
yield chunk
|
||||
|
||||
|
||||
async def collect(chunks: list[bytes]) -> list[dict]:
|
||||
return [frame async for frame in _sse_frames(_FakeResponse(chunks))]
|
||||
|
||||
|
||||
def frame(event: dict) -> str:
|
||||
return "data: " + json.dumps(event, ensure_ascii=False) + "\n\n"
|
||||
|
||||
|
||||
async def test_sse_split_inside_multibyte_and_crlf_and_multiline():
|
||||
event1 = {"t": "chat.delta", "epoch": 1, "turn_id": "t1", "delta": "你也好呀"}
|
||||
event2 = {"t": "chat.final", "epoch": 1, "turn_id": "t1",
|
||||
"utterance": {"text": "你也好呀"}, "receipt": {"token": "x" * 48}}
|
||||
blob = (frame(event1) + frame(event2)).encode()
|
||||
# split inside a multibyte char, mid-frame, and across CRLF boundaries
|
||||
cuts = [1, 7, 8, 9, 13, 21, len(blob) // 2, len(blob) - 3, len(blob) - 1]
|
||||
chunks, prev = [], 0
|
||||
for cut in cuts + [len(blob)]:
|
||||
chunks.append(blob[prev:cut])
|
||||
prev = cut
|
||||
parsed = await collect(chunks)
|
||||
assert [p["t"] for p in parsed] == ["chat.delta", "chat.final"]
|
||||
assert parsed[1]["receipt"]["token"] == "x" * 48
|
||||
|
||||
|
||||
async def test_sse_multiline_data_and_comment_lines_and_crlf_separator():
|
||||
payload = (": keep-alive\r\n"
|
||||
"data: {\"t\": \"chat.delta\",\r\n"
|
||||
"data: \"delta\": \"两行\"}\r\n\r\n"
|
||||
"data: {\"t\": \"chat.final\"}\r\n\r\n")
|
||||
parsed = await collect([payload.encode("utf-8")])
|
||||
assert parsed[0]["delta"] == "两行"
|
||||
assert parsed[1]["t"] == "chat.final"
|
||||
|
||||
|
||||
async def test_sse_invalid_json_frame_skipped_not_fatal():
|
||||
blob = b"data: not-json\n\ndata: {\"t\": \"chat.final\"}\n\n"
|
||||
parsed = await collect([blob])
|
||||
assert parsed == [{"t": "chat.final"}]
|
||||
|
||||
|
||||
async def test_sse_utf8_split_across_chunks():
|
||||
text = "晚安"
|
||||
first, second = text[:1], text[1:]
|
||||
chunks = [b"data: {\"t\": \"chat.delta\", \"delta\": \"" + first.encode(),
|
||||
second.encode() + b"\"}\n\n"]
|
||||
parsed = await collect(chunks)
|
||||
assert parsed[0]["delta"] == text
|
||||
|
||||
|
||||
# ── receipt gate: playback-completion only ──────────────────────────────────
|
||||
|
||||
|
||||
def _receipt(epoch=3):
|
||||
return {"message_id": 11, "turn_id": "t" * 36, "epoch": epoch,
|
||||
"token": "t" * 48, "text_hash": "h" * 64}
|
||||
|
||||
|
||||
def test_ack_only_after_full_playout():
|
||||
assert should_ack(played_to_end=True, interrupted=False, failed=False,
|
||||
receipt=_receipt(), current_epoch=3)
|
||||
# everything else must fail closed
|
||||
assert not should_ack(played_to_end=True, interrupted=True, failed=False,
|
||||
receipt=_receipt(), current_epoch=3), "barge-in never acks"
|
||||
assert not should_ack(played_to_end=True, interrupted=False, failed=True,
|
||||
receipt=_receipt(), current_epoch=3), "playback/generation failure never acks"
|
||||
assert not should_ack(played_to_end=False, interrupted=False, failed=False,
|
||||
receipt=_receipt()), "not finished playing never acks"
|
||||
assert not should_ack(played_to_end=True, interrupted=False, failed=False,
|
||||
receipt=None), "phi error turn has no receipt"
|
||||
assert not should_ack(played_to_end=True, interrupted=False, failed=False,
|
||||
receipt={"token": "x"}, current_epoch=3), "incomplete receipt never acks"
|
||||
assert not should_ack(played_to_end=True, interrupted=False, failed=False,
|
||||
receipt=_receipt(epoch=2), current_epoch=3), "stale epoch never acks"
|
||||
|
||||
|
||||
def test_receipt_before_playout_not_possible_by_construction():
|
||||
# should_ack requires played_to_end; a receipt arriving mid-playout has no
|
||||
# path to True even if every other field is perfect.
|
||||
for interrupted in (True, False):
|
||||
assert not should_ack(played_to_end=False, interrupted=interrupted, failed=False,
|
||||
receipt=_receipt())
|
||||
|
||||
|
||||
async def test_ledger_binds_handle_to_its_stream():
|
||||
ledger = TurnLedger()
|
||||
handle = type("H", (), {"created_at": 1.0})()
|
||||
older = type("S", (), {"created_at": 0.5, "text": "old"})()
|
||||
ledger.note_stream(older, 0.5)
|
||||
ledger.note_handle(handle, 1.0)
|
||||
stream = type("S", (), {"created_at": 1.2, "text": "new"})()
|
||||
ledger.note_stream(stream, 1.2)
|
||||
assert ledger.stream_for(handle) is stream, "first stream at/after the handle"
|
||||
assert ledger.stream_for(handle) is None, "binding consumed exactly once"
|
||||
|
||||
|
||||
async def test_receipt_sender_confirms_once_and_reports_server_refusal():
|
||||
seen: list[tuple[str, dict]] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
seen.append((request.url.path, json.loads(request.read())))
|
||||
return httpx.Response(200, json={"accepted": True})
|
||||
|
||||
client = ChatApiClient("http://x", transport=httpx.MockTransport(handler))
|
||||
sender = ReceiptSender(client)
|
||||
receipt = _receipt()
|
||||
assert await sender.confirm(receipt["turn_id"], receipt) is True
|
||||
assert await sender.confirm(receipt["turn_id"], receipt) is True # no second POST
|
||||
assert len(seen) == 1 and seen[0][0] == "/api/chat/received"
|
||||
|
||||
def refusing(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(404, json={"detail": "gone"})
|
||||
|
||||
refuser = ReceiptSender(
|
||||
ChatApiClient("http://x", transport=httpx.MockTransport(refusing)))
|
||||
assert await refuser.confirm(receipt["turn_id"], receipt) is False
|
||||
|
||||
|
||||
# ── real-socket cancel path: barge-in closes the HTTP stream immediately ─────
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def live_server(api):
|
||||
app, provider, _ = api
|
||||
probe = socket.socket()
|
||||
probe.bind(("127.0.0.1", 0))
|
||||
port = probe.getsockname()[1]
|
||||
probe.close() # free the port for uvicorn to bind
|
||||
config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error")
|
||||
server = uvicorn.Server(config)
|
||||
thread = threading.Thread(target=server.run, daemon=True)
|
||||
thread.start()
|
||||
for _ in range(100):
|
||||
try:
|
||||
httpx.get(f"http://127.0.0.1:{port}/api/health", timeout=1)
|
||||
break
|
||||
except Exception:
|
||||
time.sleep(0.1)
|
||||
yield f"http://127.0.0.1:{port}", app, provider
|
||||
server.should_exit = True
|
||||
thread.join(timeout=5)
|
||||
|
||||
|
||||
async def test_barge_in_cancels_http_stream_and_server_row(live_server):
|
||||
"""Voice-turn cancellation = barge-in: the adapter's in-flight HTTP stream
|
||||
closes immediately; the server marks the row cancelled without waiting for
|
||||
the next ASR final (it never comes in this test)."""
|
||||
url, app, provider = live_server
|
||||
provider.mode = "slow" # reply hangs after first delta
|
||||
client = ChatApiClient(url)
|
||||
got_delta = asyncio.Event()
|
||||
task = asyncio.create_task(
|
||||
client.send_turn("说一半我要打断", on_delta=lambda _: got_delta.set())
|
||||
)
|
||||
await asyncio.wait_for(got_delta.wait(), timeout=10)
|
||||
task.cancel() # the interruption
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
# server notices the disconnect and fail-closes the row
|
||||
for _ in range(50):
|
||||
rows = httpx.get(f"{url}/api/messages").json()["messages"]
|
||||
row = next((m for m in rows if m["text"] == "说一半我要打断"), None)
|
||||
if row and row["status"] == "cancelled":
|
||||
break
|
||||
await asyncio.sleep(0.2)
|
||||
else:
|
||||
row = next((m for m in httpx.get(f"{url}/api/messages").json()["messages"]
|
||||
if m["text"] == "说一半我要打断"), None)
|
||||
assert row and row["status"] == "cancelled"
|
||||
assert not any(m["role"] == "companion" and m["turn_id"] == row["turn_id"]
|
||||
for m in rows), "no phantom companion row for the aborted turn"
|
||||
# and the next turn is clean (no ghost gate)
|
||||
provider.mode = ""
|
||||
nxt = await client.send_turn("打断之后")
|
||||
assert nxt.completed
|
||||
await client.aclose()
|
||||
@@ -0,0 +1,271 @@
|
||||
"""Voice session endpoint tests (HEL-877): honest refusal, server-side dispatch,
|
||||
token room isolation, end/invalidation cleanup — all against the real router and
|
||||
real service with a fake LiveKit Twirp transport. Zero network."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
|
||||
from test_r2 import R2LLM # noqa: E402
|
||||
|
||||
from cybergril.api.app import create_app # noqa: E402
|
||||
from cybergril.life.runtime import LifeConfig # noqa: E402
|
||||
from cybergril.think.router import build_router # noqa: E402
|
||||
from cybergril.think.scenes import Tier # noqa: E402
|
||||
from cybergril.voice import livekit_wire # noqa: E402
|
||||
from cybergril.voice.session import VoiceConfig, VoiceSessionService # noqa: E402
|
||||
|
||||
CREATE = {"name": "语音测试", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友"}
|
||||
|
||||
|
||||
class FakeLiveKit:
|
||||
"""Fake Twirp LiveKit server: records dispatches, room deletes, auth tokens."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.dispatches: list[dict] = []
|
||||
self.deleted_rooms: list[str] = []
|
||||
self.auth_tokens: list[str] = []
|
||||
self.fail = False
|
||||
self.transport = httpx.MockTransport(self._handle)
|
||||
self._dispatch_seq = 0
|
||||
|
||||
def _handle(self, request: httpx.Request) -> httpx.Response:
|
||||
self.auth_tokens.append(request.headers.get("authorization", ""))
|
||||
if self.fail:
|
||||
return httpx.Response(500, text="livekit down")
|
||||
path = request.url.path
|
||||
if path == "/twirp/livekit.AgentDispatchService/CreateDispatch":
|
||||
body = request.content
|
||||
agent_name, room = _parse_dispatch(body)
|
||||
self._dispatch_seq += 1
|
||||
self.dispatches.append({"agent_name": agent_name, "room": room,
|
||||
"proto": True, "content_type":
|
||||
request.headers.get("content-type", "")})
|
||||
return httpx.Response(200, json={"id": f"AD_{self._dispatch_seq}",
|
||||
"agentName": agent_name, "room": room})
|
||||
if path == "/twirp/livekit.RoomService/DeleteRoom":
|
||||
self.deleted_rooms.append(_parse_room(request.content))
|
||||
return httpx.Response(200, content=b"")
|
||||
return httpx.Response(404, text="unknown twirp route")
|
||||
|
||||
def service(self) -> VoiceSessionService:
|
||||
config = VoiceConfig(
|
||||
livekit_url="ws://voice.test:7880",
|
||||
livekit_internal="http://livekit.test",
|
||||
api_key="devkey",
|
||||
api_secret="test-secret-not-real",
|
||||
tts_health_url="http://tts.test/health",
|
||||
)
|
||||
return VoiceSessionService(config=config, http=httpx.AsyncClient(transport=self.transport))
|
||||
|
||||
|
||||
def _read_varint(data: bytes, index: int) -> tuple[int, int]:
|
||||
shift = 0
|
||||
value = 0
|
||||
while True:
|
||||
byte = data[index]
|
||||
value |= (byte & 0x7F) << shift
|
||||
index += 1
|
||||
if not byte & 0x80:
|
||||
return value, index
|
||||
shift += 7
|
||||
|
||||
|
||||
def _parse_dispatch(body: bytes) -> tuple[str, str]:
|
||||
fields = _parse_proto_strings(body)
|
||||
return fields.get(1, ""), fields.get(2, "")
|
||||
|
||||
|
||||
def _parse_room(body: bytes) -> str:
|
||||
return _parse_proto_strings(body).get(1, "")
|
||||
|
||||
|
||||
def _parse_proto_strings(data: bytes) -> dict[int, str]:
|
||||
out = {}
|
||||
index = 0
|
||||
while index < len(data):
|
||||
tag, index = _read_varint(data, index)
|
||||
field, wire = tag >> 3, tag & 7
|
||||
if wire != 2:
|
||||
break
|
||||
length, index = _read_varint(data, index)
|
||||
out[field] = data[index: index + length].decode()
|
||||
index += length
|
||||
return out
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_livekit():
|
||||
return FakeLiveKit()
|
||||
|
||||
|
||||
class FakeTTS:
|
||||
def __init__(self) -> None:
|
||||
self.ok = True
|
||||
self.calls = 0
|
||||
|
||||
def handler(self, request: httpx.Request) -> httpx.Response:
|
||||
self.calls += 1
|
||||
return httpx.Response(200) if self.ok else httpx.Response(503)
|
||||
|
||||
|
||||
def make_app(fake_livekit: FakeLiveKit, tts: FakeTTS):
|
||||
provider = R2LLM()
|
||||
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
|
||||
service = fake_livekit.service()
|
||||
service.http = httpx.AsyncClient(transport=_combined_transport(fake_livekit, tts))
|
||||
app = create_app(db_path=":memory:", router=router,
|
||||
life_config=LifeConfig(enabled=True, poll_seconds=3600),
|
||||
semantic_mode="stub", voice_service=service)
|
||||
return app, service, provider
|
||||
|
||||
|
||||
def _combined_transport(fake_livekit: FakeLiveKit, tts: FakeTTS) -> httpx.MockTransport:
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.host == "tts.test":
|
||||
return tts.handler(request)
|
||||
return fake_livekit._handle(request)
|
||||
|
||||
return httpx.MockTransport(handler)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def instance(fake_livekit):
|
||||
tts = FakeTTS()
|
||||
app, service, provider = make_app(fake_livekit, tts)
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/companion", json=CREATE)
|
||||
yield client, fake_livekit, service, provider, tts
|
||||
|
||||
|
||||
def test_status_unconfigured_honest():
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
app = create_app(db_path=":memory:", router=build_router(
|
||||
providers={t: R2LLM() for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)}),
|
||||
life_config=LifeConfig(enabled=False), semantic_mode="stub")
|
||||
with TestClient(app) as client:
|
||||
status = client.get("/api/voice/status").json()
|
||||
assert status == {"configured": False, "tts_ok": False, "agent_name": None,
|
||||
"voice": False}
|
||||
# health stays honest: capabilities.voice never faked on
|
||||
assert client.get("/api/health").json()["capabilities"]["voice"] is False
|
||||
refusal = client.post("/api/voice/session")
|
||||
assert refusal.status_code == 503
|
||||
assert "语音还没有在这台服务上配置" in refusal.json()["detail"]
|
||||
|
||||
|
||||
def test_open_session_dispatches_dedicated_worker(instance):
|
||||
client, livekit, service, _, _ = instance
|
||||
response = client.post("/api/voice/session")
|
||||
assert response.status_code == 201, response.text
|
||||
body = response.json()
|
||||
# dedicated dispatch, not the generic cascade-voice-agent
|
||||
assert livekit.dispatches[-1]["agent_name"] == "cybergril-voice-agent"
|
||||
assert livekit.dispatches[-1]["room"] == body["room"]
|
||||
assert livekit.dispatches[-1]["proto"] is True
|
||||
assert livekit.dispatches[-1]["content_type"] == "application/protobuf"
|
||||
assert body["url"] == "ws://voice.test:7880"
|
||||
assert body["agent_name"] == "cybergril-voice-agent"
|
||||
# no livekit key material leaks into the browser payload
|
||||
assert "devkey" not in json.dumps(body) and "test-secret-not-real" not in json.dumps(body)
|
||||
|
||||
|
||||
def test_token_is_real_short_ttl_and_room_scoped(instance):
|
||||
client, livekit, _, _, _ = instance
|
||||
secret = "test-secret-not-real"
|
||||
first = client.post("/api/voice/session").json()
|
||||
second = client.post("/api/voice/session").json()
|
||||
assert first["room"] != second["room"], "each session gets its own room"
|
||||
for body in (first, second):
|
||||
claims, signing_input = livekit_wire.decode_token(body["token"])
|
||||
assert livekit_wire.verify_signature(body["token"], secret)
|
||||
assert claims["iss"] == "devkey"
|
||||
assert claims["sub"].startswith("user-")
|
||||
video = claims["video"]
|
||||
assert video["roomJoin"] is True and video["room"] == body["room"]
|
||||
assert video["canPublish"] is True and video["canSubscribe"] is True
|
||||
assert claims["exp"] - claims["nbf"] <= 300, "token must be short-lived"
|
||||
# token for room A grants nothing about room B (room isolation)
|
||||
claims_a, _ = livekit_wire.decode_token(first["token"])
|
||||
claims_b, _ = livekit_wire.decode_token(second["token"])
|
||||
assert claims_a["video"]["room"] != claims_b["video"]["room"]
|
||||
|
||||
|
||||
def test_open_session_refuses_without_companion(fake_livekit):
|
||||
tts = FakeTTS()
|
||||
app, service, _ = make_app(fake_livekit, tts)
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
with TestClient(app) as client:
|
||||
refusal = client.post("/api/voice/session")
|
||||
assert refusal.status_code == 409
|
||||
assert "还没有创建真实伴侣" in refusal.json()["detail"]
|
||||
assert not fake_livekit.dispatches, "no dispatch may happen without a profile"
|
||||
|
||||
|
||||
def test_open_session_refuses_when_tts_down(instance):
|
||||
client, livekit, service, _, tts = instance
|
||||
tts.ok = False
|
||||
service._tts_health.checked = -1e9 # bust cache
|
||||
refusal = client.post("/api/voice/session")
|
||||
assert refusal.status_code == 503
|
||||
assert "她的声音服务这会儿不在" in refusal.json()["detail"]
|
||||
assert not livekit.dispatches
|
||||
tts.ok = True
|
||||
service._tts_health.checked = -1e9
|
||||
assert client.post("/api/voice/session").status_code == 201
|
||||
|
||||
|
||||
def test_open_session_refuses_when_livekit_down(instance):
|
||||
client, livekit, _, _, _ = instance
|
||||
livekit.fail = True
|
||||
refusal = client.post("/api/voice/session")
|
||||
assert refusal.status_code == 503
|
||||
assert "通话服务暂时连不上" in refusal.json()["detail"]
|
||||
|
||||
|
||||
def test_end_session_deletes_room_and_cleans_registry(instance):
|
||||
client, livekit, service, _, _ = instance
|
||||
body = client.post("/api/voice/session").json()
|
||||
assert service.get(body["session_id"]) is not None
|
||||
ended = client.delete(f"/api/voice/session/{body['session_id']}")
|
||||
assert ended.status_code == 200 and ended.json()["ended"] is True
|
||||
assert livekit.deleted_rooms == [body["room"]]
|
||||
assert service.get(body["session_id"]) is None
|
||||
again = client.delete(f"/api/voice/session/{body['session_id']}")
|
||||
assert again.status_code == 404
|
||||
|
||||
|
||||
def test_registry_expiry_prunes_old_sessions(fake_livekit):
|
||||
import asyncio
|
||||
|
||||
service = fake_livekit.service()
|
||||
now = time.time()
|
||||
session = asyncio.run(service.open_session(epoch=7))
|
||||
assert service.get(session.session_id) is not None
|
||||
service.clock = lambda: now + service.config.session_ttl_seconds + 1
|
||||
assert service.get(session.session_id) is None, "expired registry entry pruned"
|
||||
asyncio.run(service.aclose())
|
||||
|
||||
|
||||
def test_worker_auth_tokens_are_server_jwt(instance):
|
||||
client, livekit, _, _, _ = instance
|
||||
client.post("/api/voice/session")
|
||||
auth = livekit.auth_tokens[-1]
|
||||
assert auth.startswith("Bearer ")
|
||||
token = auth.removeprefix("Bearer ")
|
||||
claims, _ = livekit_wire.decode_token(token)
|
||||
assert claims["iss"] == "devkey" and claims["sub"] == ""
|
||||
assert claims["exp"] - claims["nbf"] <= 60
|
||||
Reference in New Issue
Block a user