Files
CyberGril/web/tests/hel875_shots.mjs
T

167 lines
15 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// HEL-875 browser check: drives headless Edge over CDP against tests/hel875_mock.mjs (reach-outs on an open page).
// Usage: node tests/hel875_shots.mjs <edge.exe> <outDir> [port]. Prints one PASS/FAIL line per check, exits 1 on any FAIL.
// A read is triggered the way a returning tab triggers it (visibilitychange), instead of waiting the 20 s interval.
import { spawn } from 'node:child_process';
import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
const [edge, out, portArg] = process.argv.slice(2);
const port = Number(portArg || 8875), base = `http://127.0.0.1:${port}`, cdpPort = 9475;
mkdirSync(out, { recursive: true });
const profile = join(tmpdir(), `hel875-edge-${Date.now()}`);
const browser = spawn(edge, ['--headless=new', `--remote-debugging-port=${cdpPort}`, `--user-data-dir=${profile}`, '--no-first-run', '--hide-scrollbars', '--force-color-profile=srgb', 'about:blank'], { stdio: 'ignore' });
const sleep = ms => new Promise(r => setTimeout(r, ms));
let targets;
for (let i = 0; i < 60 && !targets; i++) { try { targets = await (await fetch(`http://127.0.0.1:${cdpPort}/json`)).json(); } catch { await sleep(250); } }
const ws = new WebSocket(targets.find(t => t.type === 'page').webSocketDebuggerUrl);
await new Promise(r => ws.addEventListener('open', r, { once: true }));
let seq = 0; const waiting = new Map();
ws.addEventListener('message', ({ data }) => { const m = JSON.parse(data); if (m.id && waiting.has(m.id)) { const { ok, ko } = waiting.get(m.id); waiting.delete(m.id); m.error ? ko(new Error(m.error.message)) : ok(m.result); } });
const cdp = (method, params = {}) => new Promise((ok, ko) => { const id = ++seq; waiting.set(id, { ok, ko }); ws.send(JSON.stringify({ id, method, params })); });
const js = async expr => { const r = await cdp('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true }); if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || 'js error'); return r.result.value; };
const results = [];
const check = (name, ok, detail = '') => { results.push(ok); console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`); };
const ctl = async path => (await fetch(`${base}${path}`)).json();
const shot = async name => { const { data } = await cdp('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(out, `${name}.png`), Buffer.from(data, 'base64')); };
const click = async (selector, text = '') => js(`(() => { const el = [...document.querySelectorAll(${JSON.stringify(selector)})].find(e => e.offsetParent !== null && e.textContent.includes(${JSON.stringify(text)})); if (!el) return false; el.click(); return true; })()`);
const text = sel => js(`[...document.querySelectorAll(${JSON.stringify(sel)})].map(e => e.innerText).join('\\n')`);
const exists = sel => js(`!!document.querySelector(${JSON.stringify(sel)})`);
const said = () => js(`document.querySelector('.conversation .sr')?.textContent || ''`);
const status = () => js(`document.querySelector('.talk-status')?.innerText || ''`);
const read = async () => { await js(`document.dispatchEvent(new Event('visibilitychange')), true`); await sleep(700); };
const views = { desktop: { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false }, phone: { width: 390, height: 844, deviceScaleFactor: 2, mobile: true } };
async function view(v) { await cdp('Emulation.setDeviceMetricsOverride', views[v]); await cdp('Emulation.setTouchEmulationEnabled', { enabled: views[v].mobile, maxTouchPoints: 5 }); }
async function boot(theme, { fresh = false } = {}) {
await cdp('Page.navigate', { url: `${base}/` }); await sleep(500);
await js(`${fresh ? 'localStorage.clear();' : ''} localStorage.setItem('cg.theme', ${JSON.stringify(theme)}); sessionStorage.clear(); true`);
await cdp('Page.navigate', { url: `${base}/` }); await sleep(1800);
}
// Frames for the motion evidence: every ~80 ms for `ms`.
async function frames(name, ms) { const list = []; const end = Date.now() + ms; while (Date.now() < end) { const { data } = await cdp('Page.captureScreenshot', { format: 'jpeg', quality: 70 }); list.push(data); } list.forEach((d, i) => writeFileSync(join(out, `${name}-${String(i).padStart(2, '0')}.jpg`), Buffer.from(d, 'base64'))); return list.length; }
await cdp('Page.enable'); await cdp('Runtime.enable');
// Count any request for microphone, camera or notifications.
await cdp('Page.addScriptToEvaluateOnNewDocument', { source: `window.__asked = 0; try { const md = navigator.mediaDevices; if (md) md.getUserMedia = () => { window.__asked++; return Promise.reject(new Error('blocked')); }; } catch {} try { if (window.Notification) Notification.requestPermission = () => { window.__asked++; return Promise.resolve('denied'); }; } catch {}` });
// ── 1. First visit: the old reach-out in the record is history, not new. ──
await view('desktop'); await boot('moon', { fresh: true }); await ctl('/__log');
check('first visit marks existing history as seen', await js(`localStorage.getItem('cg.real.seen')`) === '3' && !(await exists('.nav-item.unread')) && (await text('.home .letter')).includes('最近说过的话'), await js(`localStorage.getItem('cg.real.seen')`));
await shot('01-moon-desktop-home-history');
// ── 2. A reach-out lands while the page is open on the home view. ──
await ctl('/__reach?text=' + encodeURIComponent('窗外的雨停了,想跟你说一声。'));
await js(`document.dispatchEvent(new Event('visibilitychange')), true`);
await frames('m1-reach-in', 1100);
check('on 此刻 the letter takes her real words with the nav mark; no second card', (await text('.home .letter')).includes('窗外的雨停了') && (await text('.home .letter')).includes('还没看') && await exists('.nav-item.unread') && !(await exists('.reach.show')));
check('it does not open the conversation by itself', await js(`!document.body.classList.contains('talk')`));
await shot('02-moon-desktop-home-letter');
// Repeated reads, a restarted epoch and a failed read add nothing and show nothing.
await read(); await read(); await ctl('/__epoch'); await read(); await ctl('/__down/1'); await read(); await read();
check('repeat/epoch/reconnect reads keep one copy and no error on screen', !(await exists('.toast.show')) && (await text('.home')).split('窗外的雨停了').length === 2);
// ── 3. Over 日子 the card speaks up; reply to her: the stage presents it; then it counts as seen. ──
await click('.nav-item', '日子'); await sleep(1300);
check('over 日子 the reach-out card shows her real words', (await text('.reach.show')).includes('窗外的雨停了'));
await shot('02b-moon-desktop-days-reach');
await click('.reach .btn-primary', '回她'); await sleep(1500);
check('回她 opens the conversation at her message', (await said()).includes('窗外的雨停了'), await said());
check('seen once shown on the stage: mark cleared, stored id advanced', !(await exists('.nav-item.unread')) && await js(`localStorage.getItem('cg.real.seen')`) === '6');
await shot('03-moon-desktop-talk-reach');
await click('.log-btn'); await sleep(900);
check('record holds it once, tagged as hers', (await text('.log-panel .scroll')).split('窗外的雨停了').length === 2 && (await text('.log-panel')).includes('她主动说的'));
await click('.log-panel .btn-round'); await sleep(600);
// ── 4. A reach-out during her answer waits; your draft stays. ──
await js(`(() => { const t = document.querySelector('textarea'); const set = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set; set.call(t, '我刚到家'); t.dispatchEvent(new Event('input', { bubbles: true })); return true; })()`);
await js(`document.querySelector('.send').click(), true`); await sleep(1200);
await js(`(() => { const t = document.querySelector('textarea'); const set = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set; set.call(t, '还没写完的草稿'); t.dispatchEvent(new Event('input', { bubbles: true })); return true; })()`);
await ctl('/__reach?text=' + encodeURIComponent('刚才楼下有人在弹吉他,弹得很慢。'));
await read();
const during = await said();
check('while she is answering, the new reach-out does not cut in', !during.includes('弹吉他'),`${during} | ${await status()}`);
await shot('04-moon-desktop-during-reply');
// Wait for the stream to end and her last line to have its time; then it comes in on its own.
// Frames are kept around the moment it enters: the last ones before and about 1.2 s after.
const film = []; let arrived = false;
for (let i = 0; i < 160 && !arrived; i++) { film.push((await cdp('Page.captureScreenshot', { format: 'jpeg', quality: 70 })).data); arrived = (await said()).includes('弹吉他'); }
for (const end = Date.now() + 1200; Date.now() < end;) film.push((await cdp('Page.captureScreenshot', { format: 'jpeg', quality: 70 })).data);
film.slice(-16).forEach((d, i) => writeFileSync(join(out, `m2-admit-${String(i).padStart(2, '0')}.jpg`), Buffer.from(d, 'base64')));
check('after her answer has had its time, the reach-out comes in as a new turn', arrived);
check('draft untouched', await js(`document.querySelector('textarea').value`) === '还没写完的草稿');
await shot('05-moon-desktop-admitted');
// ── 5. Paused reading holds it, with a quiet reason; resuming lets it in. ──
await click('.reader-bar .flow'); await sleep(400);
await ctl('/__reach?text=' + encodeURIComponent('今天的晚霞是粉色的。')); await read(); await sleep(1500);
check('paused: stays on your line and says why', !(await said()).includes('晚霞') && (await status()).includes('继续后呈现'), await status());
await shot('06-moon-desktop-paused-held');
await click('.reader-bar .flow'); arrived = false; for (let i = 0; i < 30 && !arrived; i++) { await sleep(500); arrived = (await said()).includes('晚霞'); }
check('resume lets it in', arrived);
// ── 6. Leaving the conversation with one held: it joins the record as unread. ──
await click('.reader-bar .flow'); await sleep(300);
await ctl('/__reach?text=' + encodeURIComponent('我把书签夹在第三十页了。')); await read(); await sleep(600);
await click('.nav-item', '此刻'); await sleep(1200);
check('held one becomes unread on leaving', await exists('.nav-item.unread') && (await text('.home .letter')).includes('书签'));
await shot('07-moon-desktop-home-unread');
// ── 7. Reopen: same record, no duplicates, unread still unread. ──
const before = await ctl('/__rows');
await cdp('Page.reload'); await sleep(2000);
const ids = await js(`(async () => (await (await fetch('/api/messages?limit=200')).json()).messages.map(m => m.id))()`);
check('reopen: full record, unique ids', ids.length === before.length && new Set(ids).size === ids.length, `${ids.length} rows`);
check('reopen: unread survives a reload', await exists('.nav-item.unread') && (await text('.home .letter')).includes('书签'));
// ── 8. Two unread: 回她/letter opens the record at the first one. ──
await ctl('/__reach?text=' + encodeURIComponent('还有,明天可能降温。')); await read();
check('two unread counted on the letter', (await text('.home .letter')).includes('2 句还没看'));
await click('.home .letter'); await sleep(1300);
check('several unread open the record at the first', await js(`!!document.querySelector('.log-panel:not([hidden]) .message.hl')`) && (await text('.log-panel .message.hl')).includes('书签'));
await click('.log-panel .btn-round'); await sleep(500); await click('.nav-item', '此刻'); await sleep(900);
check('all seen after opening the record', !(await exists('.nav-item.unread')));
// ── 8b. HEL-880: back after a long absence — more rows than one bounded read (5 × 50). The older reach-out is not
// skipped; both arrive once, in order, after the follow-up reads. ──
await ctl('/__reach?text=' + encodeURIComponent('你走之后我把灯调暗了一点。')); await ctl('/__bulk/320');
await ctl('/__reach?text=' + encodeURIComponent('回来了就好。')); await ctl('/__log');
await read(); await sleep(2500);
const caught = await text('.home .letter'), reads = (await ctl('/__log')).filter(l => l.includes('/api/messages')).length;
check('long absence: the older reach-out is not skipped; both counted once', caught.includes('2 句还没看') && caught.includes('回来了就好'), `${caught.replace(/\n/g, ' ')} | ${reads} reads`);
await click('.home .letter'); await sleep(1300);
const absent = await text('.log-panel .scroll');
check('long absence: record holds each once, older one first and opened at', absent.split('灯调暗').length === 2 && absent.split('回来了就好').length === 2 && absent.indexOf('灯调暗') < absent.indexOf('回来了就好') && (await text('.log-panel .message.hl')).includes('灯调暗'));
await shot('08b-moon-desktop-long-absence');
await click('.log-panel .btn-round'); await sleep(500); await click('.nav-item', '此刻'); await sleep(900);
check('no microphone, camera or notification request', await js('window.__asked') === 0);
// ── 9. Evidence: both themes, desktop and phone, with a fresh reach-out on home and in the days pane. ──
for (const theme of ['moon', 'fog']) for (const v of ['desktop', 'phone']) {
await view(v); await boot(theme);
await click('.nav-item', '日子'); await sleep(1300);
await ctl('/__reach?text=' + encodeURIComponent('雨停了,窗台上还有一小洼水。')); await read(); await sleep(500);
await shot(`10-${theme}-${v}-days-reach`);
await click('.reach button', '稍后再看'); await sleep(700);
check(`${theme}/${v}: 稍后再看 hides the card, the mark stays`, !(await exists('.reach.show')) && await exists('.nav-item.unread'));
await click('.nav-item', '此刻'); await sleep(1200);
await shot(`11-${theme}-${v}-home-unread`);
await click('.nav-item', '交谈'); await sleep(1600);
await shot(`12-${theme}-${v}-talk`);
await click('.nav-item', '此刻'); await sleep(800);
}
await view('phone'); await boot('fog');
await click('.nav-item', '日子'); await sleep(1200);
await ctl('/__reach?text=' + encodeURIComponent('我在窗边等你。')); await read(); await sleep(400);
await frames('m3-reach-paned-phone', 900);
await shot('13-fog-phone-days-reach');
// ── 10. The demo entry stays separate: no real message reads. ──
await ctl('/__log');
await cdp('Page.navigate', { url: `${base}/?demo=1` }); await sleep(2500);
check('demo entry makes no real message requests', !(await ctl('/__log')).some(l => l.includes('/api/messages')));
ws.close(); browser.kill();
try { rmSync(profile, { recursive: true, force: true }); } catch { /* Edge may still hold the profile. */ }
const failed = results.filter(r => !r).length;
console.log(`${results.length - failed}/${results.length} passed`);
process.exit(failed ? 1 : 0);