169 lines
8.4 KiB
Python
169 lines
8.4 KiB
Python
import asyncio
|
|
import io
|
|
import json
|
|
import struct
|
|
import tempfile
|
|
import unittest
|
|
import uuid
|
|
import wave
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
from fastapi.testclient import TestClient
|
|
from unittest.mock import patch
|
|
|
|
from gateway import Dialogue, app
|
|
from history import History
|
|
from protocol import pack
|
|
from tests_fake import FakeModel
|
|
from test_gateway import Socket
|
|
|
|
|
|
class SpeechModel(FakeModel):
|
|
def infer(self, pcm, state): return (0.9 if pcm[0] else 0.0), state
|
|
|
|
|
|
class HistoryTests(unittest.IsolatedAsyncioTestCase):
|
|
async def asyncSetUp(self):
|
|
self.temp = tempfile.TemporaryDirectory()
|
|
self.h = History(Path(self.temp.name) / 'history.sqlite3')
|
|
await self.h.initialize()
|
|
self.cid = await self.h.conversation()
|
|
|
|
async def asyncTearDown(self): self.temp.cleanup()
|
|
|
|
async def test_restore_window_clear_and_partial(self):
|
|
for i in range(12):
|
|
rid = str(uuid.uuid4())
|
|
await self.h.begin(self.cid, rid, f'user{i}')
|
|
await self.h.finish(rid, f'answer{i}', 'completed')
|
|
await self.h.drained(rid)
|
|
partial = str(uuid.uuid4())
|
|
await self.h.begin(self.cid, partial, 'partial user')
|
|
await self.h.finish(partial, 'unfinished', 'interrupted')
|
|
restarted = History(self.h.path); await restarted.initialize()
|
|
context = await restarted.context(self.cid, 'current')
|
|
self.assertEqual(len(context), 20)
|
|
self.assertEqual(context[0]['content'], 'user2')
|
|
self.assertFalse(any(x['content'] == 'unfinished' for x in context))
|
|
self.assertEqual(len(await restarted.rows(self.cid)), 26)
|
|
other = await restarted.conversation()
|
|
await restarted.begin(other, str(uuid.uuid4()), 'keep')
|
|
await restarted.clear(self.cid)
|
|
self.assertEqual(await restarted.rows(self.cid), [])
|
|
self.assertEqual(len(await restarted.rows(other)), 2)
|
|
self.assertEqual(self.h.path.stat().st_mode & 0o777, 0o600)
|
|
with self.assertRaises(ValueError): await restarted.conversation('../bad')
|
|
|
|
async def test_stale_finalize_and_playback_separate(self):
|
|
rid = str(uuid.uuid4())
|
|
await self.h.begin(self.cid, rid, 'user')
|
|
await self.h.interrupt(rid)
|
|
await self.h.finish(rid, 'partial', 'interrupted')
|
|
await self.h.finish(rid, 'old complete', 'completed')
|
|
rows = await self.h.rows(self.cid)
|
|
self.assertEqual(rows[-1]['text'], 'partial')
|
|
self.assertEqual(rows[-1]['status'], 'interrupted')
|
|
self.assertEqual(await self.h.context(self.cid, 'other'), [])
|
|
rid2 = str(uuid.uuid4())
|
|
await self.h.begin(self.cid, rid2, 'user2')
|
|
await self.h.finish(rid2, 'answer2', 'completed')
|
|
self.assertEqual((await self.h.rows(self.cid))[-1]['playback'], 'awaiting_drain')
|
|
self.assertEqual(await self.h.context(self.cid, 'next'), [])
|
|
rid3 = str(uuid.uuid4())
|
|
await self.h.begin(self.cid, rid3, 'unheard user')
|
|
await self.h.finish(rid3, 'unheard completed answer', 'completed')
|
|
await self.h.interrupt(rid3)
|
|
self.assertEqual(await self.h.context(self.cid, 'next'), [])
|
|
self.assertEqual((await self.h.rows(self.cid))[-1]['status'], 'completed')
|
|
await self.h.drained(rid2)
|
|
rows = await self.h.rows(self.cid)
|
|
self.assertEqual(next(r for r in rows if r['run_id'] == rid2 and r['role'] == 'assistant')['playback'], 'confirmed')
|
|
self.assertEqual(len(await self.h.context(self.cid, 'next')), 2)
|
|
|
|
async def test_duplex_running_and_awaiting_drain_no_loop(self):
|
|
for running in (True, False):
|
|
socket = Socket(); d = Dialogue(socket, SpeechModel(), None)
|
|
await d.listen('auto')
|
|
old = d.turn
|
|
if running: d.task = asyncio.create_task(asyncio.sleep(10))
|
|
else: d.playback_waiting = True
|
|
await d.input(pack(1, old, 1, struct.pack('<h', 1000) * 1536))
|
|
self.assertEqual(d.turn, old + 1)
|
|
after_start = d.turn
|
|
await d.input(pack(1, d.turn, 1, struct.pack('<h', 1000) * 1536))
|
|
self.assertEqual(d.turn, after_start)
|
|
submitted = []
|
|
async def submit(pcm, end): submitted.append((len(pcm), end))
|
|
d.submit = submit
|
|
await d.input(pack(1, d.turn, 2, bytes(10240)))
|
|
self.assertEqual(submitted, [(6144, 3072)])
|
|
self.assertEqual(len([e for e in socket.events if e.get('reason') == 'voice_barge_in']), 1)
|
|
await d.close()
|
|
|
|
async def test_two_turn_mock_context_and_drain(self):
|
|
calls = []
|
|
wav = io.BytesIO()
|
|
with wave.open(wav, 'wb') as w:
|
|
w.setnchannels(1); w.setsampwidth(2); w.setframerate(48000); w.writeframes(struct.pack('<h', 1000) * 960)
|
|
def backend(request):
|
|
if 'transcriptions' in request.url.path: return httpx.Response(200, json={'text': '当前问题'})
|
|
if 'chat' in request.url.path:
|
|
calls.append(json.loads(request.content)['messages'])
|
|
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"直接回答。"}}]}\n\ndata: [DONE]\n\n')
|
|
return httpx.Response(200, content=wav.getvalue())
|
|
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
|
|
d = Dialogue(Socket(), SpeechModel(), client, self.h, self.cid)
|
|
for _ in range(2):
|
|
await d.submit(bytes(640), 320)
|
|
await d.task
|
|
await d.drained()
|
|
self.assertEqual(len(calls[0]), 2)
|
|
self.assertEqual(len(calls[1]), 4)
|
|
self.assertEqual(calls[1][-1], {'role':'user','content':'当前问题'})
|
|
self.assertEqual(len(await self.h.rows(self.cid)), 4)
|
|
await d.close()
|
|
|
|
async def test_interrupted_pipeline_keeps_partial_no_new_turn_pollution(self):
|
|
socket = Socket(); d = Dialogue(socket, SpeechModel(), None, self.h, self.cid)
|
|
rid = str(uuid.uuid4()); d.run_id = rid
|
|
await self.h.begin(self.cid, rid, 'old question')
|
|
async def old_pipeline():
|
|
try: await asyncio.sleep(10)
|
|
finally: await self.h.finish(rid, 'old partial', 'interrupted')
|
|
d.task = asyncio.create_task(old_pipeline()); await asyncio.sleep(0)
|
|
await d.invalidate('voice_barge_in')
|
|
await asyncio.gather(*list(d.cancelled_tasks), return_exceptions=True)
|
|
new_rid = str(uuid.uuid4())
|
|
await self.h.begin(self.cid, new_rid, 'new question')
|
|
await self.h.finish(new_rid, 'new answer', 'completed')
|
|
await self.h.drained(new_rid)
|
|
rows = await self.h.rows(self.cid)
|
|
self.assertEqual([r['status'] for r in rows], ['completed','interrupted','completed','completed'])
|
|
self.assertEqual(len(await self.h.context(self.cid, 'future')), 2)
|
|
await d.close()
|
|
|
|
|
|
class AuthHistoryTests(unittest.TestCase):
|
|
def test_history_only_after_auth_and_scoped(self):
|
|
with tempfile.TemporaryDirectory() as directory, patch.dict('os.environ', {'LAN_GATEWAY_TOKEN':'x'*40}), patch('gateway.ROOT', Path(directory)):
|
|
app.state.busy = False; app.state.token = 'x'*40
|
|
h = History(Path(directory)/'history.sqlite3')
|
|
asyncio.run(h.initialize()); app.state.history = h
|
|
app.state.model = FakeModel(); app.state.client = None
|
|
from tts_debug import DebugStore
|
|
app.state.debug = DebugStore(Path(directory)/'debug')
|
|
from gateway import DEFAULT_VOICE_ID
|
|
app.state.voices = [{'id':DEFAULT_VOICE_ID,'source':'design','default':True}]
|
|
client = TestClient(app)
|
|
with client.websocket_connect('/ws/dialogue', headers={'Origin':'https://192.168.31.61:5011'}) as ws:
|
|
ws.send_json({'type':'history','action':'get'})
|
|
with self.assertRaises(Exception): ws.receive_json()
|
|
with client.websocket_connect('/ws/dialogue', headers={'Origin':'https://192.168.31.61:5011'}) as ws:
|
|
ws.send_json({'type':'auth','token':'x'*40}); ws.receive_json()
|
|
ws.send_json({'type':'hello','codec':'pcm16','sample_rate':16000,'frame_duration':20})
|
|
cid = ws.receive_json()['conversation_id']; history = ws.receive_json()
|
|
self.assertEqual(history['messages'], [])
|
|
ws.send_json({'type':'history','action':'clear','conversation_id':str(uuid.uuid4())})
|
|
with self.assertRaises(Exception): ws.receive_json()
|