// HEL-834 browser check: drives headless Edge over CDP against tests/hel834_mock.mjs. // Usage: node tests/hel834_shots.mjs [port]. Prints one PASS/FAIL line per check, exits 1 on any FAIL. 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 || 8834), base = `http://127.0.0.1:${port}`, cdpPort = 9434; mkdirSync(out, { recursive: true }); const profile = join(tmpdir(), `hel834-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(), requests = []; 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); } else if (m.method === 'Network.requestWillBeSent') requests.push(m.params.request.url); }); 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 mode = m => fetch(`${base}/__mode/${m}`); const serverLog = async () => (await fetch(`${base}/__log`)).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)})].filter(e => e.offsetParent !== null).map(e => e.innerText).join('\\n')`); const count = sel => js(`[...document.querySelectorAll(${JSON.stringify(sel)})].filter(e => e.offsetParent !== null).length`); 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, path = '/') { await cdp('Page.navigate', { url: `${base}/` }); await sleep(600); await js(`localStorage.setItem('cg.theme', ${JSON.stringify(theme)}); sessionStorage.clear(); true`); await cdp('Page.navigate', { url: `${base}${path}` }); await sleep(1800); } const openMemories = async () => { await click('.nav-item', '日子'); await sleep(1300); await click('[role=tab]', '我们的回忆'); await sleep(900); }; await cdp('Page.enable'); await cdp('Runtime.enable'); await cdp('Network.enable'); // 1. Two themes × desktop/phone: list and detail. for (const theme of ['moon', 'fog']) for (const v of ['desktop', 'phone']) { await mode('full'); await view(v); await boot(theme); await openMemories(); await shot(`${theme}-${v}-memories`); await click('button.mem', '旋律'); await sleep(1000); await shot(`${theme}-${v}-detail`); } // 2. Behaviour (desktop, moon). await view('desktop'); await mode('full'); await boot('moon'); await serverLog(); await openMemories(); let list = await text('.list'); check('first page renders 30 valid memories, malformed rows dropped', await count('button.mem') === 30 && !list.includes('坏行'), `${await count('button.mem')} items`); check('unbuilt groups not drawn; 她的成长 points to settings', !list.includes('你们的小习惯') && !list.includes('她知道的你') && list.includes('她的成长') && list.includes('在设置里看底色与成长')); await click('.more button', '看更早的回忆'); await sleep(900); list = await text('.list'); check('cursor paging appends the older page', await count('button.mem') === 32 && list.includes('再往前的聊天'), `${await count('button.mem')} items`); check('paging used next_before=12', (await serverLog()).includes('GET /api/memories?limit=30&before=12')); await click('button.mem', '旋律'); await sleep(900); let detail = await text('.detail'); check('detail shows server fields and source', /我们一起的 · 来自 \d+月\d+日 \d\d:\d\d 的聊天/u.test(detail) && detail.includes('她是这样记得的')); check('那时候的聊天 is exactly messageIds under the real speaker', await count('.said-then p') === 1 && detail.includes('换了一个结尾')); check('linked days: loaded one by title, older one by id placeholder', detail.includes('一个念头') && detail.includes('她讲给你听过的一件事')); await click('.link-card', '她讲给你听过的一件事'); await sleep(1200); detail = await text('.detail'); check('older day opens by id through /api/life/90', detail.includes('修钟表')); await click('[role=tab]', '我们的回忆'); await sleep(600); await click('button.mem', '加班'); await sleep(900); detail = await text('.detail'); check('a memory from your words shows them as yours', /你\s*今天加班到九点/u.test(detail) && await count('.said-then p[data-role=user]') === 1 && await count('.said-then p[data-role=companion]') === 0); await click('.detail button', '在交谈里看这段'); await sleep(1500); check('在交谈里看这段 opens the record at that message', await js(`!!document.querySelector('article.message.hl[data-mid="3"]')`) && await count('article.message.hl') === 1); await click('.nav-item', '日子'); await sleep(1000); await click('[role=tab]', '她的日子'); await sleep(500); await click('button.ev', '旋律'); await sleep(900); detail = await text('.detail'); check('life detail lists the memory linked by server lifeIds', detail.includes('和这件事有关的回忆') && detail.includes('她把那段旋律换了个结尾')); // Reopen re-reads. await click('.nav-item', '此刻'); await sleep(800); await mode('full-new'); await serverLog(); await click('.nav-item', '日子'); await sleep(1200); await click('[role=tab]', '我们的回忆'); await sleep(800); check('reopening re-reads /api/memories and shows the new memory first', (await serverLog()).some(l => l.startsWith('GET /api/memories?limit=30')) && (await text('button.mem')).split('\n').some(l => l.includes('开一条窗缝'))); // Old link to a memory the server will not show. await mode('full'); await boot('moon', '/#memory=77'); await click('.nav-item', '日子'); await sleep(1600); detail = await text('.detail'); check('old/hidden memory link is one neutral can\'t-open', detail.includes('这一条现在打不开') && !detail.includes('77')); await shot('moon-desktop-hidden-link'); await boot('moon', '/#memory=47'); await click('.nav-item', '日子'); await sleep(1600); check('deep link to a visible memory opens it', (await text('.detail')).includes('加班到九点')); // 3. States. for (const [m, expect] of [['empty', '还没有可以展示的回忆'], ['fail', '回忆一时没翻出来'], ['unwired', '长期记忆尚未接通']]) { for (const v of ['desktop', 'phone']) { await mode(m); await view(v); await boot('moon'); await openMemories(); const t = await text('.list'); if (v === 'desktop') check(`${m} state is its own honest state`, t.includes(expect) && !(m !== 'empty' && t.includes('还没有可以展示的回忆')) && !(m !== 'fail' && t.includes('一时没翻出来'))); await shot(`moon-${v}-${m}`); } } await view('desktop'); await mode('fail'); await boot('fog'); await openMemories(); await shot('fog-desktop-fail'); await mode('full'); await click('.list button', '再试一次'); await sleep(900); check('retry after failure loads the list', await count('button.mem') === 30); await mode('empty'); await boot('fog'); await openMemories(); await shot('fog-desktop-empty'); await mode('unwired'); await boot('fog'); await openMemories(); await shot('fog-desktop-unwired'); const home = async () => { await click('.nav-item', '此刻'); await sleep(700); return js(`document.querySelector('.first-note')?.textContent || ''`); }; check('home note stays conservative when memory is not on', (await home()).includes('长期记忆与语音尚未接通')); await mode('full'); await boot('moon'); check('home note says memory is saved only when the server reports it', (await js(`document.querySelector('.first-note')?.textContent || ''`)).includes('资料、聊天与回忆保存在服务器')); // 4. Real text chat still works. await click('.nav-item', '交谈'); await sleep(1200); await js(`document.querySelector('textarea').focus(); true`); await cdp('Input.insertText', { text: '雨停了吗' }); await cdp('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, text: '\r' }); await cdp('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 }); await sleep(6000); check('real text chat sends and receives', (await serverLog()).includes('POST /api/chat') && (await js('document.body.innerText')).includes('今天的雨停了没有')); // 5. Demo path: separate, zero API and zero off-host requests. requests.length = 0; await serverLog(); await view('desktop'); await cdp('Page.navigate', { url: `${base}/?demo=1` }); await sleep(2000); await shot('moon-desktop-demo-entry'); const offHost = requests.filter(u => !u.startsWith(base) && !u.startsWith('data:') && !u.startsWith('blob:')); const api = (await serverLog()).filter(l => l.includes('/api/')); check('demo path makes zero /api and zero off-host requests', offHost.length === 0 && api.length === 0, `${requests.length} requests, off-host ${offHost.length}, api ${api.length}`); check('demo stays its own local path (wizard, no real profile)', (await js('document.body.innerText')).includes('这是本机演示') && !(await js('document.body.innerText')).includes('栖')); ws.close(); browser.kill(); await sleep(500); 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} checks passed`); process.exit(failed ? 1 : 0);