Separate detected speech limits from continuous microphone silence while preserving transport bounds and absolute commit fencing. Handle verified OpenAI cancellation races and terminal items, preserve causal close outcomes, and share bounded cleanup ownership with safe diagnostics. Add regression coverage and align the API contract and frontend handoff. Validation: 61 focused unit tests passed; staged diff whitespace checks passed. Live browser acceptance remains outstanding.
155 lines
8.3 KiB
Python
155 lines
8.3 KiB
Python
"""Actual Gemini adapter + runtime + canonical search + StructuredTool/shared runner."""
|
|
import asyncio
|
|
import base64
|
|
from contextlib import nullcontext
|
|
import json
|
|
from types import SimpleNamespace
|
|
from uuid import uuid4
|
|
import pytest
|
|
from app.infrastructure.gemini_live import GeminiLiveAdapter, PCM24To16, GeminiContextError
|
|
from app.modules.voice.runtime import VoiceRuntime
|
|
from app.modules.voice.settings import RuntimeSettings
|
|
from app.modules.knowledge import langchain_tool as boundary
|
|
from tests.unit.test_search_phase2 import service as canonical_service, row
|
|
from tests.unit.test_realtime_phase1 import runner, persisted, until
|
|
|
|
class FakeGoogleTransport:
|
|
def __init__(self):
|
|
self.sent = []
|
|
self.inbound = asyncio.Queue()
|
|
self.closed = 0
|
|
async def send(self, value):
|
|
self.sent.append(json.loads(value))
|
|
async def recv(self):
|
|
value = await self.inbound.get()
|
|
if isinstance(value, Exception):
|
|
raise value
|
|
return json.dumps(value) if isinstance(value,dict) else value
|
|
async def close(self):
|
|
self.closed += 1
|
|
|
|
async def make(service, runner, state):
|
|
wire, output = FakeGoogleTransport(), []
|
|
adapter = GeminiLiveAdapter(wire, model='configured-model', voice='Aoede')
|
|
async def emit(value): output.append(value)
|
|
async def authority(execution):
|
|
return state['enabled'] and execution.capture(dict(id=execution.user_id, organization_id='fixture',role='user'),state['epoch'])
|
|
runtime = VoiceRuntime(adapter, service, runner, uuid4(), emit, authority_check=authority)
|
|
await runtime.start()
|
|
receive = asyncio.create_task(runtime.receive_loop())
|
|
await until(lambda: wire.sent)
|
|
assert not runtime.ready and not adapter.acknowledged(adapter.setup()['session'])
|
|
await wire.inbound.put({'setupComplete':{}})
|
|
await until(lambda: runtime.ready)
|
|
return runtime, adapter, wire, output, receive
|
|
|
|
async def input_turn(runtime, wire, start=0):
|
|
for _ in range(2):
|
|
await runtime.input_audio(bytes(4800))
|
|
await until(lambda: runtime.input_transport_count == 0)
|
|
await wire.inbound.put({'voiceActivity': {'type':'ACTIVITY_START','audioOffset':f'{start/1000}s'}})
|
|
await wire.inbound.put({'voiceActivity': {'type':'ACTIVITY_END','audioOffset':f'{(start+100)/1000}s'}})
|
|
|
|
async def cleanup(runtime, receive):
|
|
receive.cancel()
|
|
await asyncio.gather(receive,return_exceptions=True)
|
|
await runtime.close()
|
|
|
|
@pytest.mark.parametrize('rows,status', [([row()],'ok'),([],'no_evidence')])
|
|
def test_native_tool_correlation_canonical_result_and_once_only_continuation(settings,monkeypatch,runner,persisted,rows,status):
|
|
service = canonical_service(settings,monkeypatch,rows)
|
|
async def scenario():
|
|
runtime,adapter,wire,out,receive = await make(service,runner,persisted)
|
|
try:
|
|
assert wire.sent[0]['setup']['model']=='models/configured-model'
|
|
assert wire.sent[0]['setup']['inputAudioTranscription']=={}
|
|
await input_turn(runtime,wire)
|
|
await wire.inbound.put({'serverContent': {'inputTranscription':{'text':'پرسش'}}})
|
|
fn={'id':'private-google-call','name':'search_knowledge','args':{'query':'q'}}
|
|
await wire.inbound.put({'toolCall':{'functionCalls':[fn]}})
|
|
await until(lambda: any('toolResponse' in m for m in wire.sent) or not runtime.usable)
|
|
assert runtime.usable, runtime.failure
|
|
responses=[m['toolResponse'] for m in wire.sent if 'toolResponse' in m]
|
|
assert len(responses)==1
|
|
answer=responses[0]['functionResponses'][0]
|
|
assert answer['id']=='private-google-call' and answer['response']['status']==status
|
|
assert answer['response']['sources']==next(iter(runtime.calls.values()))[1]['result']['sources']
|
|
await wire.inbound.put({'serverContent': {'modelTurn':{'parts':[{'inlineData':{'mimeType':'audio/pcm;rate=24000','data':base64.b64encode(bytes(960)).decode()}}]},'outputTranscription':{'text':'پاسخ'},'turnComplete':True}})
|
|
await until(lambda: any(isinstance(e,dict) and e.get('type')=='audio_ended' for e in out) or not runtime.usable)
|
|
assert runtime.usable, runtime.failure
|
|
assert any(isinstance(e,dict) and e.get('role')=='user' and e['text']=='پرسش' for e in out)
|
|
assert any(isinstance(e,dict) and e.get('role')=='assistant' and e['status']=='completed' and e['text']=='پاسخ' for e in out)
|
|
source_event=next(e for e in out if isinstance(e,dict) and e.get('type')=='sources')
|
|
assert source_event['tool_call_id']!='private-google-call'
|
|
finally:
|
|
await cleanup(runtime,receive)
|
|
assert wire.closed==1
|
|
asyncio.run(scenario())
|
|
|
|
@pytest.mark.parametrize('message', [ConnectionError('remote-private-detail'), 'x'*262145,
|
|
{'serverContent':{'interrupted':True}}, {'goAway':{'timeLeft':'1s'}}],
|
|
ids=['provider_loss', 'oversized_frame', 'unexpected_interruption', 'goaway'])
|
|
def test_provider_loss_and_limits_wake_runtime_and_close_once(runner,persisted,message):
|
|
async def scenario():
|
|
runtime,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
|
await wire.inbound.put(message)
|
|
await asyncio.wait_for(runtime.failure_signal.wait(),2)
|
|
await cleanup(runtime,receive)
|
|
assert wire.closed==1 and not runtime.usable
|
|
assert 'remote-private-detail' not in json.dumps([e for e in out if isinstance(e,dict)])
|
|
asyncio.run(scenario())
|
|
|
|
def test_no_fabricated_cancel_or_truncate_acknowledgement():
|
|
async def scenario():
|
|
wire=FakeGoogleTransport();adapter=GeminiLiveAdapter(wire)
|
|
with pytest.raises(GeminiContextError):
|
|
await adapter.send({'type':'response.cancel','response_id':'private'})
|
|
await adapter.close()
|
|
assert wire.closed==1 and not wire.sent and adapter._inbound_events.empty()
|
|
asyncio.run(scenario())
|
|
|
|
def test_bounded_queue_and_resampler_partition_invariance():
|
|
adapter=GeminiLiveAdapter(FakeGoogleTransport())
|
|
for i in range(adapter.settings.max_control_messages): adapter._put({'type':'test','n':i})
|
|
with pytest.raises(ValueError): adapter._put({'type':'overflow'})
|
|
pcm=bytes([1,3])*2400
|
|
assert len(PCM24To16().convert(pcm))==3200
|
|
a=PCM24To16();b=PCM24To16()
|
|
assert a.convert(pcm)==b.convert(pcm[:200])+b.convert(pcm[200:])
|
|
|
|
|
|
def test_unverified_input_boundaries_fail_closed(runner,persisted):
|
|
async def scenario():
|
|
runtime,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
|
await wire.inbound.put({'toolCall':{'functionCalls':[{'id':'x','name':'search_knowledge','args':{'query':'q'}}]}})
|
|
await asyncio.wait_for(runtime.failure_signal.wait(),2)
|
|
assert not runtime.calls
|
|
await cleanup(runtime,receive)
|
|
asyncio.run(scenario())
|
|
|
|
|
|
def test_operator_uses_configured_gemini_with_actual_runtime_tool(settings,monkeypatch,runner,persisted,capsys):
|
|
from app import voice_smoke
|
|
from app.modules.voice.configuration import VoiceSettings
|
|
from app.modules.voice import runtime as runtime_module
|
|
monkeypatch.setattr(runtime_module,'transaction',lambda _:nullcontext(None))
|
|
monkeypatch.setattr(runtime_module,'authority',boundary.authority)
|
|
class Scripted(FakeGoogleTransport):
|
|
async def send(self,value):
|
|
await super().send(value)
|
|
message=self.sent[-1]
|
|
if 'setup' in message:await self.inbound.put({'setupComplete':{}})
|
|
elif 'clientContent' in message:
|
|
await self.inbound.put({'toolCall':{'functionCalls':[{'id':'private','name':'search_knowledge','args':{'query':'q'}}]}})
|
|
elif 'toolResponse' in message:
|
|
await self.inbound.put({'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}})
|
|
wire=Scripted()
|
|
async def connection(*args):return wire
|
|
monkeypatch.setattr('app.infrastructure.voice_provider.connect_gemini',connection)
|
|
config=VoiceSettings(_env_file=None,gemini_api_key='fake-only',gemini_model='configured-model')
|
|
service=canonical_service(settings,monkeypatch,[row()])
|
|
assert asyncio.run(voice_smoke.run(service,runner,uuid4(),config,'q',3,4))==0
|
|
assert wire.sent[0]['setup']['model']=='models/configured-model'
|
|
assert wire.closed==1
|
|
assert 'smoke_correlation' in capsys.readouterr().out
|