dsh-sansheng-liubu/preview/check-preview.mjs

34 lines
7.6 KiB
JavaScript

import {spawn} from 'node:child_process';
import {mkdtemp,writeFile,rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join,dirname} from 'node:path';
import {fileURLToPath,pathToFileURL} from 'node:url';
const dir=dirname(fileURLToPath(import.meta.url));const profile=await mkdtemp(join(tmpdir(),'sansheng-preview-'));let browser,ws;const checks=[];const errors=[];
try{
browser=spawn('C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',['--headless=new','--disable-gpu','--no-first-run','--no-default-browser-check','--remote-debugging-port=0','--user-data-dir='+profile,'about:blank'],{stdio:['ignore','ignore','pipe']});
const endpoint=await new Promise((resolve,reject)=>{let log='';const timer=setTimeout(()=>reject(Error('Browser startup timeout')),20000);browser.stderr.on('data',b=>{log+=b;const m=log.match(/DevTools listening on (.+)/);if(m){clearTimeout(timer);resolve(m[1].trim())}});browser.on('error',reject);browser.on('exit',code=>{if(!log.includes('DevTools listening'))reject(Error('Browser exited '+code))})});
ws=new WebSocket(endpoint);await new Promise((resolve,reject)=>{ws.onopen=resolve;ws.onerror=reject});let n=0;const pending=new Map();ws.onmessage=e=>{const m=JSON.parse(e.data);if(m.id){const p=pending.get(m.id);pending.delete(m.id);if(m.error)p.reject(Error(JSON.stringify(m.error)));else p.resolve(m.result)}else if(m.method==='Runtime.exceptionThrown')errors.push(m.params.exceptionDetails.text)};
const cdp=(method,params={},sessionId)=>new Promise((resolve,reject)=>{const id=++n;pending.set(id,{resolve,reject});ws.send(JSON.stringify({id,method,params,...(sessionId?{sessionId}:{})}))});
const {targetId}=await cdp('Target.createTarget',{url:'about:blank'});const {sessionId}=await cdp('Target.attachToTarget',{targetId,flatten:true});const call=(m,p={})=>cdp(m,p,sessionId);await call('Page.enable');await call('Runtime.enable');
const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(r.exceptionDetails.exception?.description||r.exceptionDetails.text);return r.result.value};
const waitReady=async()=>{for(let i=0;i<100;i++){if(await evaluate('document.querySelectorAll(".role").length===10'))return;await new Promise(r=>setTimeout(r,60))}throw Error('Page not ready')};
const check=async(name,code)=>{if(!await evaluate(code))throw Error('FAIL '+name);checks.push(name)};
const shot=async name=>{const r=await call('Page.captureScreenshot',{format:'png',captureBeyondViewport:false});await writeFile(join(dir,name),Buffer.from(r.data,'base64'))};
await call('Emulation.setDeviceMetricsOverride',{width:1440,height:900,deviceScaleFactor:1,mobile:false});await call('Page.navigate',{url:pathToFileURL(join(dir,'index.html')).href});await waitReady();
await check('Ten fixed two-character roles','document.querySelectorAll(".role").length===10 && [...document.querySelectorAll(".role-name")].every(x=>x.textContent.length===2)');
await check('Unselected role cannot silently save a default model','(()=>{document.getElementById("config-body").dispatchEvent(new Event("submit",{cancelable:true}));return !configs.lead&&document.getElementById("composer-model").textContent==="请选择模型"&&!document.querySelector("option[value=inherit]")})()');
await check('Role switches conversation and preserves draft','(()=>{document.getElementById("message").value="draft-lead";document.querySelector("[data-role=gongbu]").click();const ok=document.getElementById("chat-name").textContent==="工部" && document.getElementById("message").value==="";document.querySelector("[data-role=lead]").click();return ok&&document.getElementById("message").value==="draft-lead"})()');
await check('Role configuration is isolated','(()=>{document.querySelector("[data-role=gongbu]").click();document.getElementById("config-toggle").click();document.getElementById("model").value="custom";document.getElementById("model").dispatchEvent(new Event("change"));document.getElementById("custom-model").value="demo-model";document.getElementById("role-note").value="只处理工程任务";document.getElementById("config-body").requestSubmit();document.querySelector("[data-role=lead]").click();return document.getElementById("model").value===""&&document.getElementById("role-note").value===""})()');
await call('Page.reload');await waitReady();await check('Configuration persists after reload','(()=>{document.querySelector("[data-role=gongbu]").click();return document.getElementById("custom-model").value==="demo-model"&&document.getElementById("role-note").value==="只处理工程任务"})()');
await check('Demo messages remain text and separate by role','(()=>{document.getElementById("message").value="<img src=x onerror=alert(1)>";document.getElementById("composer").requestSubmit();const ok=!document.querySelector(".message img")&&document.querySelector(".message").textContent.includes("<img");document.querySelector("[data-role=lead]").click();return ok&&!document.querySelector(".message")})()');
await check('Sidebar closes and entry reopens it','(()=>{document.getElementById("close-panel").click();const ok=document.getElementById("app").classList.contains("workbench-hidden");document.getElementById("entry").click();return ok&&!document.getElementById("app").classList.contains("workbench-hidden")})()');
await check('Keyboard sidebar resizing','(()=>{const r=document.getElementById("resize");r.dispatchEvent(new KeyboardEvent("keydown",{key:"ArrowLeft",bubbles:true}));return r.getAttribute("aria-valuenow")==="384"})()');
await evaluate('chats.gongbu=[];drafts.lead="";renderChat()');
await evaluate('document.documentElement.style.setProperty("--rail-width","374px");document.documentElement.dataset.theme="light";document.getElementById("toast").hidden=true;document.getElementById("config-body").hidden=true;document.getElementById("config-toggle").setAttribute("aria-expanded","false")');await shot('desktop-light.png');
await evaluate('document.querySelector("[data-role=gongbu]").click();document.getElementById("config-toggle").click();document.getElementById("toast").hidden=true');await call('Emulation.setDeviceMetricsOverride',{width:1440,height:1140,deviceScaleFactor:1,mobile:false});await shot('role-config.png');await call('Emulation.setDeviceMetricsOverride',{width:1440,height:900,deviceScaleFactor:1,mobile:false});
await evaluate('document.querySelector("[data-role=lead]").click();document.getElementById("config-toggle").click();document.documentElement.dataset.theme="dark";document.getElementById("workbench").scrollTop=0');await shot('desktop-dark.png');
await call('Emulation.setDeviceMetricsOverride',{width:390,height:844,deviceScaleFactor:1,mobile:true});await evaluate('document.documentElement.dataset.theme="light";document.getElementById("close-panel").click()');await check('Narrow chat has no horizontal overflow','document.documentElement.scrollWidth<=390');await shot('mobile-chat.png');await evaluate('document.getElementById("panel-toggle").click()');await check('Narrow workbench remains visible without overflow','document.documentElement.scrollWidth<=390&&document.getElementById("workbench").getBoundingClientRect().right<=391');await shot('mobile-workbench.png');
if(errors.length)throw Error(errors.join(';'));console.log(JSON.stringify({passed:checks.length,checks,consoleErrors:errors,screenshots:['desktop-light.png','role-config.png','desktop-dark.png','mobile-chat.png','mobile-workbench.png']}));
await cdp('Browser.close').catch(()=>{});
}finally{ws?.close();browser?.kill();await new Promise(r=>setTimeout(r,500));await rm(profile,{recursive:true,force:true,maxRetries:5,retryDelay:300}).catch(()=>{})}