// Real Rust/Wasm acceptance in an isolated database. Never opens receiver transports. import {mkdtemp,writeFile} 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 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');} 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());}); 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(),false); assert.equal(await page.locator('#toggle-menu').isVisible(),false); assert.equal(await page.locator('#home-top').isVisible(),true); await page.keyboard.press('Tab');assert.equal(await page.evaluate(()=>document.activeElement.id),'home-app-register'); 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=[]; for(const theme of ['blue','white','graphite']){ await page.locator('.theme-quick [data-theme='+theme+']').click();await waitPref(p=>p.theme===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(),false); const dimensions=await page.locator('.home-launcher').boundingBox();assert.equal(Math.round(dimensions.x),0);assert.equal(Math.round(dimensions.y),48);assert.equal(Math.round(dimensions.width),width);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 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)); 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); 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); 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.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.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.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('.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 page.locator('.theme-quick [data-theme='+theme+']').click();await waitPref(p=>p.theme===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,scenarios:['B1 home: three accessible cards, keyboard activation and return focus','home hides navigation and preserves module collapse state','15 home viewport/theme cases','B4 first-use and reset default','real Rust/Wasm','three themes','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);}