review-statusbar-native.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. /** 2026-12-01 状态栏修复真机验证:独立账本,更新安装保留登录,不发送业务数据。 */
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. import assert from 'node:assert/strict';
  5. import { spawnSync } from 'node:child_process';
  6. import { createHash } from 'node:crypto';
  7. import { readRealReview, updateRealReview } from './lib/real-account-review-ledger.mjs';
  8. import { beginNativeAction, finishNativeAction, updateNativeReview } from './lib/native-ui-review-ledger.mjs';
  9. import { connectWebView, captureNativeScreenshot } from './android-webview-cdp.mjs';
  10. const phase = process.argv.find(x => x.startsWith('--phase='))?.slice(8);
  11. assert.ok(['baseline', 'install', 'verify'].includes(phase));
  12. const dir = 'test-results/statusbar-refinement-20261201';
  13. fs.mkdirSync(dir, { recursive: true });
  14. const ledger = path.resolve(dir, 'state.json');
  15. const serial = '3e529a34', packageId = 'cn.fmode.app';
  16. const revision = process.argv.find(x => x.startsWith('--revision='))?.slice(11) || 'r4';
  17. assert.ok(['r4', 'r5', 'r6'].includes(revision), '仅支持已登记的状态栏修订');
  18. assert.ok(phase !== 'baseline' || revision === 'r4', '旧基线不重做');
  19. if (!fs.existsSync(ledger)) fs.writeFileSync(ledger, JSON.stringify({ version: 1, serial, packageId, revision, actions: {}, checks: [], failures: [], screenshots: [] }, null, 2), { flag: 'wx' });
  20. const read = () => JSON.parse(fs.readFileSync(ledger, 'utf8'));
  21. const save = fn => updateNativeReview(fn, ledger);
  22. const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
  23. const adb = (args, timeout = 30000) => {
  24. const r = spawnSync('adb', ['-s', serial, ...args], { encoding: 'utf8', timeout, windowsHide: true, maxBuffer: 10 * 1024 * 1024 });
  25. assert.equal(r.status, 0, r.error?.message || r.stderr || 'ADB失败'); return r.stdout.trim();
  26. };
  27. const installed = () => {
  28. const apk = adb(['shell', 'pm', 'path', packageId]).split(/\r?\n/).find(x => x.startsWith('package:'))?.slice(8);
  29. assert.ok(apk); return { apk, sha256: adb(['shell', 'sha256sum', apk]).split(/\s+/)[0] };
  30. };
  31. const expected = rev => {
  32. const build = readRealReview().actions['build_' + rev];
  33. assert.equal(build?.status, 'confirmed'); return build.receipt;
  34. };
  35. async function action(id, target, fn) {
  36. const old = read().actions[id];
  37. if (old) throw Error(`动作已登记:${id}/${old.status},先读回,不重放`);
  38. beginNativeAction(id, target, {}, ledger);
  39. try { const result = await fn(); finishNativeAction(id, result, ledger); return result; }
  40. catch (error) { save(s => { s.actions[id].status = 'uncertain'; s.failures.push({ id, error: error.message, at: new Date().toISOString() }); }); throw error; }
  41. }
  42. function check(name, pass, evidence = {}) {
  43. save(s => s.checks.push({ name, pass: !!pass, evidence, at: new Date().toISOString() }));
  44. assert.ok(pass, name);
  45. }
  46. function foreground() {
  47. assert.match(adb(['shell', 'dumpsys', 'activity', 'activities']), /topResumedActivity=.*cn\.fmode\.app\//, '不操作其他应用');
  48. }
  49. async function connect(rev) {
  50. assert.equal(installed().sha256, expected(rev).sha256);
  51. const pid = adb(['shell', 'pidof', packageId]); assert.match(pid, /^\d+$/);
  52. const port = rev === 'r3' ? 12228 : rev === 'r4' ? 12229 : 12230;
  53. const remote = 'localabstract:webview_devtools_remote_' + pid;
  54. const rows = adb(['forward', '--list']).split(/\r?\n/).map(x => x.trim().split(/\s+/));
  55. const old = rows.find(x => x[1] === 'tcp:' + port);
  56. if (old) assert.ok(old[0] === serial && old[2] === remote, '不覆盖其他调试连接');
  57. else await action('forward-' + rev + '-' + pid, { serial, port, remote }, async () => ({ output: adb(['forward', '--no-rebind', 'tcp:' + port, remote]) }));
  58. const version = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json();
  59. assert.equal(version['Android-Package'], packageId);
  60. const cdp = await connectWebView(port);
  61. return { cdp, session: { revision: rev, pid, port, serial, packageId, sourceMode: 'production-real', at: new Date().toISOString() } };
  62. }
  63. let cdp;
  64. async function snapshot(id) {
  65. foreground();
  66. assert.ok(!fs.existsSync(path.join(dir, id + '.png')), '不覆盖原截图');
  67. const data = await cdp.evaluate(async () => {
  68. const rect = e => { const r = e.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height, bottom: r.bottom }; };
  69. let me; try { me = JSON.parse(localStorage.getItem('fmode_me') || 'null'); } catch { me = null; }
  70. return { path: location.pathname, width: innerWidth, height: innerHeight, scrollWidth: document.documentElement.scrollWidth,
  71. dark: document.documentElement.classList.contains('dark'), safeTop: getComputedStyle(document.documentElement).getPropertyValue('--mob-safe-top').trim(),
  72. canvas: getComputedStyle(document.documentElement).getPropertyValue('--canvas').trim(),
  73. palette: document.documentElement.getAttribute('data-palette'),
  74. nativeSafeTop: document.documentElement.style.getPropertyValue('--safe-area-inset-top'),
  75. bar: await window.Capacitor.Plugins.StatusBar.getInfo(), me: me ? { id: me.id, mobile: me.mobile } : null,
  76. 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) })) };
  77. });
  78. fs.writeFileSync(path.join(dir, id + '.json'), JSON.stringify(data, null, 2), { flag: 'wx' });
  79. captureNativeScreenshot(path.join(dir, id + '.png'), serial);
  80. save(s => s.screenshots.push({ id, file: path.join(dir, id + '.png'), path: data.path, at: new Date().toISOString() }));
  81. return data;
  82. }
  83. async function tap(id, selector) {
  84. foreground();
  85. return action(id, { selector, path: await cdp.evaluate(() => location.pathname) }, async () => {
  86. await cdp.evaluate(selector => {
  87. const e = document.querySelector(selector); if (!e) throw Error('找不到控件:' + selector);
  88. e.scrollIntoView({ block: 'center' }); const r = e.getBoundingClientRect(), hit = document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2);
  89. if (e.disabled || (hit !== e && !e.contains(hit))) throw Error('控件禁用或被遮挡');
  90. }, selector);
  91. await cdp.tap(selector); await sleep(700); return { path: await cdp.evaluate(() => location.pathname) };
  92. });
  93. }
  94. try {
  95. assert.equal(adb(['get-state']), 'device');
  96. if (phase === 'baseline') {
  97. assert.equal(installed().sha256, expected('r3').sha256);
  98. // 手机连接正常但App已关闭:登记明确打开目标,不把pidof返回1当成设备断线。
  99. const process = spawnSync('adb', ['-s', serial, 'shell', 'pidof', packageId], { encoding: 'utf8', windowsHide: true });
  100. if (process.status === 1 && !process.stdout.trim()) {
  101. await action('baseline-launch-r3', { serial, packageId, preserveData: true }, async () => ({ output: adb(['shell', 'am', 'start', '-W', '-n', packageId + '/.MainActivity']) }));
  102. await sleep(6500);
  103. }
  104. ({ cdp } = await connect('r3'));
  105. const baseline = await snapshot('baseline-r3');
  106. check('更新前账号匹配', baseline.me?.id === 'wXuLfZrkgp');
  107. save(s => { s.baseline = baseline; s.stage = 'baseline_recorded'; });
  108. console.log(JSON.stringify({ phase, me: baseline.me, path: baseline.path, statusBar: baseline.bar, safeTop: baseline.safeTop }));
  109. } else if (phase === 'install') {
  110. assert.equal(read().baseline?.me?.id, 'wXuLfZrkgp', '必须先留存真实登录基线');
  111. const receipt = expected(revision);
  112. assert.equal(installed().sha256, expected(revision === 'r4' ? 'r3' : 'r4').sha256, '安装前设备须匹配已知上一版,不重复安装');
  113. assert.equal(createHash('sha256').update(fs.readFileSync(receipt.apk)).digest('hex'), receipt.sha256);
  114. await action('install-' + revision, { serial, packageId, apk: receipt.apk, sha256: receipt.sha256, previous: installed(), preserveData: true }, async () => {
  115. const result = spawnSync('adb', ['-s', serial, 'install', '-r', '--no-streaming', receipt.apk], { encoding: 'utf8', timeout: 180000, windowsHide: true });
  116. fs.writeFileSync(path.join(dir, 'install-' + revision + '.log'), (result.stdout || '') + (result.stderr || ''), { flag: 'wx' });
  117. const actual = installed(); assert.equal(actual.sha256, receipt.sha256, '安装结果不明,禁止盲重试');
  118. return { actual, exitCode: result.status };
  119. });
  120. await action('launch-' + revision, { serial, packageId, activity: packageId + '.MainActivity' }, async () => ({ output: adb(['shell', 'am', 'start', '-W', '-n', packageId + '/.MainActivity']) }));
  121. await sleep(7000);
  122. const connected = await connect(revision); cdp = connected.cdp;
  123. const current = await snapshot('installed-' + revision);
  124. check('更新安装保留原登录身份', current.me?.id === read().baseline.me.id, { before: read().baseline.me, after: current.me });
  125. save(s => { s.session = connected.session; s.revision = revision; s.stage = 'installed_' + revision; });
  126. updateRealReview(s => { s.reviewSession = connected.session; s.stage = 'statusbar_refinement_' + revision + '_installed'; });
  127. console.log(JSON.stringify({ phase, revision, sha256: receipt.sha256, identity: current.me, bar: current.bar, safeTop: current.safeTop }));
  128. } else {
  129. assert.equal(read().stage, 'installed_' + revision, '不重放已进行过的实测阶段');
  130. ({ cdp } = await connect(revision));
  131. save(s => { s.stage = 'native_verification_running_' + revision; });
  132. for (const [route, index] of [['messages', 1], ['contacts', 2], ['workbench', 3], ['mine', 4]]) {
  133. await tap(revision + '-tab-' + route, `.m-tabbar button:nth-of-type(${index})`);
  134. await cdp.waitFor(route => location.pathname === '/mobile/' + route, route, 10000);
  135. const data = await snapshot(revision + '-' + route);
  136. check(route + '状态栏持续显示', data.bar.visible === true, data.bar);
  137. check(route + '无横向溢出', data.scrollWidth <= data.width + 1);
  138. const menu = data.controls.find(x => x.label === '打开导航');
  139. check(route + '菜单不覆盖状态栏', !!menu && menu.rect.y >= parseFloat(data.safeTop) - 1, { menu: menu?.rect, safeTop: data.safeTop, nativeSafeTop: data.nativeSafeTop });
  140. }
  141. const originalDark = await cdp.evaluate(() => document.documentElement.classList.contains('dark'));
  142. await tap(revision + '-theme-toggle', '.m-switch');
  143. const alternate = await snapshot(revision + '-theme-alternate');
  144. check('主题切换后状态栏可见且图标样式匹配', alternate.bar.visible && alternate.bar.style === (alternate.dark ? 'DARK' : 'LIGHT'), { dark: alternate.dark, bar: alternate.bar });
  145. await tap(revision + '-theme-restore', '.m-switch');
  146. check('主题偏好已恢复', await cdp.evaluate(original => document.documentElement.classList.contains('dark') === original, originalDark));
  147. const notification = await cdp.evaluate(() => {
  148. const matches = [...document.querySelectorAll('button.m-row')].filter(e => e.innerText.includes('消息与任务通知'));
  149. if (matches.length !== 1) throw Error('通知入口不唯一'); matches[0].setAttribute('data-statusbar-review', 'notification'); return '[data-statusbar-review="notification"]';
  150. });
  151. await tap(revision + '-notification-guide-open', notification);
  152. await cdp.waitFor(() => !!document.querySelector('.pg-root'), true, 6000);
  153. const guide = await snapshot(revision + '-notification-guide');
  154. const close = guide.controls.find(x => x.label === '关闭' && x.cls.includes('pg-close'));
  155. check('TOUCH-001通知关闭热区至少44px', !!close && close.rect.width >= 44 && close.rect.height >= 44, { rect: close?.rect });
  156. await tap(revision + '-notification-guide-close', '.pg-root .pg-close');
  157. check('关闭后通知说明消失', await cdp.evaluate(() => !document.querySelector('.pg-root')));
  158. await action(revision + '-background-home', { key: 'KEYCODE_HOME' }, async () => ({ output: adb(['shell', 'input', 'keyevent', 'KEYCODE_HOME']) }));
  159. await sleep(1000);
  160. await action(revision + '-resume-app', { activity: packageId + '/.MainActivity' }, async () => ({ output: adb(['shell', 'am', 'start', '-W', '-n', packageId + '/.MainActivity']) }));
  161. await sleep(1200);
  162. const resumed = await snapshot(revision + '-resumed');
  163. check('回到前台后状态栏和会话身份保留', resumed.bar.visible === true && resumed.me?.id === read().baseline.me.id);
  164. save(s => { s.stage = 'native_verified'; s.completedAt = new Date().toISOString(); });
  165. console.log(JSON.stringify({ phase, stage: read().stage, checks: read().checks.length, screenshots: read().screenshots.length }));
  166. }
  167. } catch (error) {
  168. save(s => { s.failures.push({ phase, message: error.message, at: new Date().toISOString() }); s.lastFailure = { phase, message: error.message }; });
  169. console.error(error); process.exitCode = 1;
  170. } finally { cdp?.close(); }