| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- #!/usr/bin/env node
- import fs from 'node:fs';
- import path from 'node:path';
- import {spawnSync} from 'node:child_process';
- import {createHash} from 'node:crypto';
- import {connectWebView,captureNativeScreenshot} from './android-webview-cdp.mjs';
- import {readNativeReview,updateNativeReview,beginNativeAction,finishNativeAction,failNativeAction,nativeCheck} from './lib/native-ui-review-ledger.mjs';
- const state=readNativeReview();const serial=state.device.serial;const attempt=Number(process.argv.find(x=>x.startsWith('--install-attempt='))?.split('=')[1]||'1');if(!Number.isInteger(attempt)||attempt<1||attempt>9)throw Error('非法安装尝试编号');const revision=process.argv.find(x=>x.startsWith('--revision='))?.split('=')[1]||'r1';
- if(!/^r[1-9][0-9]*$/.test(revision))throw Error('非法修订');
- const receipt=state.actions['build_'+revision]?.receipt;
- if(!receipt||receipt.packageId!=='cn.fmode.app.uitest'||receipt.sourceMode!=='mock-production')throw Error('没有已确认的独立Mock原生包');
- const apkHash=createHash('sha256').update(fs.readFileSync(receipt.apk)).digest('hex');if(apkHash!==receipt.sha256)throw Error('APK摘要不匹配');
- const adb=args=>{const r=spawnSync('adb',['-s',serial,...args],{encoding:'utf8',timeout:120000,windowsHide:true});if(r.status!==0)throw Error('adb '+args.slice(0,4).join(' ')+' 退出'+r.status+':'+(r.stderr||r.stdout||r.error?.message||'无输出').trim());return r.stdout.trim()};
- const out='test-results/native-ui-20261130';
- let activeAction=null,cdp;
- try{
- const key='install_'+revision+(attempt===1?'':'_attempt'+attempt);
- const priorInstall=readNativeReview().actions[key];
- if(priorInstall&&priorInstall.status!=='confirmed')throw Error('该安装尝试没有确认成功;先回读设备许可与原回执,再显式登记新尝试');
- if(!priorInstall){
- const listed=adb(['shell','pm','list','packages',receipt.packageId]).split(/\r?\n/);
- const packagePath=listed.includes('package:'+receipt.packageId)?adb(['shell','pm','path',receipt.packageId]):'';
- if(packagePath){
- const base=packagePath.split(/\r?\n/).find(x=>x.startsWith('package:'))?.slice(8);
- const same=base&&adb(['shell','sha256sum',base]).split(/\s+/)[0].toLowerCase()===apkHash;
- if(same){beginNativeAction(key,{serial,packageId:receipt.packageId,sha256:apkHash,readOnlyReconciliation:true});finishNativeAction(key,{alreadyInstalled:true,installedSha256:apkHash});}
- else throw Error('同名测试包与目标摘要不同,先核实,不覆盖未知安装');
- }
- if(!readNativeReview().actions[key]){
- beginNativeAction(key,{serial,packageId:receipt.packageId,sha256:apkHash,apk:receipt.apk,originalPackageUntouched:true,attempt});activeAction=key;
- const output=adb(['install','-r',receipt.apk]);
- if(!/Success/.test(output))throw Error('安装未获得Success回执:'+output);
- const installed=adb(['shell','pm','path',receipt.packageId]);const base=installed.split(/\r?\n/).find(x=>x.startsWith('package:'))?.slice(8);if(!base)throw Error('新包安装路径未回读');
- const installedHash=adb(['shell','sha256sum',base]).split(/\s+/)[0];if(installedHash.toLowerCase()!==apkHash)throw Error('安装后APK摘要不一致');
- const original=adb(['shell','dumpsys','package','cn.fmode.app']).split(/\r?\n/).filter(l=>/versionCode=|versionName=|lastUpdateTime=/.test(l));
- finishNativeAction(key,{output,installedPath:base,installedSha256:installedHash,originalPackageReadback:original});activeAction=null;console.log('独立测试包安装及摘要回读通过,原包保留');
- }
- }
- const finalPath=adb(['shell','pm','path',receipt.packageId]).split(/\r?\n/).find(x=>x.startsWith('package:'))?.slice(8);
- if(!finalPath||adb(['shell','sha256sum',finalPath]).split(/\s+/)[0].toLowerCase()!==apkHash)throw Error('当前已安装测试包与本次目标摘要不符,停止启动/填充');
- updateNativeReview(s=>{s.stage='native_ui_testing'});
- const launch='launch_'+revision;
- if(!readNativeReview().actions[launch]){const resolved=adb(['shell','cmd','package','resolve-activity','--brief',receipt.packageId]).split(/\r?\n/).find(l=>l.startsWith(receipt.packageId+'/'));if(!resolved)throw Error('测试包启动组件未解析');beginNativeAction(launch,{serial,component:resolved});activeAction=launch;const output=adb(['shell','am','start','-n',resolved]);finishNativeAction(launch,{output});activeAction=null;}
- const deadline=Date.now()+30000;let pid,socket;
- while(Date.now()<deadline){try{pid=adb(['shell','pidof',receipt.packageId]).trim();socket=adb(['shell','cat','/proc/net/unix']).split(/\r?\n/).find(l=>l.endsWith('@webview_devtools_remote_'+pid));if(pid&&socket)break}catch{}await new Promise(r=>setTimeout(r,300))}
- if(!pid||!socket)throw Error('测试包WebView未就绪,不复用原包调试连接');
- const forward='forward_'+revision+'_'+pid;let port=readNativeReview().actions[forward]?.result?.port;
- if(!port){beginNativeAction(forward,{packageId:receipt.packageId,pid,socket:'webview_devtools_remote_'+pid});activeAction=forward;port=Number(adb(['forward','tcp:0','localabstract:webview_devtools_remote_'+pid]));finishNativeAction(forward,{port});activeAction=null;}
- updateNativeReview(s=>{s.reviewSession={revision,pid,port,packageId:receipt.packageId,at:new Date().toISOString()}});
- const blocked=[];
- cdp=await connectWebView(port,{onEvent:(message,send)=>{if(message.method!=='Fetch.requestPaused')return;const request=message.params.request;const url=new URL(request.url);const allow=url.origin==='https://localhost'&&!/^\/(?:api(?:-platform)?|parse)(?:\/|$)/i.test(url.pathname);if(!allow)blocked.push({origin:url.origin,path:url.pathname,method:request.method});return send(allow?'Fetch.continueRequest':'Fetch.failRequest',allow?{requestId:message.params.requestId}:{requestId:message.params.requestId,errorReason:'BlockedByClient'})}});
- await cdp.send('Network.setBlockedURLs',{urls:['http://*','https://server.fmode.cn/*','https://matrix.fmode.cn/*','wss://*','ws://*']});
- await cdp.send('Fetch.enable',{patterns:[{urlPattern:'*',requestStage:'Request'}]});
- const seed='seed_'+revision;
- if(!readNativeReview().actions[seed]){
- beginNativeAction(seed,{packageId:receipt.packageId,profile:'demo-user',identityScope:'仅独立测试包本地存储;不复制真实Token',dataMode:'mock'});activeAction=seed;
- const fixtureClock=`(() => { const RealDate=Date; const fixed=${new Date('2026-10-14T10:43:00+08:00').getTime()}; class DemoDate extends RealDate { constructor(...args){super(...(args.length?args:[fixed]))} static now(){return fixed} } globalThis.Date=DemoDate; })();`;
- await cdp.send('Page.addScriptToEvaluateOnNewDocument',{source:fixtureClock});
- await cdp.evaluate(()=>{
- localStorage.setItem('fmode_session_token','native-ui-demo');localStorage.setItem('fmode_me',JSON.stringify({id:'demo-user',name:'真机UI测试(演示)',companyId:'demo-company'}));
- localStorage.setItem('fmode_ui_mode_override','mobile');localStorage.setItem('fmode_palette','platinum');
- localStorage.setItem('fmode_workspaces_demo-user',JSON.stringify([{id:'ws-shell',name:'外壳 3D',createdAt:Date.now()-86400000},{id:'ws-research',name:'产品研究',createdAt:Date.now()}]));
- localStorage.setItem('mock/chat-threads',JSON.stringify(Array.from({length:8},(_,i)=>({objectId:'ui-review-'+i,agentId:['zhixia','qiyun','jianwei','xingzhou'][i%4],roomId:'!native-ui-'+i+':example.invalid',threadRoot:'$ui-review-'+i,workspaceId:i%2?'ws-research':'ws-shell',title:['真机界面验收:检查长标题与摘要是否清晰完整','项目执行清单与下一步安排','第三季度数据分析','客户反馈整理'][i%4],titleLocked:true,messageCount:4,lastMessageAt:Date.now()-i*2400000,archived:false,lastPreview:'隔离演示数据,仅用于真实手机界面与交互检查。'}))));
- });
- await cdp.send('Page.navigate',{url:'https://localhost/mobile/messages'});
- await cdp.waitFor(()=>location.pathname==='/mobile/messages'&&document.querySelector('.m-title-main'));
- finishNativeAction(seed,{path:await cdp.evaluate(()=>location.pathname),demoClockOnly:'仅WebView演示时钟,未修改设备时间'});activeAction=null;
- }
- await new Promise(r=>setTimeout(r,1200));
- const metrics=await cdp.evaluate(()=>({path:location.pathname,visible:document.visibilityState,viewport:{width:innerWidth,height:innerHeight,dpr:devicePixelRatio},width:document.documentElement.clientWidth,scrollWidth:document.documentElement.scrollWidth,title:document.querySelector('.m-title-main')?.textContent.trim(),dialogs:[...document.querySelectorAll('[role=dialog]')].filter(el=>{const r=el.getBoundingClientRect();return r.width>0&&r.right>0&&r.left<innerWidth&&r.bottom>0&&r.top<innerHeight}).map(el=>({label:el.getAttribute('aria-label'),text:el.textContent.trim().slice(0,80)}))}));
- const file=out+'/review-'+revision+'-first-native.png';if(!fs.existsSync(file))captureNativeScreenshot(file,serial);
- updateNativeReview(s=>{s.reviewFirstMetrics=metrics;s.blockedReviewRequests=[...(s.blockedReviewRequests||[]),...blocked]});nativeCheck('独立包首屏真实WebView可见且无横向溢出',metrics.visible==='visible'&&metrics.width===metrics.scrollWidth,{metrics,file,sourceMode:'mock-production'});
- console.log(JSON.stringify({metrics,file,session:readNativeReview().reviewSession,blockedRequests:blocked.length},null,2));
- }catch(error){if(activeAction)failNativeAction(activeAction,error);else updateNativeReview(s=>s.failures.push({stage:'setup_'+revision,message:error.message,at:new Date().toISOString()}));console.error(error);process.exitCode=1}finally{cdp?.close()}
|