#!/usr/bin/env node /** 真机独立Mock包UI检查;不连接原App、不触发真实业务动作。 */ import fs from 'node:fs'; import {spawnSync} from 'node:child_process'; import {connectWebView,captureNativeScreenshot} from './android-webview-cdp.mjs'; import {readNativeReview,beginNativeAction,finishNativeAction,failNativeAction,nativeCheck,updateNativeReview} from './lib/native-ui-review-ledger.mjs'; const phase=process.argv.find(x=>x.startsWith('--phase='))?.split('=')[1]||'basics'; const revision=process.argv.find(x=>x.startsWith('--revision='))?.split('=')[1]||'r1'; const attempt=Number(process.argv.find(x=>x.startsWith('--attempt='))?.split('=')[1]||'1'); if(!Number.isInteger(attempt)||attempt<1||attempt>9)throw Error('非法检查尝试编号'); if(!['basics','keyboard','appearance','projects','permission'].includes(phase)||!/^r[1-9][0-9]*$/.test(revision))throw Error('非法检查阶段'); const state=readNativeReview(),serial=state.device.serial,session=state.reviewSession,receipt=state.actions['build_'+revision]?.receipt; if(session?.packageId!=='cn.fmode.app.uitest'||session.revision!==revision||!receipt)throw Error('没有匹配的独立Mock包会话'); const adb=args=>{const r=spawnSync('adb',['-s',serial,...args],{encoding:'utf8',timeout:30000,windowsHide:true});if(r.status!==0)throw Error(r.stderr||r.stdout||r.error?.message||'adb失败');return r.stdout.trim()}; if(adb(['shell','pidof',session.packageId])!==session.pid)throw Error('测试包进程已变化;先只读核实会话'); const installed=adb(['shell','pm','path',session.packageId]).split(/\r?\n/).find(x=>x.startsWith('package:'))?.slice(8); if(!installed||adb(['shell','sha256sum',installed]).split(/\s+/)[0]!==receipt.sha256)throw Error('安装包摘要与账本不符'); const suffix=attempt===1?'':'-attempt'+attempt; const key='native_'+revision+'_'+phase+suffix; if(state.actions[key]){console.log(JSON.stringify(state.actions[key],null,2));process.exit(state.actions[key].status==='confirmed'?0:1)} beginNativeAction(key,{serial,packageId:session.packageId,phase,revision,scope:'独立Mock包内UI与演示交互;不发送真实消息或修改原包'}); let cdp;const files=[],blocked=[];const initialChecks=readNativeReview().checks.length; const sleep=ms=>new Promise(r=>setTimeout(r,ms)); try{ if(!/mWakefulness=Awake/.test(adb(['shell','dumpsys','power']))){adb(['shell','input','keyevent','KEYCODE_WAKEUP']);await sleep(300)} const policy=adb(['shell','dumpsys','window','policy']); if(/showing=true/.test(policy)){ if(!/secure=false/.test(policy))throw Error('手机有凭据锁,请在设备上解锁后继续'); adb(['shell','wm','dismiss-keyguard']); } const resumed=adb(['shell','dumpsys','activity','activities']).split(/\r?\n/).filter(x=>/topResumedActivity=|mResumedActivity:|ResumedActivity:/.test(x)); if(!resumed.length||!resumed.every(x=>x.includes(session.packageId+'/')))throw Error('独立测试包不在前台,不操作其他应用'); cdp=await connectWebView(session.port,{onEvent:(message,send)=>{ if(message.method!=='Fetch.requestPaused')return; const url=new URL(message.params.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}); 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 check=(name,pass,evidence={})=>{nativeCheck(revision+' '+name,pass,evidence);console.log((pass?'PASS ':'FAIL ')+name)}; const shot=async name=>{await sleep(300);const file='test-results/native-ui-20261130/'+revision+'-'+name+suffix+'.png';captureNativeScreenshot(file,serial);files.push(file);return file}; const tap=async selector=>{ const available=await cdp.evaluate(selector=>{const el=document.querySelector(selector);if(!el)return false;el.scrollIntoView({block:'nearest'});const r=el.getBoundingClientRect();const hit=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2);return r.width>0&&r.height>0&&r.top>=0&&r.bottom<=innerHeight+1&&(el===hit||el.contains(hit))},selector); if(!available)throw Error('目标不可见或被遮挡:'+selector);await cdp.tap(selector);await sleep(200); }; const textTap=async(text,scope='body')=>{const selector=await cdp.evaluate(({text,scope})=>{document.querySelectorAll('[data-native-review-target]').forEach(el=>el.removeAttribute('data-native-review-target'));const matches=[...document.querySelectorAll(scope+' button')].filter(el=>el.textContent.trim()===text&&el.getBoundingClientRect().width>0);if(matches.length!==1)throw Error('按钮不唯一:'+text+' '+matches.length);matches[0].setAttribute('data-native-review-target','current');return '[data-native-review-target="current"]'},{text,scope});await tap(selector)}; const metrics=()=>cdp.evaluate(()=>{const rr=el=>{if(!el)return null;const r=el.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height,bottom:r.bottom,right:r.right}};return {path:location.pathname,visible:document.visibilityState,width:innerWidth,height:innerHeight,visualHeight:visualViewport?.height,scrollWidth:document.documentElement.scrollWidth,title:document.querySelector('.m-title-main')?.textContent.trim(),titleRect:rr(document.querySelector('.m-title-main')),rightRect:rr(document.querySelector('.m-bar-right')),dock:rr(document.querySelector('app-m-dock')),textarea:rr(document.querySelector('app-m-dock textarea')),send:rr(document.querySelector('.m-send')),tabbar:rr(document.querySelector('.m-tabbar'))}}); const layout=async name=>{const m=await metrics();check(name,m.visible==='visible'&&m.width===m.scrollWidth&&(!m.titleRect||!m.rightRect||m.titleRect.right<=m.rightRect.x+1),m);return m}; const go=async route=>{await cdp.send('Page.navigate',{url:'https://localhost/mobile/'+route});await cdp.waitFor(r=>decodeURIComponent(location.pathname)==='/mobile/'+r&&document.querySelector('.m-title-main'),route);await sleep(500)}; if(phase==='basics'){ if(await cdp.evaluate(()=>!!document.querySelector('.pg-root')))await textTap('暂不开启','.pg-root'); await layout('会话列表无横向溢出或标题重叠');await shot('messages'); for(const [route,index] of [['contacts',2],['workbench',3],['mine',4],['messages',1]]){await tap('.m-tabbar button:nth-of-type('+index+')');await cdp.waitFor(r=>location.pathname==='/mobile/'+r,route);await layout(route+'真机导航与布局');await shot(route+'-nav')} await tap('[aria-label="打开导航"]');await cdp.waitFor(()=>document.querySelector('.m-drawer.show')); const drawer=await cdp.evaluate(()=>{const el=document.querySelector('.m-drawer.show'),r=el.getBoundingClientRect();const tab=document.querySelector('.m-tabbar');return {width:r.width,height:r.height,screen:innerHeight,tabDisplay:tab?getComputedStyle(tab).display:'none',text:el.innerText.slice(0,500)}}); check('抽屉覆盖底栏且未超出屏幕',drawer.height<=drawer.screen+1&&drawer.tabDisplay==='none',drawer);await shot('drawer'); await go('chat/zhixia/$ui-review-0');await layout('聊天页真机布局');await shot('chat'); const dom=await cdp.evaluate(()=>({text:document.body.innerText.slice(-1800),buttons:[...document.querySelectorAll('button')].filter(el=>{const r=el.getBoundingClientRect();return r.width>0&&r.height>0}).map(el=>({text:el.textContent.trim().slice(0,50),label:el.getAttribute('aria-label'),class:el.className}))})); updateNativeReview(s=>{s.nativeChatProbe=dom}); } if(phase==='keyboard'){ await go('chat/zhixia/$ui-review-0');const before=await metrics();await tap('app-m-dock textarea'); await sleep(1200);const ime=adb(['shell','dumpsys','input_method']);const shown=/mInputShown=true|isInputViewShown=true/.test(ime);const after=await metrics(); check('Android真实软键盘已弹出',shown,{before,after});check('软键盘上方输入区与发送按钮完整可见',shown&&after.send?.bottom<=after.height+1&&after.textarea?.y>=0&&after.heightbefore.textarea.height&&multiline.send.bottom<=multiline.height+1,multiline);await shot('keyboard-multiline'); await tap('.m-send');await cdp.waitFor(()=>document.querySelector('app-m-dock textarea')?.value==='');await sleep(1500); check('独立Mock会话发送后清空输入且展示演示消息',await cdp.evaluate(()=>document.body.innerText.includes('真机界面检查(演示)')),{scope:'独立Mock包,不代表真实收发验收'});await shot('mock-sent'); if(/mInputShown=true|isInputViewShown=true/.test(adb(['shell','dumpsys','input_method'])))adb(['shell','input','keyevent','KEYCODE_BACK']); } if(phase==='appearance'){ await go('mine'); await tap('[role="switch"][aria-label="深色模式"]');const dark=await cdp.evaluate(()=>document.documentElement.classList.contains('dark'));check('真机深色设置生效',dark);await layout('深色设置布局');await shot('mine-dark'); for(let i=1;i<=4;i++){await tap('.m-palette:nth-child('+i+')');const p=await cdp.evaluate(i=>({pressed:document.querySelector('.m-palette:nth-child('+i+')').getAttribute('aria-pressed'),id:document.documentElement.getAttribute('data-palette')||document.documentElement.getAttribute('data-accent')}),i);check('真机第'+i+'套配色可切换',p.pressed==='true',p)} await tap('.m-palette:nth-child(4)');await tap('[role="switch"][aria-label="深色模式"]'); await cdp.fill('input[aria-label="正文大小"]','20');await textTap('大','.m-ui-scale');await layout('大字设置无溢出');await shot('mine-large'); await go('chat/zhixia/$ui-review-0');await layout('大字聊天无溢出');await shot('chat-large'); await go('mine');await cdp.fill('input[aria-label="正文大小"]','16');await textTap('标准','.m-ui-scale');await tap('.m-palette:nth-child(1)'); } if(phase==='projects'){ await go('chat/zhixia/$ui-review-0');await tap('[aria-label="选择项目并切换对话"]');await cdp.waitFor(()=>document.querySelector('.m-project-root')); await layout('项目切换弹层无横向溢出');await shot('projects'); await textTap('产品研究 4','.m-project-list'); } if(phase==='permission'){ await go('mine');await textTap('消息与任务通知 未开启');await shot('permission'); } const runtimeErrors=cdp.events.filter(x=>x.method==='Runtime.exceptionThrown'||x.method==='Review.eventHandlerError');check(phase+'无未处理运行时错误',runtimeErrors.length===0,{runtimeErrors}); const checks=readNativeReview().checks.slice(initialChecks),failed=checks.filter(x=>!x.pass); finishNativeAction(key,{files,checks:checks.length,failed:failed.length,blockedRequests:blocked,at:new Date().toISOString()}); console.log(JSON.stringify({phase,files,checks:checks.length,failed:failed.length}));if(failed.length)process.exitCode=1; }catch(error){failNativeAction(key,error);console.error(error);process.exitCode=1}finally{cdp?.close()}