/** 2026-12-01 状态栏修复真机验证:独立账本,更新安装保留登录,不发送业务数据。 */ import fs from 'node:fs'; import path from 'node:path'; import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import { readRealReview, updateRealReview } from './lib/real-account-review-ledger.mjs'; import { beginNativeAction, finishNativeAction, updateNativeReview } from './lib/native-ui-review-ledger.mjs'; import { connectWebView, captureNativeScreenshot } from './android-webview-cdp.mjs'; const phase = process.argv.find(x => x.startsWith('--phase='))?.slice(8); assert.ok(['baseline', 'install', 'verify'].includes(phase)); const dir = 'test-results/statusbar-refinement-20261201'; fs.mkdirSync(dir, { recursive: true }); const ledger = path.resolve(dir, 'state.json'); const serial = '3e529a34', packageId = 'cn.fmode.app'; const revision = process.argv.find(x => x.startsWith('--revision='))?.slice(11) || 'r4'; assert.ok(['r4', 'r5', 'r6'].includes(revision), '仅支持已登记的状态栏修订'); assert.ok(phase !== 'baseline' || revision === 'r4', '旧基线不重做'); if (!fs.existsSync(ledger)) fs.writeFileSync(ledger, JSON.stringify({ version: 1, serial, packageId, revision, actions: {}, checks: [], failures: [], screenshots: [] }, null, 2), { flag: 'wx' }); const read = () => JSON.parse(fs.readFileSync(ledger, 'utf8')); const save = fn => updateNativeReview(fn, ledger); const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); const adb = (args, timeout = 30000) => { const r = spawnSync('adb', ['-s', serial, ...args], { encoding: 'utf8', timeout, windowsHide: true, maxBuffer: 10 * 1024 * 1024 }); assert.equal(r.status, 0, r.error?.message || r.stderr || 'ADB失败'); return r.stdout.trim(); }; const installed = () => { const apk = adb(['shell', 'pm', 'path', packageId]).split(/\r?\n/).find(x => x.startsWith('package:'))?.slice(8); assert.ok(apk); return { apk, sha256: adb(['shell', 'sha256sum', apk]).split(/\s+/)[0] }; }; const expected = rev => { const build = readRealReview().actions['build_' + rev]; assert.equal(build?.status, 'confirmed'); return build.receipt; }; async function action(id, target, fn) { const old = read().actions[id]; if (old) throw Error(`动作已登记:${id}/${old.status},先读回,不重放`); beginNativeAction(id, target, {}, ledger); try { const result = await fn(); finishNativeAction(id, result, ledger); return result; } catch (error) { save(s => { s.actions[id].status = 'uncertain'; s.failures.push({ id, error: error.message, at: new Date().toISOString() }); }); throw error; } } function check(name, pass, evidence = {}) { save(s => s.checks.push({ name, pass: !!pass, evidence, at: new Date().toISOString() })); assert.ok(pass, name); } function foreground() { assert.match(adb(['shell', 'dumpsys', 'activity', 'activities']), /topResumedActivity=.*cn\.fmode\.app\//, '不操作其他应用'); } async function connect(rev) { assert.equal(installed().sha256, expected(rev).sha256); const pid = adb(['shell', 'pidof', packageId]); assert.match(pid, /^\d+$/); const port = rev === 'r3' ? 12228 : rev === 'r4' ? 12229 : 12230; const remote = 'localabstract:webview_devtools_remote_' + pid; const rows = adb(['forward', '--list']).split(/\r?\n/).map(x => x.trim().split(/\s+/)); const old = rows.find(x => x[1] === 'tcp:' + port); if (old) assert.ok(old[0] === serial && old[2] === remote, '不覆盖其他调试连接'); else await action('forward-' + rev + '-' + pid, { serial, port, remote }, async () => ({ output: adb(['forward', '--no-rebind', 'tcp:' + port, remote]) })); const version = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json(); assert.equal(version['Android-Package'], packageId); const cdp = await connectWebView(port); return { cdp, session: { revision: rev, pid, port, serial, packageId, sourceMode: 'production-real', at: new Date().toISOString() } }; } let cdp; async function snapshot(id) { foreground(); assert.ok(!fs.existsSync(path.join(dir, id + '.png')), '不覆盖原截图'); const data = await cdp.evaluate(async () => { const rect = e => { const r = e.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height, bottom: r.bottom }; }; let me; try { me = JSON.parse(localStorage.getItem('fmode_me') || 'null'); } catch { me = null; } return { path: location.pathname, width: innerWidth, height: innerHeight, scrollWidth: document.documentElement.scrollWidth, dark: document.documentElement.classList.contains('dark'), safeTop: getComputedStyle(document.documentElement).getPropertyValue('--mob-safe-top').trim(), canvas: getComputedStyle(document.documentElement).getPropertyValue('--canvas').trim(), palette: document.documentElement.getAttribute('data-palette'), nativeSafeTop: document.documentElement.style.getPropertyValue('--safe-area-inset-top'), bar: await window.Capacitor.Plugins.StatusBar.getInfo(), me: me ? { id: me.id, mobile: me.mobile } : null, controls: [...document.querySelectorAll('button,input,textarea')].filter(e => { const r = e.getBoundingClientRect(); return r.width > 0 && r.height > 0; }).map(e => ({ label: e.getAttribute('aria-label'), text: e.matches('input,textarea') ? '' : e.textContent.trim().replace(/\s+/g, ' ').slice(0, 80), cls: String(e.className), rect: rect(e) })) }; }); fs.writeFileSync(path.join(dir, id + '.json'), JSON.stringify(data, null, 2), { flag: 'wx' }); captureNativeScreenshot(path.join(dir, id + '.png'), serial); save(s => s.screenshots.push({ id, file: path.join(dir, id + '.png'), path: data.path, at: new Date().toISOString() })); return data; } async function tap(id, selector) { foreground(); return action(id, { selector, path: await cdp.evaluate(() => location.pathname) }, async () => { await cdp.evaluate(selector => { const e = document.querySelector(selector); if (!e) throw Error('找不到控件:' + selector); e.scrollIntoView({ block: 'center' }); const r = e.getBoundingClientRect(), hit = document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2); if (e.disabled || (hit !== e && !e.contains(hit))) throw Error('控件禁用或被遮挡'); }, selector); await cdp.tap(selector); await sleep(700); return { path: await cdp.evaluate(() => location.pathname) }; }); } try { assert.equal(adb(['get-state']), 'device'); if (phase === 'baseline') { assert.equal(installed().sha256, expected('r3').sha256); // 手机连接正常但App已关闭:登记明确打开目标,不把pidof返回1当成设备断线。 const process = spawnSync('adb', ['-s', serial, 'shell', 'pidof', packageId], { encoding: 'utf8', windowsHide: true }); if (process.status === 1 && !process.stdout.trim()) { await action('baseline-launch-r3', { serial, packageId, preserveData: true }, async () => ({ output: adb(['shell', 'am', 'start', '-W', '-n', packageId + '/.MainActivity']) })); await sleep(6500); } ({ cdp } = await connect('r3')); const baseline = await snapshot('baseline-r3'); check('更新前账号匹配', baseline.me?.id === 'wXuLfZrkgp'); save(s => { s.baseline = baseline; s.stage = 'baseline_recorded'; }); console.log(JSON.stringify({ phase, me: baseline.me, path: baseline.path, statusBar: baseline.bar, safeTop: baseline.safeTop })); } else if (phase === 'install') { assert.equal(read().baseline?.me?.id, 'wXuLfZrkgp', '必须先留存真实登录基线'); const receipt = expected(revision); assert.equal(installed().sha256, expected(revision === 'r4' ? 'r3' : 'r4').sha256, '安装前设备须匹配已知上一版,不重复安装'); assert.equal(createHash('sha256').update(fs.readFileSync(receipt.apk)).digest('hex'), receipt.sha256); await action('install-' + revision, { serial, packageId, apk: receipt.apk, sha256: receipt.sha256, previous: installed(), preserveData: true }, async () => { 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'), (result.stdout || '') + (result.stderr || ''), { flag: 'wx' }); const actual = installed(); assert.equal(actual.sha256, receipt.sha256, '安装结果不明,禁止盲重试'); return { actual, exitCode: result.status }; }); await action('launch-' + revision, { serial, packageId, activity: packageId + '.MainActivity' }, async () => ({ output: adb(['shell', 'am', 'start', '-W', '-n', packageId + '/.MainActivity']) })); await sleep(7000); const connected = await connect(revision); cdp = connected.cdp; const current = await snapshot('installed-' + revision); check('更新安装保留原登录身份', current.me?.id === read().baseline.me.id, { before: read().baseline.me, after: current.me }); save(s => { s.session = connected.session; s.revision = revision; s.stage = 'installed_' + revision; }); updateRealReview(s => { s.reviewSession = connected.session; s.stage = 'statusbar_refinement_' + revision + '_installed'; }); console.log(JSON.stringify({ phase, revision, sha256: receipt.sha256, identity: current.me, bar: current.bar, safeTop: current.safeTop })); } else { assert.equal(read().stage, 'installed_' + revision, '不重放已进行过的实测阶段'); ({ cdp } = await connect(revision)); save(s => { s.stage = 'native_verification_running_' + revision; }); for (const [route, index] of [['messages', 1], ['contacts', 2], ['workbench', 3], ['mine', 4]]) { await tap(revision + '-tab-' + route, `.m-tabbar button:nth-of-type(${index})`); await cdp.waitFor(route => location.pathname === '/mobile/' + route, route, 10000); const data = await snapshot(revision + '-' + route); check(route + '状态栏持续显示', data.bar.visible === true, data.bar); check(route + '无横向溢出', data.scrollWidth <= data.width + 1); const menu = data.controls.find(x => x.label === '打开导航'); check(route + '菜单不覆盖状态栏', !!menu && menu.rect.y >= parseFloat(data.safeTop) - 1, { menu: menu?.rect, safeTop: data.safeTop, nativeSafeTop: data.nativeSafeTop }); } const originalDark = await cdp.evaluate(() => document.documentElement.classList.contains('dark')); await tap(revision + '-theme-toggle', '.m-switch'); const alternate = await snapshot(revision + '-theme-alternate'); check('主题切换后状态栏可见且图标样式匹配', alternate.bar.visible && alternate.bar.style === (alternate.dark ? 'DARK' : 'LIGHT'), { dark: alternate.dark, bar: alternate.bar }); await tap(revision + '-theme-restore', '.m-switch'); check('主题偏好已恢复', await cdp.evaluate(original => document.documentElement.classList.contains('dark') === original, originalDark)); const notification = await cdp.evaluate(() => { const matches = [...document.querySelectorAll('button.m-row')].filter(e => e.innerText.includes('消息与任务通知')); if (matches.length !== 1) throw Error('通知入口不唯一'); matches[0].setAttribute('data-statusbar-review', 'notification'); return '[data-statusbar-review="notification"]'; }); await tap(revision + '-notification-guide-open', notification); await cdp.waitFor(() => !!document.querySelector('.pg-root'), true, 6000); const guide = await snapshot(revision + '-notification-guide'); const close = guide.controls.find(x => x.label === '关闭' && x.cls.includes('pg-close')); check('TOUCH-001通知关闭热区至少44px', !!close && close.rect.width >= 44 && close.rect.height >= 44, { rect: close?.rect }); await tap(revision + '-notification-guide-close', '.pg-root .pg-close'); check('关闭后通知说明消失', await cdp.evaluate(() => !document.querySelector('.pg-root'))); await action(revision + '-background-home', { key: 'KEYCODE_HOME' }, async () => ({ output: adb(['shell', 'input', 'keyevent', 'KEYCODE_HOME']) })); await sleep(1000); await action(revision + '-resume-app', { activity: packageId + '/.MainActivity' }, async () => ({ output: adb(['shell', 'am', 'start', '-W', '-n', packageId + '/.MainActivity']) })); await sleep(1200); const resumed = await snapshot(revision + '-resumed'); check('回到前台后状态栏和会话身份保留', resumed.bar.visible === true && resumed.me?.id === read().baseline.me.id); save(s => { s.stage = 'native_verified'; s.completedAt = new Date().toISOString(); }); console.log(JSON.stringify({ phase, stage: read().stage, checks: read().checks.length, screenshots: read().screenshots.length })); } } catch (error) { save(s => { s.failures.push({ phase, message: error.message, at: new Date().toISOString() }); s.lastFailure = { phase, message: error.message }; }); console.error(error); process.exitCode = 1; } finally { cdp?.close(); }