chore: archive recoverable gateway source baseline

This commit is contained in:
zenord
2026-10-11 20:57:05 +08:00
parent 9b428fb76f
commit 19a7adccd9
58 changed files with 4060 additions and 0 deletions
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Portable model-free archive regression: isolated temp root + synthetic persona manifests."""
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
root = Path(__file__).resolve().parents[1]
with tempfile.TemporaryDirectory(prefix='lan-voice-archive-check-') as folder:
stage = Path(folder)
for source in root.glob('*.py'): shutil.copy2(source, stage/source.name)
for name in ('tests','personas','web'):
shutil.copytree(root/name, stage/name, ignore=shutil.ignore_patterns('__pycache__'))
target=stage/'.runtime/personas'; target.mkdir(parents=True)
for name in ('lvbu','yangmi_fiction'):
# Public dummy IDs only; no production profile/reference audio/runtime copied.
(target/(name+'.json')).write_text(json.dumps({'voice_id':'synthetic-'+name}))
runner=r'''
import sys,unittest
sys.path[:0]=['.','tests']
from pathlib import Path
ordered=['test_gateway','test_continuity','test_history','test_v08','test_debug','test_segmentation','test_guests','test_personas','test_face_context','test_gateway_reply_face']
ordered += sorted(p.stem for p in Path('tests').glob('test_*.py') if p.stem not in ordered)
suite=unittest.TestSuite(unittest.defaultTestLoader.loadTestsFromName(name) for name in ordered)
def safe(suite):
result=unittest.TestSuite()
for item in suite:
if isinstance(item,unittest.TestSuite): result.addTest(safe(item))
elif item.id().endswith('.test_silero_silence_and_state'):
# Model artifacts are intentionally absent; never download/load a model in archive checks.
item.setUp=lambda: (_ for _ in ()).throw(unittest.SkipTest('Silero artifact excluded from source archive'))
result.addTest(item)
else: result.addTest(item)
return result
out=unittest.TextTestRunner(verbosity=2).run(safe(suite))
raise SystemExit(not out.wasSuccessful())
'''
raise SystemExit(subprocess.run([sys.executable,'-c',runner],cwd=stage,env={**os.environ,'PYTHONDONTWRITEBYTECODE':'1'}).returncode)
+51
View File
@@ -0,0 +1,51 @@
import asyncio
import json
import os
import ssl
import sys
import wave
from pathlib import Path
import websockets
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from protocol import pack, unpack
async def main():
ssl_context = ssl.create_default_context(cafile=str(ROOT / '.runtime/gateway-cert.pem'))
with wave.open(str(ROOT / 'tmp/public_tts_16k.wav')) as f: pcm = f.readframes(f.getnframes())
pcm += bytes(32000)
events = []; frames = 0; turn = 0; seq = 0; stopped = asyncio.Event()
async with websockets.connect('wss://192.168.31.61:5011/ws/dialogue', ssl=ssl_context, origin='https://192.168.31.61:5011', proxy=None) as ws:
await ws.send(json.dumps({'type': 'auth', 'token': os.environ['LAN_GATEWAY_TOKEN']})); await ws.recv()
await ws.send(json.dumps({'type': 'hello', 'codec': 'pcm16', 'sample_rate': 16000, 'frame_duration': 20})); await ws.recv()
await ws.send(json.dumps({'type': 'listen', 'mode': 'auto', 'state': 'start'}))
turn = json.loads(await ws.recv())['turn_id']; await ws.recv()
async def receive():
nonlocal turn, seq, frames
while True:
raw = await ws.recv()
if isinstance(raw, bytes):
actual, _, _ = unpack(raw, 2); assert actual == turn; frames += 1
else:
event = json.loads(raw); events.append(event)
if event['type'] == 'abort': turn = event['turn_id']; seq = 0
if event['type'] == 'error': raise AssertionError(event)
if event['type'] == 'tts' and event['state'] == 'stop': stopped.set(); return
task = asyncio.create_task(receive())
for i in range(0, len(pcm), 640):
if any(e['type'] == 'capture.end' for e in events): break
seq += 1; await ws.send(pack(1, turn, seq, pcm[i:i+640])); await asyncio.sleep(.02)
await asyncio.wait_for(task, 60)
assert frames > 0
await ws.send(json.dumps({'type':'playback.drained','turn_id':turn}))
ack = json.loads(await ws.recv()); assert ack['state'] == 'resumed'
await ws.send(json.dumps({'type':'abort'})); await ws.recv()
result = {'status':'passed','mode':'auto','downlink_frames':frames,'drain_ack':'passed','events':events}
(ROOT/'tmp/auto_integration.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n')
print(json.dumps(result,ensure_ascii=False))
if __name__=='__main__': asyncio.run(main())
+80
View File
@@ -0,0 +1,80 @@
import asyncio
import json
import subprocess
import tempfile
import time
from pathlib import Path
import httpx
import websockets
ROOT = Path(__file__).resolve().parents[1]
CHROME = '/home/gorios-spark-2/.cache/ms-playwright/chromium_headless_shell-1243/chrome-headless-shell-linux-arm64/chrome-headless-shell'
async def main():
with tempfile.TemporaryDirectory(prefix='lan-voice-browser-') as profile:
process = subprocess.Popen([CHROME, '--headless', '--no-sandbox', '--ignore-certificate-errors', '--autoplay-policy=no-user-gesture-required', '--remote-debugging-address=127.0.0.1', '--remote-debugging-port=0', '--user-data-dir=' + profile, 'https://192.168.31.61:5011'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
portfile = Path(profile) / 'DevToolsActivePort'
for _ in range(100):
if portfile.exists(): break
await asyncio.sleep(0.05)
port = portfile.read_text().splitlines()[0]
async with httpx.AsyncClient(trust_env=False) as client:
pages = (await client.get(f'http://127.0.0.1:{port}/json')).json()
target = next(p for p in pages if p['type'] == 'page')
async with websockets.connect(target['webSocketDebuggerUrl'], proxy=None) as ws:
counter = 0
async def cdp(method, params):
nonlocal counter
counter += 1; current = counter
await ws.send(json.dumps({'id': current, 'method': method, 'params': params}))
while True:
message = json.loads(await ws.recv())
if message.get('id') == current: return message
await asyncio.sleep(0.5)
result = await cdp('Runtime.evaluate', {'expression': '''(async()=>{
const {Resampler}=await import('/static/audio-core.js');
const {runPlaybackTests}=await import('/static/playback-test.js');
const playbackTests=runPlaybackTests();
const checks=[];
for(const rate of [44100,48000]){
const signal=Float32Array.from({length:rate*2},(_,i)=>Math.sin(i*.01));
const all=new Resampler(rate,16000).push(signal);
const r=new Resampler(rate,16000);let pieces=[];
for(let i=0;i<signal.length;i+=128)pieces.push(...r.push(signal.slice(i,i+128)));
if(all.length!==pieces.length||all.some((x,i)=>Math.abs(x-pieces[i])>1e-7))throw Error('resample drift');
checks.push({rate,outputSamples:pieces.length,chunkInvariant:true});
}
const context=new AudioContext();await context.resume();
await context.audioWorklet.addModule('/static/capture-worklet.js');
await context.audioWorklet.addModule('/static/play-worklet.js');
const node=new AudioWorkletNode(context,'playback');node.connect(context.destination);
const events=[];node.port.onmessage=e=>events.push(e.data);
node.port.postMessage({type:'clear',turn:1});
node.port.postMessage({type:'pcm',turn:1,pcm:new Float32Array(6000).fill(.1)});
node.port.postMessage({type:'end',turn:1});
await new Promise(r=>setTimeout(r,200));node.port.postMessage({type:'clear',turn:2});
await new Promise(r=>setTimeout(r,50));await context.close();
let microphone;
try{const stream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:true,noiseSuppression:true,autoGainControl:true}});microphone={available:true,settings:stream.getAudioTracks()[0].getSettings()};stream.getTracks().forEach(t=>t.stop());}catch(e){microphone={available:false,error:e.name};}
return {secureContext:isSecureContext,title:document.title,checks,playbackTests,workletEvents:events,microphone,opusDisabled:document.querySelector('#codec option:nth-child(2)').disabled};
})()''', 'awaitPromise': True, 'returnByValue': True})
if 'exceptionDetails' in result.get('result', {}): raise RuntimeError(result)
await cdp('Page.captureScreenshot', {'format':'png'})
for width,name in [(1100,'desktop'),(390,'mobile')]:
await cdp('Emulation.setDeviceMetricsOverride', {'width':width,'height':900,'deviceScaleFactor':1,'mobile':width<500})
shot=await cdp('Page.captureScreenshot', {'format':'png'})
import base64
(ROOT / ('tmp/home-'+name+'.png')).write_bytes(base64.b64decode(shot['result']['data']))
data = result['result']['result']['value']
print(json.dumps(data, ensure_ascii=False))
(ROOT / 'tmp/browser_validation.json').write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n')
finally:
process.terminate()
try: process.wait(timeout=5)
except subprocess.TimeoutExpired: process.kill(); process.wait()
if __name__ == '__main__': asyncio.run(main())
+64
View File
@@ -0,0 +1,64 @@
import asyncio
import json
import os
import ssl
import sys
import time
import wave
from pathlib import Path
import websockets
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from protocol import pack, unpack
async def main():
ssl_context = ssl.create_default_context(cafile=str(ROOT / '.runtime/gateway-cert.pem'))
kwargs = dict(ssl=ssl_context, origin='https://192.168.31.61:5011', proxy=None)
url = 'wss://192.168.31.61:5011/ws/dialogue'
async with websockets.connect(url, **kwargs) as ws:
await ws.send(json.dumps({'type': 'auth', 'token': 'invalid'}))
try: await ws.recv(); raise AssertionError('bad auth accepted')
except websockets.exceptions.ConnectionClosed: pass
with wave.open(str(ROOT / 'tmp/public_tts_16k.wav')) as file: pcm = file.readframes(file.getnframes())
events = []; frames = 0; first = None; last_seq = 0
async with websockets.connect(url, **kwargs) as ws:
await ws.send(json.dumps({'type': 'auth', 'token': os.environ['LAN_GATEWAY_TOKEN']}))
assert json.loads(await ws.recv())['state'] == 'ok'
await ws.send(json.dumps({'type': 'hello', 'codec': 'pcm16', 'sample_rate': 16000, 'frame_duration': 20}))
assert json.loads(await ws.recv())['type'] == 'hello'
await ws.send(json.dumps({'type': 'listen', 'mode': 'manual', 'state': 'start'}))
turn = json.loads(await ws.recv())['turn_id']
assert json.loads(await ws.recv())['type'] == 'listen'
for i in range(0, len(pcm), 640):
await ws.send(pack(1, turn, i // 640 + 1, pcm[i:i + 640])); await asyncio.sleep(0.02)
start = time.perf_counter()
await ws.send(json.dumps({'type': 'listen', 'mode': 'manual', 'state': 'stop'}))
async with asyncio.timeout(60):
while True:
raw = await ws.recv()
if isinstance(raw, bytes):
actual, seq, audio = unpack(raw, 2)
assert actual == turn and seq == last_seq + 1
last_seq = seq; frames += 1
if first is None: first = (time.perf_counter() - start) * 1000
else:
event = json.loads(raw); events.append(event)
if event['type'] == 'abort': turn = event['turn_id']; last_seq = 0
if event['type'] == 'error': raise AssertionError(event)
if event['type'] == 'tts' and event['state'] == 'stop': break
await ws.send(json.dumps({'type': 'abort'}))
while True:
raw = await ws.recv()
if isinstance(raw, str) and json.loads(raw)['type'] == 'abort': break
assert frames > 0
assert any(e['type'] == 'stt' and e['text'] for e in events)
assert any(e['type'] == 'llm' and e['text'] for e in events)
result = {'status': 'passed', 'mode': 'manual', 'backend_calls': 'one real full chain; TTS fragment calls bounded by max_tokens=64', 'first_downlink_after_manual_end_ms': round(first, 2), 'downlink_frames': frames, 'events': events}
(ROOT / 'tmp/gateway_integration.json').write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
print(json.dumps(result, ensure_ascii=False))
if __name__ == '__main__': asyncio.run(main())
+74
View File
@@ -0,0 +1,74 @@
import asyncio
import base64
import json
import os
import sys
import time
import wave
from pathlib import Path
import httpx
import websockets
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
def token():
value = os.environ.get('LAN_VAD_TOKEN')
if not value:
raise RuntimeError('provide LAN_VAD_TOKEN in process environment')
return value
async def check():
url = 'ws://192.168.31.61:5010/ws/vad'
try:
async with websockets.connect(url, proxy=None):
raise AssertionError('unauthenticated websocket accepted')
except websockets.exceptions.InvalidStatus as exc:
assert exc.response.status_code == 403
headers = {'Authorization': 'Bearer ' + token()}
events = []
with wave.open(str(ROOT / 'tmp/public_tts_16k.wav')) as w:
pcm = bytes(16000) + w.readframes(w.getnframes()) + bytes(32000)
started = time.perf_counter()
async with websockets.connect(url, additional_headers=headers, proxy=None) as a, websockets.connect(url, additional_headers=headers, proxy=None) as b:
for ws in (a, b):
await ws.send(json.dumps({'type': 'session.start', 'include_preroll_audio': ws is a}))
assert json.loads(await ws.recv())['type'] == 'session.ready'
await b.send(bytes(32000))
await b.send(json.dumps({'type': 'ping'}))
assert json.loads(await b.recv())['type'] == 'pong'
async def receive():
while True:
data = json.loads(await a.recv())
if data['type'] == 'speech.start':
decoded = base64.b64decode(data.pop('preroll_pcm16_base64'))
expected = pcm[data['preroll_start_sample'] * 2:data['audio_until_sample'] * 2]
assert decoded == expected
data['preroll_bytes_verified'] = len(decoded)
events.append(data)
if data['type'] == 'session.ended': return
task = asyncio.create_task(receive())
for i in range(0, len(pcm), 640):
await a.send(pcm[i:i + 640])
await asyncio.sleep(0.02)
await a.send(json.dumps({'type': 'audio.end'}))
await asyncio.wait_for(task, 10)
assert any(e['type'] == 'speech.start' for e in events)
assert any(e['type'] == 'speech.end' and e['reason'] == 'silence' for e in events)
await a.send(json.dumps({'type': 'reset'}))
assert json.loads(await a.recv())['type'] == 'session.reset'
await a.send(bytes(32000))
await a.send(json.dumps({'type': 'ping'}))
assert json.loads(await a.recv())['type'] == 'pong'
result = {'status': 'passed', 'checks': ['auth_rejected', 'real_silero_speech_start_end', 'preroll_bytes', 'two_session_isolation', 'reset', 'real_time_20ms_pacing'], 'elapsed_seconds': round(time.perf_counter() - started, 3), 'events': events}
print(json.dumps(result, ensure_ascii=False))
(ROOT / 'tmp/ws_integration.json').write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
if __name__ == '__main__':
asyncio.run(check())
+135
View File
@@ -0,0 +1,135 @@
import asyncio
import io
import json
import struct
import sys
import time
import wave
from pathlib import Path
import httpx
import numpy as np
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
TEXT = '今天天气不错,我们去散步吧。'
def wav_header(data):
if len(data) < 12 or data[:4] != b'RIFF' or data[8:12] != b'WAVE':
return None
pos = 12
fmt = None
while pos + 8 <= len(data):
tag = data[pos:pos + 4]
size = struct.unpack_from('<I', data, pos + 4)[0]
if tag == b'data':
return (pos + 8, fmt) if fmt else None
if pos + 8 + size > len(data):
return None
if tag == b'fmt ':
fmt = struct.unpack_from('<HHIIHH', data, pos + 8)
pos += 8 + size + (size % 2)
return None
async def tts(client, index, cancel=False):
start = time.perf_counter()
body = bytearray()
first = None
audible = None
header = None
times = []
async with client.stream('POST', 'http://192.168.31.61:5002/v1/audio/speech', json={'model': 'openbmb/VoxCPM2', 'input': TEXT, 'stream': True}) as response:
response.raise_for_status()
async for block in response.aiter_bytes():
elapsed = time.perf_counter() - start
times.append(elapsed)
body.extend(block)
header = header or wav_header(body)
if header:
offset, fmt = header
usable = (len(body) - offset) // 2 * 2
if usable and first is None:
first = elapsed
if usable and audible is None:
pcm = np.frombuffer(body[offset:offset + usable], dtype='<i2')
if np.any(np.abs(pcm.astype(np.int32)) > 327):
audible = elapsed
if cancel and first is not None:
break
result = {'kind': 'tts', 'index': index, 'first_pcm_ms': round(first * 1000, 2) if first else None, 'first_above_minus40dbfs_ms': round(audible * 1000, 2) if audible else None, 'total_ms': round((time.perf_counter() - start) * 1000, 2), 'cancel_after_first_pcm': cancel, 'network_blocks': len(times)}
if header:
offset, fmt = header
result.update({'format_tag': fmt[0], 'channels': fmt[1], 'sample_rate': fmt[2], 'bits': fmt[5], 'audio_seconds': (len(body) - offset) / fmt[3]})
if not cancel:
with wave.open(str(ROOT / 'tmp/public_tts.wav'), 'wb') as wav:
wav.setnchannels(fmt[1]); wav.setsampwidth(fmt[5] // 8); wav.setframerate(fmt[2]); wav.writeframes(body[offset:])
x = np.frombuffer(body[offset:], dtype='<i2')
if fmt[2] != 48000 or fmt[1] != 1 or fmt[5] != 16:
raise ValueError('unexpected TTS format')
trim = len(x) // 3 * 3
reduced = np.rint(x[:trim].reshape(-1, 3).astype(np.float64).mean(axis=1)).astype('<i2')
with wave.open(str(ROOT / 'tmp/public_tts_16k.wav'), 'wb') as wav:
wav.setnchannels(1); wav.setsampwidth(2); wav.setframerate(16000); wav.writeframes(reduced.tobytes())
return result
async def qwen(client, index):
start = time.perf_counter()
first = None
text = ''
reasoning = ''
first_sentence = None
finish = None
usage = None
async with client.stream('POST', 'http://127.0.0.1:8888/v1/chat/completions', json={'model': 'qwen3.8-27b', 'messages': [{'role': 'user', 'content': '请用一句不超过十五个汉字回答:为什么要喝水?不要思考过程。'}], 'stream': True, 'max_tokens': 64, 'temperature': 0, 'chat_template_kwargs': {'enable_thinking': False}, 'stream_options': {'include_usage': True}}) as response:
response.raise_for_status()
async for line in response.aiter_lines():
if not line.startswith('data: ') or line == 'data: [DONE]':
continue
data = json.loads(line[6:])
usage = data.get('usage') or usage
for choice in data.get('choices', []):
delta = choice.get('delta', {})
reasoning += delta.get('reasoning_content') or ''
content = delta.get('content') or ''
if content:
if first is None: first = time.perf_counter() - start
text += content
if first_sentence is None and any(c in text for c in '。!?!?'):
first_sentence = time.perf_counter() - start
finish = choice.get('finish_reason') or finish
return {'kind': 'qwen', 'index': index, 'first_body_ms': round(first * 1000, 2) if first else None, 'first_sentence_ms': round(first_sentence * 1000, 2) if first_sentence else None, 'total_ms': round((time.perf_counter() - start) * 1000, 2), 'body': text, 'reasoning_chars': len(reasoning), 'finish_reason': finish, 'usage': usage, 'enable_thinking': False, 'max_tokens': 64}
async def stt(client, index):
data = (ROOT / 'tmp/public_tts_16k.wav').read_bytes()
start = time.perf_counter()
response = await client.post('http://192.168.31.61:5001/v1/audio/transcriptions', files={'file': ('public.wav', data, 'audio/wav')})
response.raise_for_status()
with wave.open(io.BytesIO(data)) as w: duration = w.getnframes() / w.getframerate()
total = time.perf_counter() - start
return {'kind': 'stt', 'index': index, 'total_ms': round(total * 1000, 2), 'audio_seconds': duration, 'rtf': round(total / duration, 4), 'text': response.json().get('text')}
async def main():
(ROOT / 'tmp').mkdir(exist_ok=True)
results = []
async with httpx.AsyncClient(timeout=30, trust_env=False) as client:
for kind, fn, count in [('tts', tts, 3), ('qwen', qwen, 3), ('stt', stt, 3)]:
for i in range(1, count + 1):
if kind == 'stt' and not (ROOT / 'tmp/public_tts_16k.wav').exists(): break
try:
async with asyncio.timeout(30):
result = await fn(client, i, cancel=i == 3) if kind == 'tts' else await fn(client, i)
except Exception as exc:
result = {'kind': kind, 'index': i, 'error_type': type(exc).__name__}
results.append(result)
print(json.dumps(result, ensure_ascii=False), flush=True)
(ROOT / 'tmp/measurements.json').write_text(json.dumps(results, ensure_ascii=False, indent=2) + '\n')
await asyncio.sleep(0.2)
if __name__ == '__main__':
asyncio.run(main())
+83
View File
@@ -0,0 +1,83 @@
import asyncio
import json
from pathlib import Path
from playwright.async_api import async_playwright
ROOT = Path(__file__).resolve().parents[1]
CHROME = '/home/gorios-spark-2/.cache/ms-playwright/chromium_headless_shell-1243/chrome-headless-shell-linux-arm64/chrome-headless-shell'
URL = 'https://192.168.31.61:5011/'
async def main():
results=[]
async with async_playwright() as pw:
browser=await pw.chromium.launch(executable_path=CHROME,headless=True,args=['--no-sandbox'])
for width in (1100,390):
context=await browser.new_context(ignore_https_errors=True,viewport={'width':width,'height':900})
await context.add_init_script("""window.roleTestSockets=[];const NativeWS=window.WebSocket;window.WebSocket=class extends NativeWS{constructor(...args){super(...args);window.roleTestSockets.push(this);}};""")
page=await context.new_page();errors=[];hellos=[];console=[]
page.on('pageerror',lambda e:errors.append(str(e)))
page.on('console',lambda m:console.append(m.text) if m.type=='error' else None)
def socket(ws):
def received(payload):
if isinstance(payload,str):
try:
data=json.loads(payload)
if data.get('type')=='hello':hellos.append(data)
except ValueError:pass
ws.on('framereceived',received)
page.on('websocket',socket)
await page.goto(URL)
await page.wait_for_function("document.querySelector('#status').textContent.includes('已认证')")
old=hellos[-1]['conversation_id']
cases=[]
for role in ('yangmi_fiction','lvbu','default'):
await page.click('[data-persona="'+role+'"]')
await page.wait_for_function("role => document.querySelector('#persona').value===role && document.querySelector('#status').textContent.includes('已认证')",arg=role)
await page.wait_for_timeout(150)
assert hellos[-1]['conversation_id']!=old, 'conversation unchanged'
old=hellos[-1]['conversation_id']
assert await page.locator('[data-persona="'+role+'"]').evaluate("e=>e.classList.contains('selected')")
expected=(json.loads((ROOT/'.runtime/personas'/('lvbu.json' if role=='lvbu' else 'yangmi_fiction.json')).read_text())['voice_id'] if role!='default' else '9a97272c-3919-5606-9c8f-9552ab602528')
assert hellos[-1]['voice_id']==expected, 'wrong voice'
cases.append({'role':role,'voice_ok':True,'new_conversation':True})
await page.evaluate("() => { document.querySelector('[data-persona=yangmi_fiction]').click();document.querySelector('[data-persona=lvbu]').click();document.querySelector('[data-persona=default]').click(); }")
await page.wait_for_function("document.querySelector('#persona').value==='default' && document.querySelector('#status').textContent.includes('已认证')",timeout=6000)
await page.wait_for_timeout(300)
assert '已认证' in await page.locator('#status').inner_text(), 'rapid switch socket state lost'
await page.evaluate("window.roleTestSockets.at(-1).send(JSON.stringify({type:'listen',mode:'auto',state:'start'}))")
await page.wait_for_function("document.querySelector('#voiceId').disabled && document.querySelector('#status').textContent.includes('监听')")
await page.evaluate("window.roleTestSockets.at(-1).send(JSON.stringify({type:'listen',mode:'auto',state:'stop'}))")
await page.click('[data-persona="yangmi_fiction"]')
await page.wait_for_function("document.querySelector('#persona').value==='yangmi_fiction' && document.querySelector('#status').textContent.includes('已认证')")
assert await page.locator('[data-persona="yangmi_fiction"]').get_attribute('aria-pressed')=='true'
assert not await page.locator('#persona').is_disabled()
assert all(len(h['conversation_id'])==36 for h in hellos)
await page.click('details summary')
await page.click('#disconnect')
await page.wait_for_timeout(200)
await page.click('#connect')
await page.wait_for_function("document.querySelector('#status').textContent.includes('已认证')")
assert len(await page.locator('[data-persona]').all())==3
await page.click('#disconnect');await page.wait_for_timeout(200)
outsider=await browser.new_context(ignore_https_errors=True)
op=await outsider.new_page();await op.goto(URL);await op.wait_for_function("document.querySelector('#status').textContent.includes('已认证')")
await op.click('details summary');await op.click('#disconnect');await op.wait_for_timeout(200)
denied=await op.evaluate("""cid=>new Promise(resolve=>{const s=new WebSocket('wss://'+location.host+'/ws/dialogue');s.onmessage=e=>{const d=JSON.parse(e.data);if(d.type==='auth')s.send(JSON.stringify({type:'hello',codec:'pcm16',sample_rate:16000,frame_duration:20,conversation_id:cid}));if(d.type==='hello'){s.close();resolve(false);}};s.onclose=()=>resolve(true);})""",hellos[-1]['conversation_id'])
assert denied,'cross owner accepted'
await outsider.close()
await page.goto(URL+'debug');assert await page.locator('#token').count()==1
import os
if os.environ.get('LAN_GATEWAY_TOKEN'):
await page.fill('#token',os.environ['LAN_GATEWAY_TOKEN']);await page.click('#connect');await page.wait_for_function("document.querySelector('#status').textContent.includes('已认证')")
assert not errors,errors
assert not console,console
results.append({'width':width,'cases':cases,'pageerrors':errors,'console_errors':console})
await context.close()
await browser.close()
(ROOT/'tmp/role-selection.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n')
print(json.dumps(results,ensure_ascii=False))
if __name__=='__main__':asyncio.run(main())