/** 本轮真实包安装与启动,动作先落盘;结果不明先回读,不盲重装。 */ import fs from 'node:fs'; import path from 'node:path'; import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; import { spawn, spawnSync } from 'node:child_process'; import { beginNativeAction, finishNativeAction, updateNativeReview } from './lib/native-ui-review-ledger.mjs'; import { readRealReview, updateRealReview } from './lib/real-account-review-ledger.mjs'; import { captureNativeScreenshot } from './android-webview-cdp.mjs'; const dir='test-results/mobile-full-audit-20261130'; const file=path.resolve(dir,'state.json'); const read=()=>JSON.parse(fs.readFileSync(file,'utf8')); const state=read(),serial=state.device.serial,packageId=state.packageId,revision=state.revision; assert.equal(packageId,'cn.fmode.app'); assert.equal(state.sourceMode,'production-real'); const build=readRealReview().actions['build_'+revision]; assert.equal(build?.status,'confirmed'); const receipt=build.receipt; assert.equal(receipt.packageId,packageId); assert.equal(receipt.realData,true); const digest=bytes=>createHash('sha256').update(bytes).digest('hex'); assert.equal(digest(fs.readFileSync(receipt.apk)),receipt.sha256); const adb=(args,timeout=30000)=>{ const r=spawnSync('adb',['-s',serial,...args],{encoding:'utf8',timeout,windowsHide:true}); if(r.status!==0)throw Error(r.stderr||r.stdout||r.error?.message||'adb未确认成功');return r.stdout.trim(); }; assert.equal(adb(['get-state']),'device'); const installed=()=>{ const query=spawnSync('adb',['-s',serial,'shell','pm','path',packageId],{encoding:'utf8',timeout:30000,windowsHide:true}); // Android的pm在“尚未安装”时返回1且无输出,不是设备连接失败。 if(query.status===1&&!query.stdout?.trim()&&!query.stderr?.trim())return null; assert.equal(query.status,0,query.stderr||query.error?.message||'安装状态读取失败'); const apk=query.stdout.trim().split(/\r?\n/).find(x=>x.startsWith('package:'))?.slice(8); return apk?{apk,sha256:adb(['shell','sha256sum',apk]).split(/\s+/)[0]}:null; }; let active; try{ const installKey='install_'+revision+'_1'; if(read().actions[installKey]){ assert.equal(read().actions[installKey].status,'confirmed','旧安装结果未确认,停止,不重复安装'); assert.equal(installed()?.sha256,receipt.sha256,'现安装包已变化,停止'); }else{ beginNativeAction(installKey,{serial,packageId,revision,apk:receipt.apk,sha256:receipt.sha256,previous:installed(),preserveData:true}, {},file);active=installKey; const result=spawnSync('adb',['-s',serial,'install','-r','--no-streaming',receipt.apk],{encoding:'utf8',timeout:180000,windowsHide:true}); fs.writeFileSync(path.join(dir,'install-'+revision+'.log'),String(result.stdout||'')+String(result.stderr||'')+(result.error?'\n'+result.error.message:''),{flag:'wx'}); const actual=installed(); assert.equal(actual?.sha256,receipt.sha256,'安装未回读成功;先查看手机安装确认与日志,不盲重试'); finishNativeAction(installKey,{actual,commandExitCode:result.status,version:adb(['shell','dumpsys','package',packageId]).split(/\r?\n/).filter(x=>/versionCode=|versionName=/.test(x)).map(x=>x.trim())},file);active=null; } const launchKey='launch_'+revision+'_1'; if(read().actions[launchKey]){ assert.equal(read().actions[launchKey].status,'confirmed','旧启动结果未确认,先只读核实'); console.log(JSON.stringify({reused:true,session:read().session}));process.exit(0); } const badging=fs.readFileSync(path.join('test-results/real-account-20261130','build-'+revision,'apk-badging.txt'),'utf8'); const activity=/^launchable-activity: name='([^']+)'/m.exec(badging)?.[1]; assert.ok(activity?.startsWith(packageId+'.'),'未确认启动Activity'); const port=12226; assert.ok(!adb(['forward','--list']).split(/\r?\n/).some(row=>row.trim().split(/\s+/)[1]==='tcp:'+port),'调试端口已占用,不覆盖已有映射'); const videoDevice='/sdcard/fmode-audit-'+revision+'-'+Date.now()+'.mp4'; const videoLocal=path.join(dir,'startup-'+revision+'.mp4'); beginNativeAction(launchKey,{serial,packageId,activity,revision,port,videoDevice,videoLocal,sha256:receipt.sha256},{},file);active=launchKey; const videoFd=fs.openSync(path.join(dir,'startup-record.log'),'wx'); const video=spawn('adb',['-s',serial,'shell','screenrecord','--time-limit','10','--size','720x1600',videoDevice],{stdio:['ignore',videoFd,videoFd],windowsHide:true}); const videoDone=new Promise(resolve=>{video.once('exit',code=>{fs.closeSync(videoFd);resolve(code)});video.once('error',()=>resolve(-1))}); await new Promise(resolve=>setTimeout(resolve,300)); const start=adb(['shell','am','start','-W','-n',packageId+'/'+activity]); fs.writeFileSync(path.join(dir,'start-'+revision+'.log'),start+'\n',{flag:'wx'}); let pid=''; for(let i=0;i<30;i++){ try{pid=adb(['shell','pidof',packageId]);if(/^\d+$/.test(pid))break}catch{} await new Promise(resolve=>setTimeout(resolve,500)); } assert.match(pid,/^\d+$/,'未确认App主进程'); adb(['forward','--no-rebind','tcp:'+port,'localabstract:webview_devtools_remote_'+pid]); let version; for(let i=0;i<40;i++){ try{version=await(await fetch('http://127.0.0.1:'+port+'/json/version',{signal:AbortSignal.timeout(1500)})).json();if(version['Android-Package']===packageId)break}catch{} await new Promise(resolve=>setTimeout(resolve,500)); } assert.equal(version?.['Android-Package'],packageId,'DevTools实际包身份未确认'); const session={revision,pid,port,serial,packageId,sourceMode:'production-real',at:new Date().toISOString()}; updateNativeReview(s=>{s.session=session;s.build=receipt;s.stage='installed_prelogin_audit'},file); updateRealReview(s=>{s.reviewSession=session;s.stage='mobile_full_audit_installed_prelogin';s.mobileFullAudit.stage='installed_prelogin_audit'}); const videoExit=await videoDone; let videoResult={exitCode:videoExit}; if(videoExit===0){adb(['pull',videoDevice,videoLocal]);const bytes=fs.readFileSync(videoLocal);assert.ok(bytes.length>10000&&bytes.subarray(4,8).toString()==='ftyp','录屏未确认为完整MP4');videoResult={...videoResult,file:videoLocal,bytes:bytes.length,sha256:digest(bytes)}} const shot=path.join(dir,'installed-'+revision+'.png');captureNativeScreenshot(shot,serial); finishNativeAction(launchKey,{session,installed:installed(),video:videoResult,screenshot:shot},file);active=null; console.log(JSON.stringify({installed:true,revision,session,screenshot:shot,video:videoResult},null,2)); }catch(error){ if(active)updateNativeReview(s=>{s.actions[active].status='uncertain';s.failures.push({stage:active,message:error.message,at:new Date().toISOString()})},file); console.error(error.message);process.exitCode=1; }