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())