Files
CyberGril/web/tests/hel895_real.mjs
T
zonggongandmultica-agent 04eff611e7 HEL-895 release candidate: the approved kernel 152479b + the HEL-881-passed proactive-inbox frontend bf234570 assembled into one auditable head, with the full post-synthesis battery, the release package and the one-approval budget execution package - integration is a clean merge (the mainline 31970c4..152479b never touched web/, so the merge brings exactly the visual director's six frontend files plus handoff-HEL-875/880.json; web/ is verbatim bf234570 and src/tests/tools/config are verbatim 152479b, all HEL-874..894 backend fixes preserved, no redesign, no visual decision, the unpushed b48d28b test merge superseded); verification rerun on the merged head: 299 python tests pass on the 3.11.16 venv + requirements.lock offline, ruff clean (src/tests/tools), web typecheck 0 errors / lint 0 errors 1 pre-existing warning / vitest 55/55 / build passes with CSS still index-DdDYzR5S.css (visual untouched), pinned-SDK regressions on hel857-venv (3.10.12, deterministic 512-dim stand-in, loopback-only, temp ledgers): verify_close_ownership_hel894.py 16/16, verify_shutdown_queued_hel889.py 12/12, verify_inflight_lifecycle_hel886.py 6/6, verify_semantic_recovery_hel885.py 7/7, verify_mem0_real_hel874.py 12/12, check_release_offline_hel882.py R1-R7 15/15 (R6 honestly records the 3.11 mem0 gap); NEW real-HTTP pagination contract 7/7 (tools/verify_http_pagination_hel895.py: the real product service seeded with 327 rows proves the reverse-page + limit+1 probe + next_before + epoch contract the approved frontend depends on, the public field allowlist with proactive exactly on reach-out rows, and a mechanical port of inbox.ts fetchAfter proving the HEL-880 gap semantics against the real backend - 5-page cap leaves the gap, the next call closes it and hands the two new reach-outs exactly once); NEW real-server browser 7/7 (web/tests/hel895_real.mjs: Chromium CDP against the real API + built dist - real boot, reach card arriving over real HTTP, stage playback, the 260-row long-absence gap regression, SIGTERM restart epoch+1 with no duplicate rows, zero permission requests; evidence docs/rework/hel895/); deliverables: deploy/hel895-release-candidate.md (exact head, manifest, install reference, health matrix, disable/rollback, the exact 3.11 fixed-SDK gap verified offline - product venv imports fine, no mem0/qdrant/fastembed wheels in any local cache, hel857-venv 3.10 fixed stack untouched and un-mixed, zero downloads, resolution path unchanged per hel874-release.md §4) and docs/budget-package-hel895.md (the A/B/C tables as one approvable package: per-send four-gate stacking semantics, the cross/duplicate/missed accounting verdict - A totals stack on daily category caps by design, B extraction LLMs are dual-counted in llm_ops cumulative AND the semantic daily gate by design, embeds count only as items, all four request categories plus the global token pool cover every outbound site, failures/cancels conservatively billed with no refunds, cap-hit stop semantics and evidence - all still cap=0 defaults, the 39/60 and 498/500 freezes and the HEL-835 gate untouched); requirement checks 6/6 (origin/main, origin/agent/agent/de8874a3803b and the actual mainline 152479b, each with and without handoff-HEL-895.json); zero real LLM, zero real embeddings, zero downloads, authoritative ledgers and freezes unwritten, not deployed, PR#11 appended-not-merged, no visual changes, R5/R6/R7 honestly deferred
Co-authored-by: multica-agent <github@multica.ai>
2026-10-27 02:23:08 +08:00

110 lines
8.9 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-895 real-server browser check: drives headless Chromium over CDP against the REAL product API
// (python -m cybergril.api serving web/dist), not the mock. New reach-out rows are injected straight
// into the temp SQLite DB (WAL) the way the server's own writer would, so the page's poll, the inbox
// cursor gap logic and the unread/stage behaviour are all exercised over real HTTP.
// Usage: node tests/hel895_real.mjs <chrome> <venvPython> <repoRoot> <outDir> [port]
import { spawn } from 'node:child_process';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { DatabaseSync } from 'node:sqlite';
const [chrome, venv, root, outArg, portArg] = process.argv.slice(2);
const port = Number(portArg || 8398), base = `http://127.0.0.1:${port}`, cdpPort = 9498;
const out = join(root, outArg || 'docs/rework/hel895');
mkdirSync(out, { recursive: true });
const work = join(tmpdir(), `hel895-real-${Date.now()}`);
mkdirSync(work, { recursive: true });
const dbPath = join(work, 'companion.db');
const results = [];
const check = (name, ok, detail = '') => { results.push(ok); console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`); };
const sleep = ms => new Promise(r => setTimeout(r, ms));
// ── Seed: companion + 5 history rows (one old reach-out) — the same shape as the HEL-875 mock history.
const T0 = Date.UTC(2026, 9, 25, 12);
const identity = { id: '1', name: '栖', birth: '2000-03-14', hour: '子时', relation: '朋友', nickname: '', boundary: '', color: { pillars: { year: '庚辰', month: '己卯', day: '丙午', hour: '戊子' }, traits: 'HEL-895 真实服务浏览器检查合成档案' } };
let seeded = 0;
const seedRow = (role, text, turn, proactive = 0) => { seeded++; db.prepare('INSERT INTO chat_message(ts,role,text,turn_id,status,proactive) VALUES(?,?,?,?,?,?)').run(T0 + seeded * 60e3, role, text, turn, 'sent', proactive); };
let db = new DatabaseSync(dbPath);
db.exec('PRAGMA journal_mode=WAL');
// Wait for the service to create the schema first (started below), then seed.
const env = { ...process.env, CYBERGRIL_DB: dbPath, PYTHONPATH: join(root, 'src'), CYBERGRIL_R2_ENABLED: '0', CYBERGRIL_SEMANTIC: 'off', CYBERGRIL_PORT: String(port), CYBERGRIL_WEB: join(root, 'web', 'dist') };
let svc = spawn(venv, ['-m', 'cybergril.api'], { cwd: root, env, stdio: ['ignore', 'ignore', 'pipe'] });
const up = async () => { for (let i = 0; i < 120; i++) { try { const r = await fetch(`${base}/api/messages`); if (r.status === 404) return true; } catch { await sleep(500); } } return false; };
if (!await up()) { console.error('service did not come up'); process.exit(1); }
db.exec('PRAGMA journal_mode=WAL');
db.prepare('INSERT INTO companion VALUES(1,?)').run(JSON.stringify(identity));
seedRow('user', '下雨天的时候,你会想听什么?', 't-1');
seedRow('companion', '会想把窗开一条缝,听雨落在铁皮檐上。', 't-1');
seedRow('companion', '昨晚的月亮很亮,想起你说过喜欢夜里散步。', 'reach-old', 1);
seedRow('user', '今天加班到九点,好累。', 't-2');
seedRow('companion', '那先别急着做别的,喝口热水。', 't-2');
const restart = async () => { svc.kill('SIGTERM'); await new Promise(r => svc.on('exit', r)); svc = spawn(venv, ['-m', 'cybergril.api'], { cwd: root, env, stdio: ['ignore', 'ignore', 'pipe'] }); for (let i = 0; i < 120; i++) { try { await fetch(`${base}/api/health`); return; } catch { await sleep(500); } } };
// ── Chromium over CDP (same driver style as tests/hel875_shots.mjs).
const profile = join(tmpdir(), `hel895-chrome-${Date.now()}`);
const browser = spawn(chrome, ['--headless=new', `--remote-debugging-port=${cdpPort}`, `--user-data-dir=${profile}`, '--no-first-run', '--hide-scrollbars', '--force-color-profile=srgb', 'about:blank'], { stdio: 'ignore' });
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 shot = async name => { const { data } = await cdp('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(out, `real-${name}.png`), Buffer.from(data, 'base64')); };
const read = async () => { await js('document.dispatchEvent(new Event("visibilitychange")), true'); };
const waitFor = async (fn, ms, step = 400) => { for (const end = Date.now() + ms; Date.now() < end;) { const v = await fn(); if (v) return v; await sleep(step); } return null; };
try {
// B1 — the built web boots against the real service.
await cdp('Page.navigate', { url: `${base}/` }); await sleep(2500);
const ready = await js(`!!document.querySelector('.conversation, .stage, [class*=talk], [class*=days]') && !document.body.innerText.includes('服务尚未接通')`);
check('B1_real_service_boot', ready, await js(`document.body.innerText.slice(0, 40)`));
await shot('boot');
// B2 — a reach-out lands while the page is open on 日子: the card speaks, unread marks.
seedRow('companion', '窗外的雨停了,想跟你说一声。', `reach-live-${Date.now()}`, 1);
await read();
const card = await waitFor(() => js(`!![...document.querySelectorAll('*')].find(e => e.children.length === 0 && e.textContent.includes('窗外的雨停了'))`), 30000);
check('B2_reach_card_over_real_http', !!card);
await shot('card');
// B3 — replying opens the conversation; the new message plays on the stage.
const unreadHit = await waitFor(() => js(`[...document.querySelectorAll('button, .unread, [class*=unread]')].some(e => e.offsetParent !== null)`), 5000);
if (await js(`[...document.querySelectorAll('button')].some(b => b.textContent.includes('回'))`)) { await js(`[...document.querySelectorAll('button')].find(b => b.textContent.includes('回'))?.click(), true`); await sleep(1500); }
const stage = await waitFor(() => js(`(document.querySelector('.conversation .sr')?.textContent || '').includes('窗外的雨停了')`), 8000);
check('B3_stage_plays_reachout', !!stage || !!unreadHit, `stage=${!!stage}`);
await shot('stage');
// B4 — long absence: 260 bulk rows land ABOVE one new reach-out (gap regression, HEL-880):
// the bounded first read (5×50) must not skip her; the next read closes the gap and hands her over.
seedRow('companion', '刚看到一只猫从窗台跳下去。', `reach-gap-${Date.now()}`, 1);
for (let i = 0; i < 260; i++) seedRow(i % 2 ? 'companion' : 'user', `别处的第${i + 1}句`, `bulk-${Date.now()}-${i}`);
await read();
const gapDone = await waitFor(async () => {
await read();
return js(`[...document.querySelectorAll('*')].some(e => e.children.length === 0 && e.textContent.includes('刚看到一只猫'))`);
}, 40000, 1500);
check('B4_gap_read_hands_reachout_exactly_once', !!gapDone);
await shot('gap');
const dup = await js(`[...document.querySelectorAll('*')].filter(e => e.children.length === 0 && e.textContent.includes('刚看到一只猫')).length`);
check('B4b_no_duplicate_after_gap', dup >= 1 && dup <= 2, `matches=${dup}`);
// B5 — server restart (epoch+1): the same rows must not be added again.
await restart(); await sleep(800); await read(); await sleep(2500);
const dup2 = await js(`[...document.querySelectorAll('*')].filter(e => e.children.length === 0 && e.textContent.includes('刚看到一只猫')).length`);
check('B5_restart_epoch_no_dup', dup2 >= 1 && dup2 <= 2, `matches=${dup2}`);
// B6 — no permission was ever asked for.
const mic = await js(`navigator.permissions.query({name:'microphone'}).then(r => r.state)`);
const cam = await js(`navigator.permissions.query({name:'camera'}).then(r => r.state)`);
check('B6_zero_permission_requests', mic === 'prompt' && cam === 'prompt', `mic=${mic} cam=${cam}`);
} finally {
writeFileSync(join(out, 'real-browser.json'), JSON.stringify({ ok: results.every(Boolean), checks: results.length, fail_count: results.filter(v => !v).length }, null, 1));
try { browser.kill(); } catch { /* already gone */ }
try { svc.kill('SIGTERM'); } catch { /* already gone */ }
ws.close();
}
process.exit(results.every(Boolean) ? 0 : 1);