// Real Rust/Wasm acceptance in an isolated database. Never opens receiver transports. import {mkdtemp,writeFile,readFile} from 'node:fs/promises'; import {tmpdir} from 'node:os'; import path from 'node:path'; import {spawn} from 'node:child_process'; import {createRequire} from 'node:module'; import assert from 'node:assert/strict'; import http from 'node:http'; import net from 'node:net'; const {chromium}=createRequire(import.meta.url)('playwright'); const {PNG}=createRequire(import.meta.url)('pngjs'); const contrastCases=[]; async function contrast(page, label, selectors, required=true) { const samples=await page.evaluate(selectors=>selectors.map(selector=>{const e=document.querySelector(selector),r=e.getBoundingClientRect();return {selector,color:getComputedStyle(e).color,x:Math.round(r.left+2),y:Math.round(r.top-2)}}),selectors); const png=PNG.sync.read(await page.screenshot()); const lum=rgb=>rgb.map(v=>v/255).map(v=>v<=.04045?v/12.92:((v+.055)/1.055)**2.4).reduce((s,v,i)=>s+v*[.2126,.7152,.0722][i],0); for(const sample of samples){const offset=(sample.y*png.width+sample.x)*4;const a=lum(sample.color.match(/[\d.]+/g).slice(0,3).map(Number)),b=lum([...png.data.subarray(offset,offset+3)]);const ratio=(Math.max(a,b)+.05)/(Math.min(a,b)+.05);contrastCases.push({label,selector:sample.selector,ratio});if(required)assert.ok(ratio>=4.5,JSON.stringify({label,...sample,ratio}));} } const root=await mkdtemp(path.join(tmpdir(),'RID-workspace-')); const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe'; const frontendPort=Number(process.env.RID_BROWSER_TEST_PORT||18787),backendPort=Number(process.env.RID_BACKEND_TEST_PORT||18788); const base='http://127.0.0.1:'+frontendPort; // Keep production origin checks unchanged. Only this isolated proxy maps the test origin. const sockets=new Set(); const proxy=http.createServer((req,res)=>{const headers={...req.headers,host:'127.0.0.1:8787'};if(headers.origin===base)headers.origin='http://127.0.0.1:8787';const upstream=http.request({hostname:'127.0.0.1',port:backendPort,path:req.url,method:req.method,headers},r=>{res.writeHead(r.statusCode,r.headers);r.pipe(res)});upstream.on('error',()=>{res.writeHead(502);res.end()});req.pipe(upstream)}); proxy.on('upgrade',(req,socket,head)=>{const upstream=net.connect(backendPort,'127.0.0.1');sockets.add(socket);sockets.add(upstream);upstream.on('connect',()=>{const headers={...req.headers,host:'127.0.0.1:8787'};if(headers.origin===base)headers.origin='http://127.0.0.1:8787';upstream.write(`GET ${req.url} HTTP/1.1\r\n${Object.entries(headers).map(([k,v])=>`${k}: ${v}`).join('\r\n')}\r\n\r\n`);if(head.length)upstream.write(head);socket.pipe(upstream);upstream.pipe(socket)});upstream.on('error',()=>socket.destroy());socket.on('error',()=>upstream.destroy());socket.on('close',()=>{upstream.destroy();sockets.delete(socket);sockets.delete(upstream)})}); let occupied=false;try{await fetch(base,{signal:AbortSignal.timeout(800)});occupied=true;}catch{}if(occupied)throw Error('8787 occupied; preserving existing service'); const backendOccupied=await new Promise(resolve=>{const socket=net.connect(backendPort,'127.0.0.1');socket.once('connect',()=>{socket.destroy();resolve(true)});socket.once('error',()=>resolve(false));socket.setTimeout(800,()=>{socket.destroy();resolve(false)})});if(backendOccupied)throw Error('18788 occupied; preserving existing service'); let output='',child,browser;const errors=[],csp=[]; function start(){child=spawn(exe,['--data-root',root,'--simulation-api'],{env:{...process.env,PATH:'C:\\Windows\\System32',RID_TEST_PORT:String(backendPort)},windowsHide:true,stdio:['ignore','pipe','pipe']});child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>output+=e.message);} async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Error(output);try{if((await fetch(base+'/api/appearance')).ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('server timeout '+output);} async function stop(){if(child&&child.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}} async function preferences(){return (await fetch(base+'/api/appearance')).json();} async function waitPref(predicate){for(let i=0;i<80;i++){const p=await preferences();if(predicate(p))return p;await new Promise(r=>setTimeout(r,100));}throw Error('preferences timeout');} async function setLegacyTheme(page, theme) { const screen = await page.locator("body").getAttribute("data-screen"); const query = await page.locator("#history-query").count() ? await page.locator("#history-query").inputValue() : ""; const current = await preferences(); const response = await fetch(base+'/api/appearance', {method:'PATCH', headers:{'content-type':'application/json'}, body:JSON.stringify({...current, theme})}); assert.equal(response.status, 200); await page.reload(); await page.waitForFunction(t => document.body.dataset.theme === t, theme); if (screen !== await page.locator("body").getAttribute("data-screen")) { if (await page.locator("body").getAttribute("data-screen") !== "home") await page.getByRole("button",{name:"返回应用总览",exact:true}).click(); await page.locator("#home-app-"+screen).click(); } if (query) { await page.locator("#history-query").fill(query); const total=(await (await fetch(base+"/api/records?page=1&q="+encodeURIComponent(query))).json()).total; await page.locator("#page-status").filter({hasText:"共 "+total+" 条"}).waitFor(); } assert.equal(await page.locator('.theme-quick, .theme-cards').count(), 0); assert.equal(await page.locator('body').evaluate(e => getComputedStyle(e).getPropertyValue('--work-panel').trim()), 'rgba(6, 18, 33, .40)'); } try{ await new Promise((resolve,reject)=>{proxy.once('error',reject);proxy.listen(frontendPort,'127.0.0.1',resolve)});start();await ready();browser=await chromium.launch({headless:true,executablePath:process.env.RID_BROWSER_PATH||'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'}); const context=await browser.newContext({viewport:{width:1600,height:1000},acceptDownloads:true});const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(/violates.*Content Security|Refused.*policy/i.test(m.text()))csp.push(m.text());}); for(const asset of ['glass.css','workbench.css'])assert.equal(await (await fetch(base+'/'+asset)).text(), await readFile('crates/web-ui/public/'+asset,'utf8')); await page.goto(base);await page.locator('body[data-screen=home]').waitFor(); assert.equal((await preferences()).wallpaper,'B4'); assert.equal(await page.locator('.home-card').count(),3); assert.equal(await page.locator('.reference-rail').isVisible(),true); assert.equal(await page.locator('#toggle-menu').isVisible(),true); assert.equal(await page.locator('#home-top').count(),0); await page.keyboard.press('Tab');assert.equal(await page.evaluate(()=>document.activeElement.id),'toggle-menu'); await page.locator('#home-app-register').focus(); await page.keyboard.press('Enter');await page.locator('body[data-screen=register]').waitFor(); assert.equal(await page.locator('.reference-rail').isVisible(),true); await page.locator('#toggle-menu').click();assert.equal(await page.locator('.reference-rail').isVisible(),false); await page.getByRole('button',{name:'返回应用总览',exact:true}).click(); assert.equal(await page.evaluate(()=>document.activeElement.id),'home-app-register'); await page.keyboard.press('Tab');await page.keyboard.press('Tab');assert.equal(await page.evaluate(()=>document.activeElement.id),'home-app-settings'); const preferenceLoaded=page.waitForResponse(r=>r.url().endsWith('/api/appearance')&&r.request().method()==='GET'); await page.keyboard.press('Space');await preferenceLoaded;await page.locator('#appearance-view').waitFor(); assert.equal(await page.locator('.reference-rail').isVisible(),false); // home did not reset the user's collapsed navigation. await page.locator('#toggle-menu').click();assert.equal(await page.locator('.reference-rail').isVisible(),true); const homeCases=[],workbenchCases=[]; for(const theme of ['blue','white','graphite']){ await setLegacyTheme(page,theme);assert.equal(await page.locator('body').getAttribute('data-theme'),theme);await page.screenshot({path:path.join(root,'settings-'+theme+'.png')}); await page.getByRole('button',{name:'返回应用总览',exact:true}).click(); assert.equal(await page.evaluate(()=>document.activeElement.id),'home-app-settings'); await page.waitForFunction(()=>[...document.querySelectorAll('.home-app-icon')].every(i=>i.complete&&i.naturalWidth>0)); for(const [width,height] of [[1600,1000],[1366,768],[1080,900],[390,844],[1366,600]]){ await page.setViewportSize({width,height}); assert.equal(await page.locator('.reference-rail').isVisible(),true); const dimensions=await page.locator('.home-launcher').boundingBox();const railWidth=width<=760?56:68;assert.equal(Math.round(dimensions.x),railWidth);assert.equal(Math.round(dimensions.y),48);assert.equal(Math.round(dimensions.width),width-railWidth);assert.equal(Math.round(dimensions.y+dimensions.height),height); assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true); await page.locator('#home-app-settings').scrollIntoViewIfNeeded(); assert.equal(await page.locator('#home-app-settings').isVisible(),true); homeCases.push({theme,width,height}); if(width===1600){await page.mouse.move(1550,20);await page.screenshot({path:path.join(root,'home-'+theme+'.png')});await contrast(page,'home-'+theme,['.home-heading p','.home-card-desc']);} } await page.setViewportSize({width:1600,height:1000});await page.locator('#home-app-settings').click();await page.locator('#appearance-view').waitFor(); } await writeFile(path.join(root,'home-viewport-cases.json'),JSON.stringify(homeCases,null,2)); // Verify materials on both built-in reference wallpapers and a bright custom image. for (const wall of ['B4','B1']) { await page.locator('[data-wall='+wall+']').click();await waitPref(p=>p.wallpaper===wall); await page.waitForFunction(w=>document.getElementById('appearance-wallpaper').src.includes(w+'-wallpaper'),wall); for (const [width,height] of [[1600,1000],[1366,768],[390,844]]) { await page.setViewportSize({width,height}); assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true); await page.screenshot({path:path.join(root,`settings-${wall}-${width}.png`)}); } } await page.setViewportSize({width:1600,height:1000}); // Verify the A workbench columns and all three panels at every breakpoint. for(const [width,height] of [[1600,1000],[1366,600],[1080,900],[820,900],[390,844]]){ await page.setViewportSize({width,height}); for(const screen of ['settings','register']){ if(screen==='register')await page.locator('.reference-rail [data-open=register]').click(); const layoutRoot=page.locator(screen==='settings'?'.settings-layout':'.registry-workspace'); const available=await page.locator(screen==='settings'?'#appearance-view':'#workspace-content').evaluate(e=>e.clientWidth); const columns=available>=1200?3:available>=768?2:1; const actual=await layoutRoot.evaluate(e=>getComputedStyle(e).display==='flex'?1:getComputedStyle(e).gridTemplateColumns.split(' ').length); assert.equal(actual,columns,JSON.stringify({screen,width,available,actual})); assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true); if(screen==='settings'){ assert.equal(await page.locator('.settings-preview').isVisible(),true); const sample=await page.locator('#desktop-sample').boundingBox();assert.equal(Math.round(sample.height),180); await page.locator('#appearance-view').evaluate(e=>e.scrollTop=0); }else{ assert.equal(await page.locator('#registration-result').isVisible(),true); await page.locator('#register-button').scrollIntoViewIfNeeded(); const save=await page.locator('#register-button').boundingBox();assert.ok(save.y>=48&&save.y+save.height<=height+1); await page.locator('#workspace-content').evaluate(e=>e.scrollTop=0); } await page.screenshot({path:path.join(root,`workbench-${screen}-${width}.png`)}); workbenchCases.push({screen,width,height,columns}); } await page.locator('.reference-rail [data-open=settings]').click(); } await page.setViewportSize({width:1600,height:1000}); const savedBeforeSection=await preferences(); await page.locator('[data-setting-section=appearance-display]').click(); assert.equal(await page.evaluate(()=>document.activeElement.id),'appearance-display'); assert.equal((await preferences()).revision,savedBeforeSection.revision); await page.locator('[data-setting-section=appearance-wallpapers]').click(); let failAppearance=true; await page.route('**/api/appearance',route=>{if(route.request().method()==='PATCH'&&failAppearance){failAppearance=false;return route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:'隔离外观保存失败'})})}return route.continue()}); await page.locator('#dim').fill('35');await page.locator('#dim').dispatchEvent('input'); await page.locator('#wall-message.error').filter({hasText:'隔离外观保存失败'}).waitFor(); assert.equal((await preferences()).dim,savedBeforeSection.dim); assert.equal(await page.locator('#appearance-dim-value').innerText(),savedBeforeSection.dim+'%'); await page.unroute('**/api/appearance'); await page.locator('[data-wall=B2]').click();await waitPref(p=>p.wallpaper==='B2');await page.locator('#dim').fill('28');await page.locator('#dim').dispatchEvent('input');await waitPref(p=>p.dim===28); assert.equal(await page.locator('#appearance-dim-value').innerText(),'28%'); await page.locator('#blur').fill('3');await page.locator('#blur').dispatchEvent('input');await waitPref(p=>p.blur===3); assert.equal(await page.locator('#appearance-blur-value').innerText(),'3 px'); assert.equal(await page.locator('#desktop-sample').evaluate(e=>e.style.getPropertyValue('--preview-blur')),'3px'); assert.equal(await page.locator('#desktop-sample').evaluate(e=>e.style.getPropertyValue('--preview-shade')),'0.28'); await page.locator('#fit').selectOption('contain');await waitPref(p=>p.fit==='contain');assert.equal(await page.locator('#appearance-fit-value').innerText(),'完整显示'); assert.equal(await page.locator('#appearance-wallpaper').evaluate(e=>getComputedStyle(e).objectFit),'contain'); await page.locator('#fit').selectOption('cover');await waitPref(p=>p.fit==='cover'); await page.locator('#blur').fill('0');await page.locator('#blur').dispatchEvent('input');await waitPref(p=>p.blur===0); const picture=await page.screenshot();await page.locator('#custom-wallpaper').setInputFiles({name:'wallpaper.png',mimeType:'image/png',buffer:picture});const uploaded=await waitPref(p=>p.image?.startsWith('data:image/jpeg')); const second=await browser.newContext();const other=await second.newPage();await other.goto(base);await other.waitForFunction(()=>document.querySelector('#workspace-wallpaper').src.startsWith('data:image/jpeg'));assert.equal(await other.locator('body').getAttribute('data-theme'),'graphite');await second.close(); const stale=await fetch(base+'/api/appearance',{method:'PATCH',headers:{'content-type':'application/json'},body:JSON.stringify({...uploaded,revision:0})});assert.equal(stale.status,400); const invalid=await fetch(base+'/api/appearance',{method:'PATCH',headers:{'content-type':'application/json'},body:JSON.stringify({...uploaded,image:'data:image/png;base64,bm90LWEtcG5n'})});assert.equal(invalid.status,400);assert.equal((await preferences()).revision,uploaded.revision); await page.locator('#custom-wallpaper').setInputFiles({name:'bad.txt',mimeType:'text/plain',buffer:Buffer.from('bad')});await page.locator('#wall-message.error').waitFor();assert.equal((await preferences()).revision,uploaded.revision); const brightImage=Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4//8/AAX+Av4N70a4AAAAAElFTkSuQmCC','base64'); await page.locator('#custom-wallpaper').setInputFiles({name:'bright.png',mimeType:'image/png',buffer:brightImage}); await waitPref(p=>p.image!==uploaded.image&&p.image?.startsWith('data:image/jpeg')); await page.locator('#dim').fill('0');await page.locator('#dim').dispatchEvent('input');await waitPref(p=>p.dim===0); await page.waitForFunction(()=>{const i=document.getElementById('workspace-wallpaper');return i.complete&&i.naturalWidth>0&&i.clientWidth===innerWidth&&i.clientHeight===innerHeight}); await page.screenshot({path:path.join(root,'settings-bright.png')}); await contrast(page,'white-wallpaper-dim0',['.micro','.section-caption span','.reference-local'],false); await page.locator('#dim').fill('28');await page.locator('#dim').dispatchEvent('input');await waitPref(p=>p.dim===28); await contrast(page,'white-wallpaper-dim28',['.micro','.section-caption span','.reference-local']); await page.screenshot({path:path.join(root,'settings-bright-dim28.png')}); await page.getByRole('button',{name:'返回应用总览',exact:true}).click(); await page.screenshot({path:path.join(root,'home-bright.png')}); await contrast(page,'white-wallpaper-home-dim28',['.home-heading p','.home-card-desc']); await page.locator('#home-app-register').click(); await page.screenshot({path:path.join(root,'registry-bright.png')}); await page.getByRole('button',{name:'返回应用总览',exact:true}).click(); await page.locator('#home-app-settings').click(); await page.locator('#reset-wallpaper').click();await waitPref(p=>p.image===null&&p.dim===14&&p.wallpaper==='B4'); await page.locator('.reference-rail [data-open=register]').click();await page.locator('#serial-no').fill('LIVE-UI-0001');await page.locator('#model-name').fill('验收机型');await page.getByRole('button',{name:'返回应用总览',exact:true}).click();await page.locator('#home-app-settings').click();await page.getByRole('button',{name:'返回应用总览',exact:true}).click();await page.locator('#home-app-register').click();assert.equal(await page.locator('#serial-no').inputValue(),'LIVE-UI-0001');assert.equal(await page.locator('#model-name').inputValue(),'验收机型');await page.locator('#owner-name').fill('隔离数据');await page.locator('#register-button').click();await page.locator('#form-message').filter({hasText:'登记成功'}).waitFor();await page.locator('#qr-stage svg').waitFor();assert.equal((await (await fetch(base+'/api/records?q=LIVE-UI-0001')).json()).records.length,1); const card=page.locator('.archive-card').filter({has:page.getByRole('heading',{name:'LIVE-UI-0001',exact:true})});await card.locator('.archive-more').click();await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.screenshot({path:path.join(root,'edit-dialog.png')});await page.locator('#edit-owner').fill('已修改');await page.locator('#edit-save').click();await page.locator('#edit-dialog').waitFor({state:'hidden'});assert.equal((await (await fetch(base+'/api/records?q=LIVE-UI-0001')).json()).records[0].ownerName,'已修改');await page.screenshot({path:path.join(root,'registry-saved.png')});await page.locator('#new-registration').click();assert.equal(await page.locator('#serial-no').inputValue(),''); await page.locator('#selection-toggle').click();await page.check('#select-all');const download=page.waitForEvent('download');await page.locator('#export-toggle').click();await page.locator('#export-excel').click();await (await download).saveAs(path.join(root,'records.xlsx')); await page.screenshot({path:path.join(root,'registry.png')}); await page.locator('.reference-rail [data-open=realtime]').click();await page.waitForURL('**/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();assert.equal(await page.locator('.mc-map-toolstrip').count(),0);await page.waitForFunction(()=>window.ridMap?.metrics().mapReady);assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.pitch),0);assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.bearing),0);assert.equal(await page.locator('.rt-target').count(),0);assert.ok(await page.locator('.maplibregl-canvas').count()); const frames=Array.from({length:3},(_,i)=>({target_id:i===0?'LIVE-UI-0001':'LIVE-TARGET-'+i,receiver_id:'TEST',source_epoch:1,sequence:1,longitude:120+i*.001,latitude:30+i*.001,altitude_m:45+i,heading_deg:85}));const response=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(frames)});assert.equal(response.status,200);await page.locator('.rt-target').filter({hasText:'LIVE-UI-0001'}).click();await page.locator('.rt-details').filter({hasText:'已匹配本地登记档案'}).waitFor();await page.locator('.rt-details').filter({hasText:'120.000000'}).waitFor(); await page.getByTitle('收起目标目录',{exact:true}).click();assert.equal(await page.locator('.live-targets').isVisible(),false);await page.getByTitle('显示目标目录',{exact:true}).click();assert.equal(await page.locator('.live-targets').isVisible(),true);await page.getByRole('button',{name:'接收器与解码',exact:true}).click();await page.locator('.rt-receiver-body').waitFor();await page.getByRole('button',{name:'目标快照与事件',exact:true}).click(); await page.waitForFunction(()=>window.ridMap?.metrics().mapReady&&window.ridMap.metrics().targets===3).catch(async e=>{console.log('MAP_DIAGNOSTIC',await page.evaluate(()=>window.ridMap?.metrics()));await page.screenshot({path:path.join(root,'map-failed.png')});throw e}); const mapMetrics=await page.evaluate(()=>window.ridMap.metrics()); assert.ok(mapMetrics.mapCanvasWidth>1000&&mapMetrics.mapCanvasHeight>700,JSON.stringify(mapMetrics)); assert.ok(!(await page.locator('body').textContent()).includes('filtered.get()')); await writeFile(path.join(root,'map-metrics.json'),JSON.stringify(mapMetrics,null,2)); await page.screenshot({path:path.join(root,'realtime-B.png')}); await page.locator('.live-detail a').click();await page.waitForURL('**/?app=register&q=LIVE-UI-0001');await page.locator('#page-status').filter({hasText:'共 1 条'}).waitFor();assert.equal(await page.locator('#history-query').inputValue(),'LIVE-UI-0001');await page.locator('.reference-rail [data-open=realtime]').click();await page.waitForURL('**/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor(); for(const[width,height]of [[1600,1000],[1366,768],[1080,900],[390,844]]){await page.setViewportSize({width,height});for(const theme of ['graphite','blue','white']){await setLegacyTheme(page,theme);const box=await page.locator('#workspace-content').boundingBox();assert.equal(Math.round(box.y),48);assert.equal(Math.round(box.x+box.width),width);assert.equal(Math.round(box.y+box.height),height);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);}await page.screenshot({path:path.join(root,`realtime-${width}.png`)});} await page.setViewportSize({width:1600,height:1000});await page.locator('.reference-rail [data-open=settings]').click();await page.locator('[data-wall=B1]').click();await waitPref(p=>p.wallpaper==='B1');await stop();start();await ready();assert.equal((await preferences()).wallpaper,'B1');await page.reload();await page.waitForFunction(()=>document.getElementById('workspace-wallpaper').src.includes('B1-wallpaper')); assert.deepEqual(errors,[]);assert.deepEqual(csp,[]); await writeFile(path.join(root,'report.json'),JSON.stringify({status:'PASS',root,errors,csp,contrastCases,workbenchCases,scenarios:['B1 home: three accessible cards, keyboard activation and return focus','shared home navigation preserves menu state and return focus','15 home viewport/theme cases','B4 first-use and reset default','real Rust/Wasm','three legacy values share A+C material','application DB preferences across independent browser contexts and server restart','custom wallpaper and invalid file rollback','stale settings update rejected','register/edit/QR/XLSX','actual Worker websocket and synthetic ingress','no fabricated empty targets','real local registration matching','overlay collapse','receiver controls','four viewport sizes']},null,2));console.log(JSON.stringify({status:'PASS',root})); }finally{if(browser)await browser.close();await stop();for(const socket of sockets)socket.destroy();await new Promise(r=>proxy.close(r));await writeFile(path.join(root,'server.log'),output);}