feat(web-ui): 新增首页启动器与地图遮挡感知交互

- 添加首页卡片式应用启动器界面,包含实时视图、登记、
  设置三个入口及对应 SVG 图标资源
- 地图组件新增 ResizeObserver 自动适配容器尺寸变化
- 地图组件引入遮挡区域(occlusion)管理,聚焦时自动
  计算可见填充偏移,避免目标被面板遮挡
- 将地图加载事件从 load 改为 style.load,提升初始化
  可靠性
- 扩展 metrics 接口,返回选中目标像素坐标、遮挡状态、
  画布尺寸等运行时诊断信息
- 补充 web-sys features(HtmlImageElement, Storage,
  PointerEvent, DomRect 等)以支持新 UI 交互
- index.html 新增 workspace/home/registry 样式及资源引用
- .gitignore 忽略 previews 目录与本地编译产物
```
This commit is contained in:
2026-10-22 13:43:58 +08:00
parent 1dfcdb619c
commit 91059cf395
44 changed files with 2787 additions and 3390 deletions
+8 -8
View File
@@ -16,26 +16,26 @@ await mkdir(path.join(root,'registry/data'),{recursive:true});
const db=new DatabaseSync(path.join(root,'registry/data/registry.sqlite'));
db.exec("CREATE TABLE records(id TEXT PRIMARY KEY,serial_no TEXT NOT NULL UNIQUE,uas_code TEXT NOT NULL UNIQUE,model_name TEXT NOT NULL DEFAULT '',owner_name TEXT NOT NULL DEFAULT '',created_at TEXT NOT NULL); CREATE TABLE photos(record_id TEXT NOT NULL REFERENCES records(id) ON DELETE CASCADE,slot INTEGER NOT NULL CHECK(slot IN(1,2)),mime_type TEXT NOT NULL,image BLOB NOT NULL,PRIMARY KEY(record_id,slot));");
for(let i=1;i<=21;i++)db.prepare('INSERT INTO records VALUES(?,?,?,?,?,?)').run(String(i).padStart(36,'0'),`BROWSER-${String(i).padStart(3,'0')}`,`FPV${String(i).padStart(8,'0')}`,'演示机型','验收数据','2020-01-01T00:00:00.000Z');db.close();
const png=Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aocsAAAAASUVORK5CYII=','base64');
const png=Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAEElEQVR4nGMImHERiBggFAAuRgblSRFDagAAAABJRU5ErkJggg==','base64');
const child=spawn(exe,['--data-root',root],{windowsHide:true,env:{...process.env,PATH:'C:\\Windows\\System32'},stdio:['ignore','pipe','pipe']});let output='';let spawnError;
child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>spawnError=e);
let browser;
try{
for(let i=0;i<150;i++){if(spawnError||child.exitCode!==null)throw Error(output||String(spawnError));try{if((await fetch(base+'/api/records')).ok)break;}catch{}await new Promise(r=>setTimeout(r,100));}
browser=await chromium.launch({headless:true,executablePath:process.env.RID_BROWSER_PATH||undefined});const page=await browser.newPage({viewport:{width:1366,height:1000},acceptDownloads:true});let errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.goto(base);await page.locator('#page-status').filter({hasText:'共 21 条'}).waitFor();
await page.goto(base+'/?app=register');await page.locator('#page-status').filter({hasText:'共 21 条'}).waitFor();
await page.fill('#serial-no','UI-NEW-001');await page.fill('#model-name','待清空机型');await page.fill('#owner-name','原登记人');await page.setInputFiles('#photo-1',{name:'photo.png',mimeType:'image/png',buffer:png});await page.click('#register-button');await page.locator('#form-message').filter({hasText:'登记成功'}).waitFor();
const card=page.locator('.archive-card').filter({has:page.getByRole('heading',{name:'UI-NEW-001',exact:true})});
await card.getByRole('button',{name:'编辑资料 / 照片'}).click();assert.equal(await page.locator('#edit-model').evaluate(el=>el===document.activeElement),true);await page.click('#edit-cancel');assert.equal(await page.locator('#edit-dialog').isVisible(),false);
await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.fill('#edit-model','');await page.fill('#edit-owner','修改后的登记人');await page.check('#edit-delete-1');await page.setInputFiles('#edit-photo-2',{name:'new.png',mimeType:'image/png',buffer:png});
await card.locator('.archive-more').click();await card.getByRole('button',{name:'编辑资料 / 照片'}).click();assert.equal(await page.locator('#edit-model').evaluate(el=>el===document.activeElement),true);await page.click('#edit-cancel');assert.equal(await page.locator('#edit-dialog').isVisible(),false);
await card.locator('.archive-more').click();await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.fill('#edit-model','');await page.fill('#edit-owner','修改后的登记人');await page.check('#edit-delete-1');await page.setInputFiles('#edit-photo-2',{name:'new.png',mimeType:'image/png',buffer:png});
let patches=0;const listener=req=>{if(req.method()==='PATCH')patches++;};page.on('request',listener);await page.click('#edit-save');await page.locator('#edit-dialog').waitFor({state:'hidden'});assert.equal(patches,1);page.off('request',listener);
let records=(await (await fetch(base+'/api/records')).json()).records;let r=records.find(r=>r.serialNo==='UI-NEW-001');assert.equal(r.modelName,'');assert.equal(r.ownerName,'修改后的登记人');assert.equal(r.photo1Url,null);assert.ok(r.photo2Url);
await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.fill('#edit-owner','不得保存');await page.setInputFiles('#edit-photo-1',{name:'bad.png',mimeType:'image/png',buffer:Buffer.from('invalid image')});await page.click('#edit-save');await page.locator('#edit-message').filter({hasText:'照片内容与格式不符'}).waitFor();assert.equal((await(await fetch(base+'/api/records')).json()).records.find(item=>item.id===r.id).ownerName,'修改后的登记人');await page.keyboard.press('Escape');
await card.locator('.archive-more').click();await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.fill('#edit-owner','不得保存');await page.setInputFiles('#edit-photo-1',{name:'bad.png',mimeType:'image/png',buffer:Buffer.from('invalid image')});await page.click('#edit-save');await page.locator('#edit-message').filter({hasText:'照片内容与格式不符'}).waitFor();assert.equal((await(await fetch(base+'/api/records')).json()).records.find(item=>item.id===r.id).ownerName,'修改后的登记人');await page.keyboard.press('Escape');
await page.click('#next-page');await page.locator('#page-status').filter({hasText:'第 2 / 2 页'}).waitFor();assert.equal(await page.locator('.archive-card').count(),2);
await page.fill('#history-query','UI-NEW-001');await page.locator('#page-status').filter({hasText:'第 1 / 1 页'}).waitFor();assert.equal(await page.locator('.archive-card').count(),1);
await page.fill('#history-query','');await page.locator('#page-status').filter({hasText:'共 22 条'}).waitFor();await page.check('#select-all');assert.equal(await page.locator('.archive-select input:checked').count(),20);
const downloadPromise=page.waitForEvent('download');const exportRequest=page.waitForRequest(req=>req.url().endsWith('/api/export/excel'));await page.click('#export-excel');assert.equal((await exportRequest).postDataJSON().ids.length,20);const download=await downloadPromise;await download.saveAs(path.join(root,'browser-export.xlsx'));
await page.screenshot({path:path.join(root,'desktop.png'),fullPage:true});await page.setViewportSize({width:390,height:844});await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.screenshot({path:path.join(root,'mobile-dialog.png'),fullPage:false});
await page.fill('#history-query','');await page.locator('#page-status').filter({hasText:'共 22 条'}).waitFor();await page.locator('#selection-toggle').click();await page.check('#select-all');assert.equal(await page.locator('.archive-select input:checked').count(),20);
const downloadPromise=page.waitForEvent('download');const exportRequest=page.waitForRequest(req=>req.url().endsWith('/api/export/excel'));await page.click('#export-toggle');await page.click('#export-excel');assert.equal((await exportRequest).postDataJSON().ids.length,20);const download=await downloadPromise;await download.saveAs(path.join(root,'browser-export.xlsx'));
await page.screenshot({path:path.join(root,'desktop.png'),fullPage:true});await page.setViewportSize({width:390,height:844});await card.locator('.archive-more').click();await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.screenshot({path:path.join(root,'mobile-dialog.png'),fullPage:false});
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth),true);assert.equal(await page.locator('#edit-dialog').evaluate(el=>el.getBoundingClientRect().right<=innerWidth),true);assert.deepEqual(errors,[]);
console.log(JSON.stringify({status:'PASS',root,scenarios:['real Rust without Node PATH','registration and photo','cancel','focus','atomic edit','invalid photo rollback','pagination','search resets page','current-page selection and XLSX download','desktop and narrow viewport','no browser errors']}));
}finally{if(browser)await browser.close();if(child.exitCode===null&&!spawnError){const exit=new Promise(r=>child.once('exit',r));child.kill();await exit;}await writeFile(path.join(root,'server.log'),output);}
+1 -1
View File
@@ -13,7 +13,7 @@ try{
let ready=false;for(let i=0;i<150;i++){if(failure||child.exitCode!==null)throw Error(output||String(failure));try{if((await fetch(base)).ok){ready=true;break;}}catch{}await new Promise(r=>setTimeout(r,100));}assert.ok(ready);
browser=await chromium.launch({headless:true,executablePath:process.env.RID_BROWSER_PATH||'C:/Program Files/Google/Chrome/Application/chrome.exe'});const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));let fail=false;
await page.route('**/api/records?**',async route=>{const u=new URL(route.request().url());if(u.searchParams.get('q')==='old')await new Promise(r=>setTimeout(r,800));if(fail){fail=false;await route.fulfill({status:500,contentType:'application/json',body:JSON.stringify({error:'network failure'})});return;}await route.fulfill({status:200,contentType:'application/json',body:JSON.stringify({records:[],page:Number(u.searchParams.get('page')),pageSize:20,total:u.searchParams.get('q')==='old'?999:45,totalPages:3})});});
await page.goto(base);await page.locator('#page-status').filter({hasText:'第 1 / 3 页'}).waitFor();
await page.goto(base+'/?app=register');await page.locator('#page-status').filter({hasText:'第 1 / 3 页'}).waitFor();
fail=true;await page.click('#next-page');await page.locator('#history-message').filter({hasText:'network failure'}).waitFor();assert.match(await page.locator('#page-status').textContent(),/第 1/);assert.equal(await page.locator('#next-page').isEnabled(),true);
await page.click('#next-page');await page.locator('#page-status').filter({hasText:'第 2 / 3 页'}).waitFor();
await page.fill('#history-query','old');await page.waitForRequest(r=>r.url().includes('q=old'));await page.fill('#history-query','new');await page.locator('#page-status').filter({hasText:'共 45 条'}).waitFor();await page.waitForTimeout(1000);assert.ok(!(await page.locator('#page-status').textContent()).includes('999'));assert.deepEqual(errors,[]);
+93
View File
@@ -0,0 +1,93 @@
// 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 root=await mkdtemp(path.join(tmpdir(),'RID-realtime-layout-'));
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
const base='http://127.0.0.1:18887';
// 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:18888,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(18888,'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('18887 occupied; preserving existing service');
const backendOccupied=await new Promise(resolve=>{const socket=net.connect(18888,'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('18888 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:'18888'},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;}}
const key='rid.realtime.layout.v1';
let report={};let heartbeat;let sequence=1;
const wait=ms=>new Promise(r=>setTimeout(r,ms));
try {
await new Promise((resolve,reject)=>{proxy.once('error',reject);proxy.listen(18887,'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}});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())});
const requests={config:0,status:0,writes:0};page.on('request',r=>{if(r.url().endsWith('/api/receiver/config')){if(r.method()==='GET')requests.config++;else requests.writes++;}if(r.url().endsWith('/api/receiver/status'))requests.status++;});
for(const asset of ['workspace-native.css','map-adapter.js','index.html']){const response=await fetch(base+'/'+(asset==='index.html'?'realtime':asset));assert.equal(response.status,200);assert.ok(await response.text()===await readFile(path.resolve('dist/web-ui',asset),'utf8'),'Executable contains stale '+asset);}
await page.goto(base+'/realtime');await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();
console.log('Checking actual Rust/Wasm layout and telemetry');
await page.locator('.live-empty').waitFor();assert.equal(await page.locator('.mc-btn-row a').getAttribute('aria-disabled'),'true');
await page.getByRole('button',{name:'聚焦此目标',exact:true}).isDisabled().then(v=>assert.ok(v));
const registered=await fetch(base+'/api/records',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({serialNo:'LAYOUT-0000',modelName:'验收模拟机型',ownerName:'隔离验收数据'})});assert.equal(registered.status,200);
const batch=Array.from({length:120},(_,i)=>({target_id:`LAYOUT-${String(i).padStart(4,'0')}`,receiver_id:'TEST',source_epoch:1,sequence:1,longitude:120+i*.0001,latitude:30+i*.0001,altitude_m:100+i,heading_deg:i%360}));
const longId='LAYOUT-LONG-'+ 'X'.repeat(52);batch[119].target_id=longId;
async function ingest(items){const r=await fetch(base+'/api/realtime/ingest',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(items)});assert.equal(r.status,200);return r.json()}
heartbeat=setInterval(()=>ingest(batch.map(x=>({...x,sequence:++sequence}))).catch(()=>{}),5000);
await ingest(batch);await page.getByText('目标 120 ·',{exact:false}).waitFor();assert.equal(await page.locator('.rt-target').count(),100);
await page.getByRole('button',{name:'下一组',exact:true}).click();await page.getByRole('button',{name:'LAYOUT-0100',exact:true}).waitFor();
await page.getByRole('textbox',{name:'搜索实时目标'}).fill('LAYOUT-0000');await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();
await page.locator('.rt-details').filter({hasText:'120.000000'}).waitFor();await page.locator('.rt-details').filter({hasText:'已匹配本地登记档案'}).waitFor();
await page.waitForFunction(()=>window.ridMap?.metrics().mapReady);
await page.getByRole('button',{name:'聚焦此目标',exact:true}).click();await wait(650);
const metrics=await page.evaluate(()=>window.ridMap.metrics());const canvas=await page.locator('.maplibregl-canvas').boundingBox();
assert.ok(metrics.selectedPixel.x>metrics.occlusion.left && metrics.selectedPixel.x<canvas.width-metrics.occlusion.right,JSON.stringify(metrics));
assert.ok(metrics.selectedPixel.y>metrics.occlusion.top && metrics.selectedPixel.y<canvas.height-metrics.occlusion.bottom,JSON.stringify(metrics));
await page.getByRole('textbox',{name:'搜索实时目标'}).fill(longId);await page.getByRole('button',{name:longId,exact:true}).click();await page.locator('.rt-details').filter({hasText:'未匹配本地档案'}).waitFor();
const longOverflow=await page.locator('#rt-details').evaluate(e=>e.scrollWidth>e.clientWidth);assert.equal(longOverflow,false);
await page.route('**/api/records?q=*',route=>route.fulfill({status:503,contentType:'application/json',body:'{}'}));
await page.getByRole('textbox',{name:'搜索实时目标'}).fill('LAYOUT-0001');await page.getByRole('button',{name:'LAYOUT-0001',exact:true}).click();await page.locator('.rt-details').filter({hasText:'本地档案查询失败'}).waitFor();await page.unroute('**/api/records?q=*');
await page.getByRole('textbox',{name:'搜索实时目标'}).fill('LAYOUT-0000');await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();
const grip=page.getByRole('separator',{name:'调整底栏高度'});let box=await grip.boundingBox();await page.mouse.move(box.x+box.width/2,box.y+4);await page.mouse.down();await page.mouse.move(box.x+box.width/2,box.y-80,{steps:5});await page.mouse.up();await wait(200);
const grown=Number(await grip.getAttribute('aria-valuenow'));assert.ok(grown>=240);await grip.focus();await page.keyboard.press('ArrowUp');assert.equal(Number(await grip.getAttribute('aria-valuenow')),grown+16);
const preferred=Number(await grip.getAttribute('aria-valuenow'));await page.reload();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await wait(250);assert.equal(Number(await grip.getAttribute('aria-valuenow')),preferred);
await page.getByRole('button',{name:'隐藏事件面板',exact:true}).click();await page.locator('#rt-dock-restore').waitFor();await wait(50);assert.equal(await page.evaluate(()=>document.activeElement.id),'rt-dock-restore');await page.reload();await page.locator('#rt-dock-restore').waitFor();await page.locator('#rt-dock-restore').click();
await page.getByRole('button',{name:'接收器与解码',exact:true}).click();await page.getByLabel('串口',{exact:true}).waitFor();await wait(250);await page.getByLabel('串口',{exact:true}).fill('UNSAVED-COM');
await wait(3200);const baseline=requests.status;await wait(3200);const beforeRate=requests.status-baseline;
for(let i=0;i<20;i++){await page.getByRole('button',{name:'目标快照与事件',exact:true}).click();await page.getByRole('button',{name:'接收器与解码',exact:true}).click();}
assert.equal(await page.getByLabel('串口',{exact:true}).inputValue(),'UNSAVED-COM');assert.equal(requests.config,1);assert.equal(requests.writes,0);
const afterStart=requests.status;await wait(3200);const afterRate=requests.status-afterStart;assert.ok(afterRate<=beforeRate+2,{beforeRate,afterRate});
await page.getByRole('button',{name:'目标快照与事件',exact:true}).click();
// Generate real transport events without writing receiver configuration.
for(let i=0;i<23;i++){for(const socket of [...sockets])socket.destroy();await page.locator('.rt-status').filter({hasText:'连接断开'}).waitFor();assert.equal(await page.getByRole('button',{name:'聚焦此目标',exact:true}).isDisabled(),true);await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();}
assert.equal(await page.locator('.live-events li').count(),64);
await grip.focus();await page.keyboard.press('Home');const scroller=page.locator('#rt-event-scroll');await scroller.evaluate(e=>e.scrollTop=Math.min(400,e.scrollHeight/2));
const anchor=await scroller.evaluate(e=>{const r=e.getBoundingClientRect();return [...e.querySelectorAll('li')].map(li=>({text:li.textContent,y:li.getBoundingClientRect().top-r.top})).find(x=>x.y>=0)});
for(const socket of [...sockets])socket.destroy();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await wait(200);
if(anchor){const next=await scroller.evaluate((e,a)=>{const li=[...e.querySelectorAll('li')].find(li=>li.textContent===a.text);return li?li.getBoundingClientRect().top-e.getBoundingClientRect().top:null},anchor);assert.ok(next!==null&&Math.abs(next-anchor.y)<4,JSON.stringify({anchor,next}));}
// Restore a normal useful desktop frame with live Worker data.
await ingest(batch.map(x=>({...x,sequence:++sequence})));await page.getByRole('textbox',{name:'搜索实时目标'}).fill('LAYOUT-0000');await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();
await page.getByRole('button',{name:'聚焦此目标',exact:true}).click();await grip.focus();await page.keyboard.press('ArrowUp');await page.keyboard.press('ArrowUp');await page.keyboard.press('ArrowUp');await page.keyboard.press('ArrowUp');await wait(500);
const sizes=[[1920,1080],[1440,900],[1280,720],[1440,500],[768,1024],[390,844]];const themes=['graphite','blue','white'];
let frames=0;
for(const [width,height]of sizes){await page.setViewportSize({width,height});await wait(250);for(const theme of themes){await page.evaluate(t=>{document.body.classList.remove('theme-blue','theme-white');if(t!=='graphite')document.body.classList.add('theme-'+t)},theme);
const state=await page.evaluate(()=>{const root=document.getElementById('rt-layout'),panels=[...root.querySelectorAll('.mc-floating-panel')].filter(e=>!e.hidden);return {headerClipped:[...root.querySelectorAll('.mc-dock-header button')].filter(e=>e.getBoundingClientRect().height>0).some(e=>{const r=e.getBoundingClientRect(),h=root.querySelector('.mc-dock-header').getBoundingClientRect();return r.left<h.left-1||r.right>h.right+1||r.top<h.top-1||r.bottom>h.bottom+1}),overflow:document.documentElement.scrollWidth>innerWidth,compact:root.classList.contains('compact'),count:panels.length,clipped:panels.some(p=>{const action=p.querySelector('.mc-btn-row,.pagination');const a=action.getBoundingClientRect(),b=p.getBoundingClientRect();return a.bottom>b.bottom+1||a.top<b.top;})}});assert.equal(state.overflow,false);assert.equal(state.clipped,false);assert.equal(state.headerClipped,false,JSON.stringify({width,height,theme,state}));if(width<900||height<568)assert.ok(state.count<=1);frames++;
if(theme==='graphite')await page.screenshot({path:path.join(root,`realtime-b-${width}x${height}.png`)});
}}
await page.setViewportSize({width:1440,height:500});await wait(250);await page.locator('#rt-list-toggle').click();await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();await wait(100);assert.equal(await page.locator('#rt-details').isVisible(),true);assert.equal(await page.evaluate(()=>document.activeElement.id),'rt-details');const lowClipped=await page.locator('#rt-details').evaluate(e=>e.querySelector('.mc-btn-row').getBoundingClientRect().bottom>e.getBoundingClientRect().bottom+1);assert.equal(lowClipped,false);await page.getByRole('button',{name:'收起详情',exact:true}).click();
await page.setViewportSize({width:390,height:844});await wait(250);await page.locator('#rt-list-toggle').click();await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();assert.equal(await page.locator('#rt-directory').isVisible(),false);assert.equal(await page.locator('#rt-details').isVisible(),true);assert.equal(await page.locator('#rt-dock').isVisible(),false);await page.screenshot({path:path.join(root,'realtime-b-mobile-detail.png')});await page.getByRole('button',{name:'聚焦此目标',exact:true}).click();await wait(500);assert.equal(await page.locator('#rt-details').isVisible(),false);
for(const zoom of [1.25,1.5]){await page.setViewportSize({width:1280,height:720});await page.evaluate(z=>document.documentElement.style.zoom=String(z),zoom);await wait(250);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:path.join(root,`realtime-b-zoom-${zoom}.png`)});}
await page.evaluate(()=>document.documentElement.style.zoom='');await page.setViewportSize({width:1600,height:1000});await wait(250);
const savedBeforeHome=await page.evaluate(k=>localStorage.getItem(k),key);await page.getByRole('button',{name:'返回应用总览',exact:true}).click();await page.locator('body[data-screen=home]').waitFor();await page.setViewportSize({width:390,height:844});await wait(250);await page.setViewportSize({width:1600,height:1000});await wait(250);assert.equal(await page.evaluate(k=>localStorage.getItem(k),key),savedBeforeHome);await page.locator('#home-app-realtime').click();await page.locator('body[data-screen=realtime]').waitFor();await wait(250);
await page.evaluate(k=>localStorage.setItem(k,'broken json'),key);await page.reload();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await wait(250);assert.equal(Number(await grip.getAttribute('aria-valuenow')),170);
await page.getByRole('textbox',{name:'搜索实时目标'}).fill('LAYOUT-0000');await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();await page.getByRole('button',{name:'聚焦此目标',exact:true}).click();await wait(500);await page.screenshot({path:path.join(root,'realtime-b-final.png')});
const realtimeStatus=await (await fetch(base+'/api/realtime/status')).json();assert.equal(realtimeStatus.clients,1);
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
report={status:'PASS',root,exe,serverPid:child.pid,clients:realtimeStatus.clients,frames,requests,beforeRate,afterRate,checks:['embedded-assets-match-build','empty','real-worker-120-targets','search-pagination','local-record-match-unmatched-error','long-id','safe-focus','drag-keyboard','reload-persistence','hide-restore-focus','receiver-20-switches','events-bounded-at-64','event-scroll-anchor','three-themes-six-sizes-including-low-height','hidden-workspace-keeps-preferences','compact-select-focus','zoom-125-150','corrupt-storage'],note:'Synthetic input; no physical receiver transport opened.'};console.log(JSON.stringify(report));
}finally{clearInterval(heartbeat);if(browser){if(report.status!=='PASS'){const p=browser.contexts()[0]?.pages()[0];if(p){await p.screenshot({path:path.join(root,'failure.png')}).catch(()=>{});console.log(JSON.stringify({root,errors,csp,diagnostic:await p.evaluate(()=>({layout:document.getElementById('rt-layout')?.outerHTML.slice(0,2000),metrics:window.ridMap?.metrics()})).catch(()=>null)}));}}await browser.close();}await stop();for(const s of sockets)s.destroy();const closed=new Promise(r=>proxy.close(r));proxy.closeAllConnections();await closed;await writeFile(path.join(root,'server.log'),output);await writeFile(path.join(root,'layout-report.json'),JSON.stringify({...report,errors,csp},null,2));}
+1 -1
View File
@@ -42,7 +42,7 @@ try{
await new Promise(r=>setTimeout(r,10));
}
clearInterval(monitor);while(sampling)await new Promise(r=>setTimeout(r,50));
await page.getByText(`在线目标 ${count} ·`,{exact:false}).waitFor();
await page.getByText(`目标 ${count} ·`,{exact:false}).waitFor();
assert.equal(await page.locator('.rt-target').count(),Math.min(count,100));
if(count>100){await page.getByRole('button',{name:'下一组',exact:true}).click();await page.getByRole('button',{name:'SIM-00100',exact:true}).waitFor();}
await page.getByRole('textbox',{name:'搜索实时目标'}).fill('SIM-00000');await page.getByRole('button',{name:'SIM-00000',exact:true}).click();
+105
View File
@@ -0,0 +1,105 @@
// 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,channel:'msedge'});
const context=await browser.newContext({viewport:{width:1600,height:1000},acceptDownloads:true,permissions:['clipboard-read','clipboard-write']});
await context.addInitScript(()=>{
window.ridPhotoUrls=new Set();const create=URL.createObjectURL.bind(URL),revoke=URL.revokeObjectURL.bind(URL);
URL.createObjectURL=b=>{const u=create(b);if(b.type.startsWith('image/'))window.ridPhotoUrls.add(u);return u};URL.revokeObjectURL=u=>{window.ridPhotoUrls.delete(u);revoke(u)};
const decode=HTMLImageElement.prototype.decode;HTMLImageElement.prototype.decode=function(){const delay=this.src.startsWith('blob:')?(window.ridDecodeDelay||0):0;if(delay)window.ridDecodeStarted=true;return decode.call(this).then(()=>new Promise(r=>setTimeout(r,delay)))};
});
const page=await context.newPage();page.on('pageerror',e=>{errors.push(e.message);console.log('PAGE ERROR',e.stack)});page.on('console',m=>{if(/violates.*Content Security|Refused.*policy/i.test(m.text()))csp.push(m.text())});
for(let i=0;i<21;i++){const r=await fetch(base+'/api/records',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({serialNo:'B-SEED-'+String(i).padStart(3,'0'),modelName:'验收机型',ownerName:'隔离数据'})});assert.equal(r.status,200)}
await page.goto(base+'/?app=register');await page.locator('#page-status').filter({hasText:'共 21 条'}).waitFor();
await page.screenshot({path:path.join(root,'register-empty.png')});
console.log('STAGE selection');const png=Buffer.from(await page.evaluate(()=>{let c=document.createElement('canvas');c.width=20;c.height=20;let x=c.getContext('2d');x.fillStyle='#5098d1';x.fillRect(0,0,20,20);return c.toDataURL().split(',')[1]}),'base64');
const file=name=>({name,mimeType:'image/png',buffer:png});
const choose=async(id,name)=>{await page.locator(id).setInputFiles(file(name));};
const readyPhoto=async(i,name)=>{await page.locator('#slot-name-'+i).filter({hasText:name}).waitFor();await page.waitForFunction(i=>document.querySelector('#slot-status-'+i).getAttribute('aria-busy')==='false',i)};
// Selection, menu keyboard and redraw focus.
assert.equal(await page.locator('#select-all').isVisible(),false);assert.equal(await page.locator('#export-toggle').isDisabled(),true);
await page.locator('#selection-toggle').click();const first=page.locator('.archive-select input').first();await first.focus();const firstId=await first.getAttribute('id');await page.keyboard.press('Space');assert.equal(await page.evaluate(()=>document.activeElement.id),firstId);
await page.locator('#export-toggle').click();assert.equal(await page.locator('#export-options').isVisible(),true);await page.keyboard.press('Escape');assert.equal(await page.evaluate(()=>document.activeElement.id),'export-toggle');
await page.locator('#select-all').check();assert.equal(await page.locator('.archive-select input:checked').count(),20);
for(const kind of ['excel','archive']){await page.locator('#export-toggle').click();const req=page.waitForRequest(r=>r.url().endsWith('/api/export/'+kind));const dl=page.waitForEvent('download');await page.locator('#export-'+kind).click();assert.equal((await req).postDataJSON().ids.length,20);await(await dl).saveAs(path.join(root,kind==='excel'?'records.xlsx':'archives.zip'))}
await page.locator('#selection-toggle').click();assert.equal(await page.locator('#export-toggle').isDisabled(),true);
const card=page.locator('.archive-card').first();await card.locator('.archive-more').click();await page.keyboard.press('Escape');assert.equal(await page.evaluate(()=>document.activeElement.classList.contains('archive-more')),true);
await card.locator('.archive-more').click();await card.getByRole('button',{name:'编辑资料 / 照片',exact:true}).click();await page.locator('#edit-model').waitFor();await page.locator('#edit-cancel').click();await page.waitForFunction(()=>document.activeElement.classList.contains('archive-more'));
console.log('STAGE draft');
// Viewing another record never overwrites draft fields.
await page.locator('#serial-no').fill('B-NEW-001');await page.locator('#owner-name').fill('待保存草稿');await card.getByRole('button',{name:'查看档案 →',exact:true}).click();assert.equal(await page.locator('#serial-no').inputValue(),'B-NEW-001');assert.match(await page.locator('#result-context').innerText(),/正在查看/);
page.once('dialog',d=>d.dismiss());await page.locator('#new-registration').click();assert.equal(await page.locator('#owner-name').inputValue(),'待保存草稿');page.once('dialog',d=>d.accept());await page.locator('#new-registration').click();assert.equal(await page.locator('#serial-no').inputValue(),'');assert.equal(await page.evaluate(()=>document.activeElement.id),'serial-no');assert.equal(await page.locator('#empty-result').isVisible(),true);
console.log('STAGE photos');
// Invalid replacement and cancelled picker preserve the accepted image.
const [picker]=await Promise.all([page.waitForEvent('filechooser'),page.locator('[data-photo-choose="0"]').click()]);await picker.setFiles(file('valid.png'));await readyPhoto(0,'valid.png');const src=await page.locator('#slot-preview-0').getAttribute('src');await page.locator('#photo-1').setInputFiles([]);assert.equal(await page.locator('#slot-preview-0').getAttribute('src'),src);
await page.locator('#photo-1').setInputFiles({name:'broken.png',mimeType:'image/png',buffer:Buffer.from('broken')});await page.locator('#slot-status-0').filter({hasText:'照片内容与格式不符'}).waitFor();assert.equal(await page.locator('#slot-preview-0').getAttribute('src'),src);await page.locator('#slot-keep-0').click();
// Out-of-order decode, removal and reset invalidate old work.
await page.evaluate(()=>{window.ridDecodeDelay=250;window.ridDecodeStarted=false});await choose('#photo-1','slow.png');await page.waitForFunction(()=>window.ridDecodeStarted);await page.evaluate(()=>window.ridDecodeDelay=0);await choose('#photo-1','latest.png');await readyPhoto(0,'latest.png');await page.waitForTimeout(320);assert.equal(await page.locator('#slot-name-0').innerText(),'latest.png');
await page.evaluate(()=>{window.ridDecodeDelay=200;window.ridDecodeStarted=false});await choose('#photo-2','removed.png');await page.waitForFunction(()=>window.ridDecodeStarted);await page.locator('#slot-remove-1').click();await page.waitForTimeout(240);assert.equal(await page.locator('#slot-preview-1').isVisible(),false);
await choose('#photo-2','reset.png');page.once('dialog',d=>d.accept());await page.locator('#new-registration').click();await page.waitForTimeout(250);assert.equal(await page.locator('#slot-preview-1').isVisible(),false);await page.evaluate(()=>window.ridDecodeDelay=0);
assert.equal(await page.evaluate(()=>window.ridPhotoUrls.size),0);
console.log('STAGE submit');
// Failure restores all controls and keeps draft + photos; busy navigation is blocked.
await page.locator('#serial-no').fill('B-NEW-001');await page.locator('#model-name').fill('验收新机');await page.locator('#owner-name').fill('原始快照');await choose('#photo-1','snapshot.png');await readyPhoto(0,'snapshot.png');
let requests=0;
await page.route('**/api/records',async route=>{if(route.request().method()==='POST'){requests++;assert.equal(route.request().postDataJSON().ownerName,'原始快照');await new Promise(r=>setTimeout(r,450));await route.fulfill({status:500,contentType:'application/json',body:JSON.stringify({error:'隔离验收失败'})})}else await route.continue()});
const sent=page.waitForRequest(r=>r.url().endsWith('/api/records')&&r.method()==='POST');await page.locator('#register-button').click();await sent;assert.equal(await page.locator('#serial-no').isDisabled(),true);assert.equal(await page.locator('#new-registration').isDisabled(),true);await page.getByRole('button',{name:'返回应用总览',exact:true}).click();assert.equal(await page.locator('body').getAttribute('data-screen'),'register');await page.locator('#register-form').evaluate(f=>{f.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true}));f.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true}))});
await page.locator('#form-message').filter({hasText:'隔离验收失败'}).waitFor();assert.equal(requests,1);assert.equal(await page.locator('#owner-name').inputValue(),'原始快照');assert.equal(await page.locator('#slot-name-0').innerText(),'snapshot.png');assert.equal(await page.locator('#serial-no').isEnabled(),true);await page.unroute('**/api/records');
console.log('STAGE save success');
// Saving waits for the latest photo validation and uses one immutable snapshot.
await page.evaluate(()=>{window.ridDecodeDelay=250;window.ridDecodeStarted=false});await choose('#photo-2','pending.png');await page.waitForFunction(()=>window.ridDecodeStarted);await page.locator('#register-button').click();await page.locator('#form-message').filter({hasText:'登记成功'}).waitFor();await page.evaluate(()=>window.ridDecodeDelay=0);
let records=(await(await fetch(base+'/api/records?q=B-NEW-001')).json()).records;assert.equal(records.length,1);assert.ok(records[0].photo1Url&&records[0].photo2Url);const record=records[0];await page.locator('#qr-stage svg').waitFor();assert.match(await page.locator('#result-context').innerText(),/B-NEW-001/);
const qrDownload=page.waitForEvent('download');await page.locator('#download-qr').click();await(await qrDownload).saveAs(path.join(root,'qr.png'));await page.locator('#copy-url').click();assert.equal(await page.evaluate(()=>navigator.clipboard.readText()),record.qrUrl);
assert.equal((await fetch(base+record.archiveUrl)).status,200);assert.equal((await fetch(base+record.downloadArchiveUrl)).status,200);
console.log('STAGE edit');
await page.screenshot({path:path.join(root,'register-saved.png')});
// Duplicate SN updates instead of adding another record.
await page.locator('#owner-name').fill('更新登记人');await page.locator('#register-button').click();await page.locator('#form-message').filter({hasText:'该 SN 已登记'}).waitFor();assert.equal((await(await fetch(base+'/api/records?q=B-NEW-001')).json()).records.length,1);
// A committed record remains saved even when the follow-up list request fails.
let failList=true;await page.route('**/api/records?**',async r=>{if(failList){failList=false;await r.fulfill({status:500,contentType:'application/json',body:JSON.stringify({error:'隔离列表失败'})})}else await r.continue()});await page.locator('#register-button').click();await page.locator('#history-message').filter({hasText:'已保存,但列表刷新失败'}).waitFor();assert.equal((await(await fetch(base+'/api/records?q=B-NEW-001')).json()).records[0].ownerName,'更新登记人');await page.unroute('**/api/records?**');
await page.locator('#history-query').fill('B-NEW-001');await page.locator('#page-status').filter({hasText:'共 1 条'}).waitFor();const own=page.locator('.archive-card').filter({has:page.getByRole('heading',{name:'B-NEW-001',exact:true})});
const edit=async()=>{await own.locator('.archive-more').click();await own.getByRole('button',{name:'编辑资料 / 照片',exact:true}).click();await page.locator('#edit-dialog').waitFor()};
await edit();await choose('#edit-photo-1','replace.png');await readyPhoto(2,'replace.png');await page.locator('#slot-remove-2').click();assert.match(await page.locator('#slot-name-2').innerText(),/现有照片/);
await page.locator('#edit-owner').fill('不得保存');await page.locator('#edit-photo-1').setInputFiles({name:'bad.png',mimeType:'image/png',buffer:Buffer.from('bad')});await page.locator('#slot-status-2.error').waitFor();await page.locator('#edit-save').click();await page.locator('#edit-message').filter({hasText:'照片内容与格式不符'}).waitFor();assert.equal((await(await fetch(base+'/api/records?q=B-NEW-001')).json()).records[0].ownerName,'更新登记人');await page.locator('#edit-cancel').click();
await edit();await page.locator('#edit-owner').fill('修改后');await page.locator('#edit-delete-1').check();await choose('#edit-photo-2','replacement.png');await readyPhoto(3,'replacement.png');await page.locator('#edit-save').click();await page.locator('#edit-dialog').waitFor({state:'hidden'});await page.locator('#history-message').filter({hasText:'档案修改已保存'}).waitFor();records=(await(await fetch(base+'/api/records?q=B-NEW-001')).json()).records;assert.equal(records[0].photo1Url,null);assert.ok(records[0].photo2Url);assert.equal(records[0].ownerName,'修改后');
console.log('STAGE geometry');
// Three themes and viewport/zoom geometry, including the final helper and save button.
const cases=[];await page.locator('#new-registration').click();
for(const theme of ['graphite','blue','white']){await page.locator('.theme-quick [data-theme='+theme+']').click();await waitPref(p=>p.theme===theme);
for(const [width,height]of [[1600,1000],[1366,768],[1080,900],[390,844],[1366,600]]){await page.setViewportSize({width,height});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.locator('.registration-photos').scrollIntoViewIfNeeded();await page.locator('#register-button').scrollIntoViewIfNeeded();const box=await page.locator('#register-button').boundingBox();assert.ok(box.x>=0&&box.x+box.width<=width&&box.y>=48&&box.y+box.height<=height+1);await page.locator('#register-form>.registry-group:last-of-type>.registry-help').scrollIntoViewIfNeeded();const overlap=await page.evaluate(()=>{const a=document.querySelector('#register-form>.registry-group:last-of-type>.registry-help').getBoundingClientRect(),b=document.querySelector('.registration-savebar').getBoundingClientRect();return a.bottom>b.top&&a.top<b.bottom});assert.equal(overlap,false);cases.push({theme,width,height});if(width===1600){await page.locator('.registration-heading').scrollIntoViewIfNeeded();await page.screenshot({path:path.join(root,'register-'+theme+'.png')})}}
}
await page.setViewportSize({width:1600,height:1000});await page.evaluate(()=>document.documentElement.style.zoom='2');assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.locator('#register-button').scrollIntoViewIfNeeded();await page.screenshot({path:path.join(root,'register-zoom200.png')});await page.evaluate(()=>document.documentElement.style.zoom='');
await page.setViewportSize({width:390,height:844});await page.locator('#history-title').scrollIntoViewIfNeeded();const mobileBar=await page.locator('.registration-savebar').boundingBox();const mobileHistory=await page.locator('#history-title').boundingBox();assert.ok(mobileBar.y+mobileBar.height<=mobileHistory.y);await page.setViewportSize({width:1600,height:1000});
console.log('STAGE delete');
// Delete current result and preserve unrelated records.
await own.getByRole('button',{name:'查看档案 →',exact:true}).click();await own.locator('.archive-more').click();page.once('dialog',d=>d.accept());await own.getByRole('button',{name:'删除档案',exact:true}).click();await page.locator('#empty-result').waitFor();await page.locator('#page-status').filter({hasText:'共 0 条'}).waitFor();assert.equal((await(await fetch(base+'/api/records?page=1')).json()).total,21);
await page.locator('#history-query').fill('');await page.locator('#page-status').filter({hasText:'共 21 条'}).waitFor();await page.locator('#next-page').click();await page.locator('#page-status').filter({hasText:'第 2 / 2 页'}).waitFor();assert.equal(await page.locator('.archive-card').count(),1);
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
await writeFile(path.join(root,'report.json'),JSON.stringify({status:'PASS',root,errors,csp,cases,scenarios:['real Rust/Wasm registration B','validated photo preservation, cancel, replacement, reset, stale decode','immutable submit, failed save, duplicate suppression, busy navigation','draft/result separation, new confirmation','menu focus, selection redraw, current-page Excel and ZIP','duplicate SN, edit atomicity and delete current result','QR PNG and clipboard/archive links','three themes, 15 viewport cases, 200% zoom, mobile save boundary']},null,2));console.log(JSON.stringify({status:'PASS',root}));
}catch(e){console.log('FAILED ROOT',root,e.stack);if(browser){const pages=browser.contexts().flatMap(c=>c.pages());if(pages[0])await pages[0].screenshot({path:path.join(root,'failed.png')}).catch(()=>{});}throw e;}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)}
+91
View File
@@ -0,0 +1,91 @@
// 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);}