// Real SQLite, Rust/Wasm, Worker and WebGL acceptance. No physical transports opened. import {mkdtemp,readFile,writeFile} from 'node:fs/promises'; import {tmpdir} from 'node:os'; import path from 'node:path'; import http from 'node:http'; import net from 'node:net'; import {spawn} from 'node:child_process'; import {createRequire} from 'node:module'; import assert from 'node:assert/strict'; const {chromium}=createRequire(import.meta.url)('playwright'); const root=await mkdtemp(path.join(tmpdir(),'RID-target-lists-')); const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe'; const probe=net.createServer();await new Promise(r=>probe.listen(0,'127.0.0.1',r));const backend=probe.address().port;await new Promise(r=>probe.close(r)); let base,child,browser,heartbeat,output='';const errors=[],csp=[],sockets=new Set(); const proxy=http.createServer(async(req,res)=>{if(process.env.RID_SOURCE_ASSETS==='1'&&!req.url.startsWith('/api/')){const pathname=new URL(req.url,'http://localhost').pathname;const relative=pathname==='/'||pathname==='/realtime'?'index.html':pathname.slice(1);if(!relative.includes('..'))try{let bytes;try{bytes=await readFile(path.join('crates/web-ui/public',relative));}catch{bytes=await readFile(path.join('dist/web-ui',relative));}res.writeHead(200,{'content-type':relative.endsWith('.html')?'text/html':relative.endsWith('.css')?'text/css':relative.endsWith('.wasm')?'application/wasm':relative.endsWith('.svg')?'image/svg+xml':relative.endsWith('.png')?'image/png':'text/javascript'});res.end(bytes);return}catch{}}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:backend,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(backend,'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';const nl=String.fromCharCode(13,10);upstream.write(['GET '+req.url+' HTTP/1.1',...Object.entries(headers).map(([k,v])=>k+': '+v),'',''].join(nl));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)})}); const wait=ms=>new Promise(r=>setTimeout(r,ms)); function start(){child=spawn(exe,['--data-root',root,'--simulation-api'],{env:{...process.env,RID_TEST_PORT:String(backend),PATH:'C:\\Windows\\System32'},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 stop(){if(child&&child.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done}} async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Error(output);try{if((await fetch(base+'/api/target-lists')).ok)return}catch{}await wait(100)}throw Error('server timeout '+output)} async function snapshot(){return(await fetch(base+'/api/target-lists')).json()} async function save(id,kind,note='验收备注'){const current=await snapshot();const r=await fetch(base+'/api/target-lists/'+id,{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({list_kind:kind,note,expected_revision:current.revision})});assert.equal(r.status,200);return r.json()} let sequence=0;const targetIds=['LIST-WHITE','LIST-BLACK','LIST-OTHER']; async function ingest(){sequence++;const frames=targetIds.map((target_id,i)=>({target_id,receiver_id:'TEST',source_epoch:1,sequence,longitude:120.15+i*.001,latitude:30.28+i*.001,altitude_m:100,heading_deg:40}));const r=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(frames)});assert.equal(r.status,200)} let report={}; try{ await new Promise(r=>proxy.listen(0,'127.0.0.1',r));base='http://127.0.0.1:'+proxy.address().port;start();await ready(); assert.deepEqual((await snapshot()).entries,[]); await save('LIST-WHITE','white');await save('LIST-BLACK','black');await save('OFFLINE_001','white'); for(const file of ['target-lists.css','map-adapter.js'])assert.equal(await(await fetch(base+'/'+file)).text(),await readFile(path.join('dist/web-ui',file),'utf8')); browser=await chromium.launch({headless:true,channel:'msedge'});const context=await browser.newContext({viewport:{width:1600,height:1000}});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+'/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await page.locator('#rt-dock-restore').click(); const filters=page.getByRole('group',{name:'目标名单筛选'}); await page.waitForFunction(()=>![...document.querySelectorAll('.rt-target-list-filters button')].some(b=>b.disabled)); await ingest();heartbeat=setInterval(()=>ingest().catch(()=>{}),3000); await page.getByRole('button',{name:'LIST-BLACK',exact:true}).waitFor();await page.waitForFunction(()=>window.ridMap?.metrics().mapReady&&window.ridMap.metrics().classifiedTargets.black===1); assert.equal(await page.getByRole('button',{name:'LIST-WHITE',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'white'); assert.equal(await page.getByRole('button',{name:'LIST-OTHER',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'unknown'); const blackEvents=()=>page.locator('.live-events li[data-alert=true]').filter({hasText:'LIST-BLACK'}); await blackEvents().waitFor();for(let i=0;i<5;i++)await ingest();await wait(500);assert.equal(await blackEvents().count(),1); await page.getByRole('button',{name:'LIST-BLACK',exact:true}).click();await page.locator('.rt-detail-classification').waitFor(); await page.screenshot({path:path.join(root,'classified-workspace.png')}); await filters.getByRole('button',{name:/^白名单/}).click();await page.waitForFunction(()=>window.ridMap.metrics().visibleTargets===1);assert.equal(await page.locator('.rt-target').count(),1);assert.equal(await page.evaluate(()=>window.ridMap.metrics().targets),3); await filters.getByRole('button',{name:/^全部/}).click();await page.getByRole('button',{name:'LIST-WHITE',exact:true}).click(); await page.getByRole('button',{name:'加入黑名单',exact:true}).click(); await page.waitForFunction(()=>window.ridMap.metrics().classifiedTargets.black===2);assert.equal(await page.getByRole('button',{name:'LIST-WHITE',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'black'); await page.locator('.rt-detail-classification').getByRole('button',{name:'加入黑名单',exact:true}).click();await wait(350); await page.locator('.live-events li[data-alert=true]').filter({hasText:'LIST-WHITE'}).waitFor(); assert.equal(await page.locator('.live-events li[data-alert=true]').filter({hasText:'LIST-WHITE'}).count(),1); await page.getByRole('button',{name:'管理黑白名单',exact:true}).click();await page.locator('#rt-list-manager').waitFor();assert.equal((await page.locator('#rt-list-manager').innerText()).includes('rows.get'),false);assert.equal(await page.locator('.rt-list-pagination').getByRole('button',{name:'下一页',exact:true}).isDisabled(),true); await page.getByRole('button',{name:'新增条目',exact:true}).click();await page.locator('#rt-list-entry-id').fill('OFFLINE_002');await page.locator('#rt-list-entry-kind').selectOption('white');await page.locator('#rt-list-entry-note').fill('离线条目');await page.locator('#rt-list-entry-form .primary').click(); await page.locator('.rt-list-manager-footer').filter({hasText:'已将 OFFLINE_002 保存为白名单'}).waitFor();assert.equal(await page.evaluate(()=>window.ridMap.metrics().targets),3); assert.equal((await(await fetch(base+'/api/records?page=1')).json()).total,0); const offline=page.locator('.rt-list-row[data-target-id=OFFLINE_002]');await offline.getByRole('button',{name:'编辑',exact:true}).click();assert.equal(await page.locator('#rt-list-entry-id').isEditable(),false); await page.locator('#rt-list-entry-note').fill('人工备注');await page.locator('#rt-list-entry-form .primary').click();await offline.filter({hasText:'人工备注'}).waitFor();assert.equal(await offline.locator('img').count(),0); const otherContext=await browser.newContext({viewport:{width:1280,height:900}}),other=await otherContext.newPage();await other.goto(base+'/realtime');await other.waitForFunction(()=>![...document.querySelectorAll('.rt-target-list-filters button')].some(b=>b.disabled)); await other.getByRole('button',{name:'管理黑白名单',exact:true}).click();await other.locator('.rt-list-row[data-target-id=OFFLINE_002]').filter({hasText:'人工备注'}).waitFor(); await page.locator('#rt-list-entry-note').fill('尚未保存的备注');await save('OFFLINE_002','white','来自其他浏览器'); await offline.filter({hasText:'来自其他浏览器'}).waitFor({timeout:12000});assert.equal(await page.locator('#rt-list-entry-note').inputValue(),'尚未保存的备注'); await page.getByRole('button',{name:'新增条目',exact:true}).click();await page.locator('#rt-list-entry-id').fill('LIST-OTHER');await page.locator('#rt-list-entry-note').fill('冲突后保留草稿'); let releaseRequest,heldRequest;const gate=new Promise(r=>releaseRequest=r),held=new Promise(r=>heldRequest=r);let intercept=true; await page.route('**/api/target-lists/LIST-OTHER',async route=>{if(route.request().method()==='PUT'&&intercept){intercept=false;heldRequest();await gate;}await route.continue()}); await page.locator('#rt-list-entry-form .primary').click();await held;assert.equal(await page.locator('#rt-list-entry-id').isDisabled(),true);await save('REMOTE_001','white');releaseRequest(); await page.locator('.rt-list-manager-footer p.error').filter({hasText:'其他页面修改'}).waitFor();await page.locator('.rt-list-row[data-target-id=REMOTE_001]').waitFor();assert.equal(await page.locator('#rt-list-entry-note').inputValue(),'冲突后保留草稿'); await page.unroute('**/api/target-lists/LIST-OTHER');await page.locator('#rt-list-entry-form .primary').click();await page.locator('.rt-list-row[data-target-id=LIST-OTHER]').waitFor(); await page.locator('#rt-list-entry-note').fill('保存失败仍保留');await page.route('**/api/target-lists/LIST-OTHER',r=>r.fulfill({status:500,contentType:'application/json',body:JSON.stringify({error:'隔离保存失败'})})); await page.locator('#rt-list-entry-form .primary').click();await page.locator('.rt-list-manager-footer p.error').filter({hasText:'隔离保存失败'}).waitFor();assert.equal(await page.locator('#rt-list-entry-note').inputValue(),'保存失败仍保留');assert.equal((await snapshot()).entries.find(e=>e.target_id==='LIST-OTHER').note,'冲突后保留草稿');await page.unroute('**/api/target-lists/LIST-OTHER'); await page.getByRole('button',{name:'新增条目',exact:true}).click();await page.locator('#rt-list-entry-id').fill('bad id');await page.locator('#rt-list-entry-form').evaluate(f=>f.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true})));await page.locator('.rt-list-manager-footer p.error').filter({hasText:'目标标识须'}).waitFor(); await page.screenshot({path:path.join(root,'manager-validation.png')}); await page.locator('.rt-list-row[data-target-id=LIST-OTHER]').getByRole('button',{name:'移除',exact:true}).click();await page.waitForFunction(()=>window.ridMap.metrics().classifiedTargets.black===2); await page.route('**/api/target-lists?revision=*',r=>r.fulfill({status:503,contentType:'application/json',body:'{}'})); await page.locator('#rt-list-manager .rt-list-sync-error').filter({hasText:'暂用上次名单'}).waitFor({timeout:12000}); assert.equal(await page.evaluate(()=>window.ridMap.metrics().classifiedTargets.black),2); await page.unroute('**/api/target-lists?revision=*');await page.locator('#rt-list-manager .rt-list-sync-error').getByRole('button',{name:'重试',exact:true}).click();await page.locator('#rt-list-manager .rt-list-sync-error').waitFor({state:'hidden'}); const unavailableContext=await browser.newContext(),unavailable=await unavailableContext.newPage(); await unavailable.route('**/api/target-lists**',r=>r.fulfill({status:503,contentType:'application/json',body:'{}'}));await unavailable.goto(base+'/realtime'); await unavailable.locator('#rt-directory .rt-list-sync-error').filter({hasText:'名单读取失败'}).waitFor();await unavailable.locator('.rt-target').first().waitFor(); assert.equal(await unavailable.locator('.rt-target .rt-list-badge[data-kind=unavailable]').count(),3); assert.equal(await unavailable.getByRole('group',{name:'目标名单筛选'}).getByRole('button',{name:/^黑名单/}).isDisabled(),true);assert.ok((await unavailable.getByRole('group',{name:'目标名单筛选'}).getByRole('button',{name:/^黑名单/}).innerText()).includes('—')); await unavailableContext.close(); const sizes=[[1600,1000],[1366,600],[1080,900],[390,844]];const geometry=[]; for(const [width,height]of sizes){await page.setViewportSize({width,height});await wait(250);await page.locator('#rt-list-entry-form .primary').scrollIntoViewIfNeeded();const box=await page.locator('#rt-list-entry-form .primary').boundingBox();assert.ok(box.x>=0&&box.x+box.width<=width&&box.y>=48&&box.y+box.height<=height+1);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.locator('.rt-list-manager-body').evaluate(e=>e.scrollTop=0);await page.screenshot({path:path.join(root,'manager-'+width+'.png')});geometry.push({width,height})} await page.setViewportSize({width:1280,height:720});await page.evaluate(()=>document.documentElement.style.zoom='2');await page.locator('#rt-list-entry-form .primary').scrollIntoViewIfNeeded();assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:path.join(root,'manager-zoom200.png')});await page.evaluate(()=>document.documentElement.style.zoom=''); await page.keyboard.press('Escape');await page.locator('#rt-list-manager').waitFor({state:'hidden'});await page.waitForFunction(()=>['rt-list-manager-open','rt-list-manager-from-directory'].includes(document.activeElement.id)); await page.setViewportSize({width:1600,height:1000});await otherContext.close(); const persisted=await snapshot();clearInterval(heartbeat);await stop();start();await ready();assert.deepEqual(await snapshot(),persisted); await page.reload();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await ingest();await page.waitForFunction(()=>window.ridMap.metrics().targets===3&&window.ridMap.metrics().classifiedTargets.black===2);assert.equal(await page.getByRole('button',{name:'LIST-OTHER',exact:true}).locator('.rt-list-badge').getAttribute('data-kind'),'unknown'); // Registration remains independent: registered targets are not automatically trusted. for(const [id,expectedKind]of [['LIST-BLACK','black'],['LIST-OTHER','unknown']]){ const response=await fetch(base+'/api/records',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({serialNo:id})});assert.equal(response.status,200);const record=(await response.json()).record; await page.getByRole('button',{name:id,exact:true}).click();await page.locator('.rt-details').filter({hasText:'已匹配本地登记档案'}).waitFor(); assert.equal(await page.locator('.rt-detail-classification .rt-list-badge').getAttribute('data-kind'),expectedKind); assert.equal((await fetch(base+'/api/records/'+record.id,{method:'DELETE'})).status,200); } assert.equal((await snapshot()).entries.find(e=>e.target_id==='LIST-BLACK').list_kind,'black'); assert.equal(await page.locator('.mc-map-toolstrip').count(),0);assert.equal(await page.evaluate(()=>window.ridMap.metrics().camera.pitch),0); assert.deepEqual(errors,[]);assert.deepEqual(csp,[]); report={status:'PASS',root,exe,geometry,errors,csp,revision:persisted.revision,entries:persisted.entries.length,checks:['exact persisted membership independent of registration','online quick marking and offline entry','map and directory filtering without telemetry loss','black alert deduplication','safe notes and reactive remote updates','cross-browser sync preserves unsaved draft','optimistic concurrency and failed save rollback','busy controls and ID validation','removal restores unclassified','four viewports and 200% zoom','escape return focus','restart persistence','failed initial load and stale snapshot recovery','topdown map and removed toolbar preserved']};console.log(JSON.stringify(report)); }catch(error){console.log('FAILED ROOT',root,error.stack,JSON.stringify({errors,csp}));if(browser){const p=browser.contexts()[0]?.pages()[0];if(p)console.log('MAP',await p.evaluate(()=>window.ridMap?.metrics()).catch(()=>null));}if(browser){const p=browser.contexts()[0]?.pages()[0];if(p)await p.screenshot({path:path.join(root,'failure.png')}).catch(()=>{});}throw error;}finally{clearInterval(heartbeat);if(browser)await browser.close();await stop();for(const socket of sockets)socket.destroy();const closed=new Promise(r=>proxy.close(r));proxy.closeAllConnections();await closed;await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));await writeFile(path.join(root,'server.log'),output)}