Files
CyberGril/docs/rework/hel910/tools/hel910_call1.mjs
T

275 lines
18 KiB
JavaScript

// HEL-910 call1: REAL web page drives the whole scenario (workstation-local Chromium, real HTTPS entry).
// - cert interstitials accepted exactly like a user (高级→继续) on 8361 AND 8363 (WSS bridge)
// - voice call started from the real UI (voice-button → 开始语音)
// - user voice = Chromium fake mic fed with the scheduled WAV (U1 haimianbaobao @0s,
// U2 bajie @60s, U3 haimianbaobao @120s; built offline from existing engineering samples)
// - TEXT interrupts are typed into the real composer textarea and sent with a REAL Enter key:
// T1 while her R1 answer is AUDIBLY playing (timing B, hush→cg.interrupt path)
// T2 while her R2 answer is STILL GENERATING (timing A, server turn-gate path)
// - in-page probes (single page clock): stream energy 50ms, el.muted transitions, voice phase,
// heard-final text, chat DOM rows, fetch network marks, MediaRecorder of the received stream
// Usage: node hel910_call1.mjs <chrome> <fakeWav> <outDir> <baseURL>
import { spawn } from 'node:child_process';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
const [chrome, fakeWav, out, baseArg] = process.argv.slice(2);
const base = baseArg || 'https://192.168.200.12:8361';
const wssOrigin = 'https://192.168.200.12:8363';
mkdirSync(out, { recursive: true });
const cdpPort = 9713;
const T1_TEXT = '先停下,我用打字跟你说:把你刚才那句还没说完的话作废,改用文字告诉我,你今天想拉我一起做的第一件事是什么?';
const T2_TEXT = '等一下,先别把刚才那段长回答说完,我打字补充:只用一句话告诉我你现在的心情,然后安静等我。';
const INIT = `(() => {
if (window.__cg) return;
const cg = window.__cg = { anchor: [Date.now(), performance.now()], energy: [], muted: [], phase: [], heard: [], chat: [], net: [], marks: {}, rec: { started: 0, bytes: 0 }, errs: [] };
const pnow = () => Math.round(performance.now());
// 1) fetch wrapper — exact page-clock network marks
const of = window.fetch.bind(window);
window.fetch = async (...a) => {
const url = typeof a[0] === 'string' ? a[0] : a[0]?.url || '';
const t0 = pnow();
try {
const r = await of(...a);
if (url.includes('/api/')) cg.net.push({ t: t0, url: url.slice(0, 80), method: (a[1] && a[1].method) || 'GET', status: r.status, tHeaders: pnow() });
return r;
} catch (e) { if (url.includes('/api/')) cg.net.push({ t: t0, url: url.slice(0, 80), method: (a[1] && a[1].method) || 'GET', status: 'err:' + String(e).slice(0, 40) }); throw e; }
};
// 2) energy + muted probe on her audio holder (50ms), starts whenever elements appear
let ctx = null, analysers = new Map(), lastMuted = null;
const ensureCtx = () => { if (!ctx) { try { ctx = new AudioContext(); } catch (e) { cg.errs.push('ctx:' + e); } } if (ctx && ctx.state === 'suspended') ctx.resume().catch(() => {}); return ctx; };
const hook = el => {
if (!el || !el.srcObject || analysers.has(el)) return;
const c = ensureCtx(); if (!c) return;
try {
const an = c.createAnalyser(); an.fftSize = 512;
c.createMediaStreamSource(el.srcObject).connect(an);
analysers.set(el, an);
if (!cg.rec.started) {
try {
const mr = new MediaRecorder(el.srcObject, { mimeType: 'audio/webm;codecs=opus' });
const chunks = []; mr.ondataavailable = ev => { chunks.push(ev.data); cg.rec.bytes += ev.data.size; };
mr.onstop = () => { cg.rec.chunks = chunks; };
mr.start(1000); cg.rec.started = pnow(); cg.rec.mr = mr;
} catch (e) { cg.errs.push('rec:' + e); }
}
} catch (e) { cg.errs.push('hook:' + e); }
};
setInterval(() => {
ensureCtx();
document.querySelectorAll("div[data-voice='her'] audio, div[data-voice='her'] video").forEach(hook);
let rms = 0;
const buf = new Uint8Array(512);
for (const an of analysers.values()) {
an.getByteTimeDomainData(buf);
let acc = 0; for (const v of buf) { const d = (v - 128) / 128; acc += d * d; }
rms = Math.max(rms, Math.sqrt(acc / buf.length));
}
const els = [...document.querySelectorAll("div[data-voice='her'] audio, div[data-voice='her'] video")];
const muted = els.length ? els.every(el => el.muted) : null;
if (muted !== lastMuted) { cg.muted.push([pnow(), muted]); lastMuted = muted; }
cg.energy.push([pnow(), Math.round(rms * 100000) / 100000, els.length]);
}, 50);
// 3) voice phase + heard text (100ms poll, log changes)
let lastPhase = null, lastHeard = null, lastSaid = null;
setInterval(() => {
const row = document.querySelector('.voice-row.real');
const phase = row ? row.dataset.phase : null;
const heard = document.querySelector('.voice-heard:not(.said)')?.textContent || '';
const said = document.querySelector('.voice-heard.said')?.textContent || '';
if (phase !== lastPhase) { cg.phase.push([pnow(), phase]); lastPhase = phase; }
if (heard !== lastHeard) { cg.heard.push([pnow(), 'draft', heard.slice(0, 60)]); lastHeard = heard; }
if (said !== lastSaid) { cg.heard.push([pnow(), 'final', said.slice(0, 60)]); lastSaid = said; }
}, 100);
// 4) chat DOM rows (conversation + record views)
const seen = new Set();
const scan = () => {
document.querySelectorAll('.message').forEach(m => {
const key = m.dataset.mid || (m.dataset.role + ':' + m.textContent.slice(0, 40));
if (seen.has(key)) return; seen.add(key);
cg.chat.push({ t: pnow(), role: m.dataset.role, mid: m.dataset.mid, text: (m.textContent || '').slice(0, 90), incomplete: !!m.querySelector('.incomplete') });
});
};
setInterval(scan, 120);
// 5) marks helper
window.__mark = (k) => { cg.marks[k] = pnow(); };
cg.mark = window.__mark;
})()`;
const sleep = ms => new Promise(r => setTimeout(r, ms));
const browser = spawn(chrome, [
'--headless=new', `--remote-debugging-port=${cdpPort}`, `--user-data-dir=${join(tmpdir(), `hel910-call1-${Date.now()}`)}`,
'--no-first-run', '--hide-scrollbars', '--force-color-profile=srgb',
'--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream',
`--use-file-for-fake-audio-capture=${fakeWav}`,
'--autoplay-policy=no-user-gesture-required', 'about:blank',
], { stdio: 'ignore', env: { ...process.env, LD_LIBRARY_PATH: `${process.env.HOME}/chromium-libs/root/usr/lib/x86_64-linux-gnu:${process.env.HOME}/chromium-libs/root/usr/lib` } });
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); } }
if (!targets) { console.error('chromium did not start'); process.exit(1); }
const ws = new WebSocket(targets.find(t => t.type === 'page').webSocketDebuggerUrl);
await new Promise(r => ws.addEventListener('open', r, { once: true }));
let id = 0; const waiting = new Map(); const events = [];
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) events.push(m);
});
const cdp = (method, params = {}) => new Promise((ok, ko) => { const n = ++id; waiting.set(n, { ok, ko }); ws.send(JSON.stringify({ id: n, 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?.slice(0, 400) || 'js error'); return r.result.value; };
const shot = async name => { const { data } = await cdp('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }); writeFileSync(join(out, `${name}.png`), Buffer.from(data, 'base64')); };
async function typeThisIsUnsafe() {
for (const ch of 'thisisunsafe') {
await cdp('Input.dispatchKeyEvent', { type: 'keyDown', key: ch, text: ch, windowsVirtualKeyCode: ch.charCodeAt(0), unmodifiedText: ch });
await cdp('Input.dispatchKeyEvent', { type: 'keyUp', key: ch, windowsVirtualKeyCode: ch.charCodeAt(0) });
await sleep(30);
}
}
async function goto(url) {
await cdp('Page.navigate', { url });
let privacySeen = 0;
for (let i = 0; i < 150; i++) {
await sleep(200);
const st = await js('document.readyState + "|" + (document.title || "") + "|" + (document.body ? document.body.textContent.slice(0, 40) : "")').catch(() => '');
if (!st.includes('Privacy') && !st.includes('not private') && st.startsWith('complete|')) return st;
// certificate interstitial: proceed through it exactly the way the interstitial itself accepts (its own key sequence)
if (st.includes('Privacy') || st.includes('not private')) {
privacySeen++;
await typeThisIsUnsafe();
}
}
return js('document.readyState + "|" + (document.title || "")').catch(() => 'unknown');
}
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.scrollIntoView({ block: 'center' }); el.click(); return true; })()`);
const until = async (fn, ms, every = 200) => { const end = Date.now() + ms; while (Date.now() < end) { const v = await fn(); if (v) return v; await sleep(every); } return null; };
const snap = () => js('JSON.stringify({e: window.__cg.energy.length ? window.__cg.energy.slice(-40) : [], ph: window.__cg.phase.slice(-6), hd: window.__cg.heard.slice(-6), mu: window.__cg.muted.slice(-6), ch: window.__cg.chat.slice(-8), mk: window.__cg.marks, rec: window.__cg.rec, err: window.__cg.errs, anchor: window.__cg.anchor})').then(JSON.parse);
const phaseNow = () => js(`document.querySelector('.voice-row.real')?.dataset.phase || null`);
const energyRecent = (n = 8) => js(`window.__cg.energy.slice(-${n})`).then(a => a || []);
async function sendText(label, text) {
await js(`(() => { window.__mark(${JSON.stringify(label + '_pre')}); const el = document.querySelector('.composer textarea'); if (!el) return false; el.focus(); const proto = HTMLTextAreaElement.prototype; Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, ${JSON.stringify(text)}); el.dispatchEvent(new Event('input', { bubbles: true })); return true; })()`);
await sleep(120);
await cdp('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13 });
await cdp('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13 });
await sleep(80);
await js(`window.__mark(${JSON.stringify(label + '_sent')})`);
}
const started = Date.now();
const R = { log: [], notes: [] };
const note = s => { R.log.push([Date.now() - started, s]); console.log(`[${((Date.now() - started) / 1000).toFixed(1)}] ${s}`); };
await cdp('Page.addScriptToEvaluateOnNewDocument', { source: INIT });
await cdp('Page.enable'); await cdp('Network.enable');
// 0) user-posture cert acceptance on both origins
note('accept cert 8361: ' + (await goto(base)).slice(0, 40));
note('accept cert 8363: ' + (await goto(wssOrigin)).slice(0, 40));
await goto(base);
await sleep(2500);
await shot('01-page-loaded');
note('page ready; companion=' + String(await js(`fetch('/api/companion').then(r => r.ok).catch(() => false)`)));
// enter the conversation view from the home window
const entered = await click('button', '和她说话');
note('clicked talk entry: ' + !!entered);
const composer = await until(async () => js(`!!document.querySelector('.composer textarea')`), 10000, 300);
if (!composer) {
note('FAIL: composer textarea not found — page state: ' + String(await js(`document.body.textContent.slice(0, 200)`)));
await finish('fail-nocomposer');
}
if (!(await js(`!!document.querySelector('.voice-button')`))) {
note('FAIL: voice button not found — page state: ' + String(await js(`document.body.textContent.slice(0, 200)`)));
await finish('fail-novoicebtn');
}
// 1) start the voice call from the real UI
if (!(await click('.voice-button'))) { note('FAIL: voice button not found'); await finish('fail-novoicebtn'); }
await sleep(600);
if (!(await click('.modal button', '开始语音'))) { note('FAIL: voice modal confirm not found'); await finish('fail-nomodal'); }
await js(`window.__mark('voice_start_click')`);
note('voice start clicked');
await until(async () => (await phaseNow()) !== null, 20000);
await until(async () => ['listening', 'thinking'].includes(await phaseNow()), 25000);
await shot('02-voice-listening');
note('voice row phase=' + (await phaseNow()));
// U1 @0-7.1s: she hears haimianbaobao → thinking → speaking (audible R1)
await until(async () => (await js(`window.__cg.heard.some(h => h[1] === 'final')`)), 30000);
note('U1 heard final');
const th1 = await until(async () => (await phaseNow()) === 'thinking', 40000);
note('phase thinking (R1 generating)');
// timing A rehearsal happens on U2; on U1 we wait for audible playback (timing B target)
const spk1 = await until(async () => {
const ph = await phaseNow(); if (ph !== 'speaking') return false;
const e = await energyRecent(12); return e.filter(x => x[1] > 0.02).length >= 8;
}, 60000);
note('R1 audible speaking: ' + !!spk1);
await sleep(1600); // let plenty of old audio remain
await shot('03-r1-speaking');
// T1 — timing B: text while old answer audibly playing (real composer + real Enter)
await sendText('T1', T1_TEXT);
note('T1 sent during playback');
await sleep(1200);
await shot('04-after-T1');
// watch old-voice stop + T1 text reply
await until(async () => { const e = await energyRecent(16); return e.length && e.filter(x => x[1] > 0.015).length === 0; }, 15000).then(v => note('stream quiet after T1: ' + !!v));
await until(async () => (await js(`window.__cg.chat.some(c => c.role === 'companion' && c.t > (window.__cg.marks.T1_sent || 0))`)), 90000, 300).then(v => note('T1 companion reply visible: ' + !!v));
await shot('05-T1-reply');
// U2 @60-73.3s: prefill T2, fire Enter the moment thinking starts for the bajie answer
await until(async () => (await js(`window.__cg.heard.some(h => h[1] === 'final' && h[2].includes('取经'))`)), 90000).then(v => note('U2 heard final (bajie): ' + !!v));
await js(`(() => { const el = document.querySelector('.composer textarea'); if (el) { el.focus(); const proto = HTMLTextAreaElement.prototype; Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, ${JSON.stringify(T2_TEXT)}); el.dispatchEvent(new Event('input', { bubbles: true })); } })()`);
const t2fired = await until(async () => (await phaseNow()) === 'thinking', 30000, 80);
if (t2fired) {
await js(`window.__mark('T2_thinking_seen')`);
await cdp('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13 });
await cdp('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13 });
await js(`window.__mark('T2_sent')`);
note('T2 sent during thinking (generation in flight)');
} else {
note('T2 NOT fired: thinking phase not observed in time');
}
await sleep(1500);
await shot('06-after-T2');
// R2 must never become audible: no energy while T2 reply streams as text
const quiet = await until(async () => { const e = await energyRecent(10); return e.length && e.every(x => x[1] <= 0.015); }, 20000);
note('no R2 audio after T2: ' + !!quiet);
await until(async () => (await js(`window.__cg.chat.filter(c => c.role === 'companion' && c.t > (window.__cg.marks.T2_sent || 0)).length >= 1`)), 90000, 300).then(v => note('T2 companion reply visible: ' + !!v));
await shot('07-T2-reply');
// U3 @120-127.1s: voice recovery — she must speak normally again
await until(async () => (await js(`window.__cg.heard.filter(h => h[1] === 'final').length >= 3`)), 90000).then(v => note('U3 heard final: ' + !!v));
const spk3 = await until(async () => {
const ph = await phaseNow(); if (ph !== 'speaking') return false;
const e = await energyRecent(12); return e.filter(x => x[1] > 0.02).length >= 8;
}, 90000);
note('R3 voice recovery audible: ' + !!spk3);
await shot('08-R3-speaking');
await until(async () => ['listening', 'thinking'].includes(await phaseNow()), 120000, 300).then(async v => note('R3 finished, back to ' + (await phaseNow())));
await shot('09-R3-done');
// end the call from the real UI
if (await click('.voice-end')) { await js(`window.__mark('voice_end_click')`); note('voice ended via UI'); }
await sleep(3000);
await finish('done');
async function finish(status) {
R.status = status;
try {
await js(`(() => { try { window.__cg.rec.mr && window.__cg.rec.mr.state !== 'inactive' && window.__cg.rec.mr.stop(); } catch (e) {} })()`);
await sleep(800);
const full = await js(`(async () => { const cg = window.__cg; let rec = null; try { if (cg.rec.chunks && cg.rec.chunks.length) { const blob = new Blob(cg.rec.chunks, { type: 'audio/webm' }); const buf = await blob.arrayBuffer(); const bytes = new Uint8Array(buf); let bin = ''; for (let i = 0; i < bytes.length; i += 32768) bin += String.fromCharCode(...bytes.subarray(i, i + 32768)); rec = { bytes: blob.size, b64: bin }; } } catch (e) {} return { anchor: cg.anchor, energy: cg.energy, muted: cg.muted, phase: cg.phase, heard: cg.heard, chat: cg.chat, net: cg.net, marks: cg.marks, recMeta: { started: cg.rec.started, bytes: cg.rec.bytes }, errs: cg.errs, recB64: rec && rec.b64 }; })()`);
writeFileSync(join(out, 'call1-probe.json'), JSON.stringify({ ...R, probe: { ...full, recB64: undefined } }));
if (full.recB64) writeFileSync(join(out, 'call1-received.webm'), Buffer.from(full.recB64, 'base64'));
note('probe saved: energy=' + full.energy.length + ' chat=' + full.chat.length + ' recBytes=' + (full.recMeta.bytes || 0));
} catch (e) { note('probe save FAILED: ' + e); }
browser.kill();
process.exit(0);
}