Files
CyberGril/web/tests/hel878_mock.mjs
T

108 lines
11 KiB
JavaScript

// HEL-878 isolated contract mock for real voice on the approved conversation. Serves web/dist, the persisted-message
// contract (as tests/hel875_mock.mjs) and the HEL-877 voice router (src/cybergril/voice/router.py): GET
// /api/voice/status, POST /api/voice/session -> 201 grant, DELETE /api/voice/session/{id}. The LiveKit client path is
// answered with tests/fake-livekit.js (a scripted stand-in, no WebRTC); the real vendored build stays reachable at
// /__real-sdk.js for the API-surface check only. Synthetic data only: no model, no LiveKit, no TTS, no network.
// Usage: node tests/hel878_mock.mjs <port>. Control GETs: /__voice?configured=&tts=, /__refuse/<code|0>,
// /__voice-turn?stage=user|reply|cancel&text=, /__proactive?text=, /__cut, /__sessions, /__log, /__rows.
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { extname, join, normalize } from 'node:path';
import { fileURLToPath } from 'node:url';
const dist = fileURLToPath(new URL('../dist/', import.meta.url)), fake = fileURLToPath(new URL('./fake-livekit.js', import.meta.url));
const port = Number(process.argv[2] || 8878);
const T0 = Date.UTC(2026, 9, 26, 12, 0);
const identity = { id: '1', name: '栖', birth: '2000-03-14', hour: '子', relation: '朋友', nickname: '', boundary: '', color: { pillars: { year: '庚辰', month: '己卯', day: '丙午', hour: '戊子' }, traits: '合成测试档案' } };
// /__hold-delete?id=<session> keeps that DELETE unanswered (a slow server); /__hold-delete with no id answers them all.
const epoch = 3, log = [], rows = [], sessions = new Map(), held = new Map();
let voice = { configured: true, tts: true }, refuse = 0, made = 0, voiceTurn = 0, textStream = null;
const add = row => { const id = rows.length + 1; rows.push({ id, ts: T0 + id * 60e3, status: 'sent', lifeIds: [], ...row }); return id; };
const seed = () => {
add({ role: 'user', text: '下雨天的时候,你会想听什么?', turn_id: '00000000-0000-4000-8000-000000000001' });
add({ role: 'companion', text: '会想把窗开一条缝,听雨落在铁皮檐上。你呢,今天累不累?', turn_id: '00000000-0000-4000-8000-000000000001' });
};
seed();
const dto = r => ({ id: r.id, ts: r.ts, role: r.role, text: r.text, turn_id: r.turn_id, status: r.status, lifeIds: r.lifeIds, ...(r.proactive ? { proactive: true } : {}) });
const send = (res, status, body, type = 'application/json; charset=utf-8') => { res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store' }); res.end(typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body)); };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const REFUSALS = { 503: '她的声音服务这会儿不在,稍后再试试。', 409: '还没有创建真实伴侣,语音也不会开始。' };
createServer(async (req, res) => {
const url = new URL(req.url, 'http://x'), p = url.pathname;
if (!p.startsWith('/__') && !p.startsWith('/assets/') && !p.startsWith('/vendor/')) log.push(`${req.method} ${p}${url.search}`);
if (p === '/__log') return send(res, 200, log.splice(0));
// HEL-898 (f92a86f): which process answers (a driver checks it started THIS mock, not someone else's service on
// the port), and a clean record for an isolated scenario (same fixture turn ids replayed per theme).
if (p === '/__pid') return send(res, 200, { pid: process.pid, mock: 'hel878' });
if (p === '/__reset') { rows.splice(0); log.splice(0); sessions.clear(); held.clear(); voiceTurn = 0; textStream = null; seed(); return send(res, 200, { rows: rows.length }); }
if (p === '/__rows') return send(res, 200, rows.map(dto));
if (p === '/__sessions') return send(res, 200, { open: [...sessions.keys()], made });
if (p === '/__voice') { voice = { configured: url.searchParams.get('configured') !== '0', tts: url.searchParams.get('tts') !== '0' }; return send(res, 200, voice); }
if (p.startsWith('/__refuse/')) { refuse = Number(p.slice(10)); return send(res, 200, { refuse }); }
// What the worker's /api/chat call leaves in the record, one stage at a time (the browser never posts it).
// `&turn=` (HEL-879 unified review) lets a recorded worker fixture drive rows under its own
// turn id (the real worker's turn ids are uuids, not voice-N); without it behavior is unchanged.
if (p === '/__voice-turn') {
const stage = url.searchParams.get('stage'), text = url.searchParams.get('text') || '';
if (stage === 'user' && !url.searchParams.has('turn')) voiceTurn++; // default path: same counter semantics as before
const key = url.searchParams.get('turn') || `voice-${voiceTurn}`;
if (stage === 'user') add({ role: 'user', text, turn_id: key, status: 'pending' });
if (stage === 'reply') { add({ role: 'companion', text, turn_id: key }); rows.forEach(r => { if (r.turn_id === key) r.status = 'sent'; }); }
if (stage === 'cancel') rows.forEach(r => { if (r.turn_id === key) r.status = 'cancelled'; });
return send(res, 200, { turn: key });
}
// A reach-out the life runtime stored (HEL-898): the worker may read it aloud; the page sees it through the inbox.
// `&id=` (HEL-879 unified review) pins the stored row id a fixture's proactive frames carry; without it
// behavior is unchanged.
if (p === '/__proactive') {
const text = url.searchParams.get('text') || '', want = Number(url.searchParams.get('id') || 0);
const id = want || add({ role: 'companion', text, turn_id: `pro-${rows.length + 1}`, proactive: true });
if (want && !rows.some(r => r.id === want)) rows.push({ id: want, ts: T0 + want * 60e3 + 1, status: 'sent', lifeIds: [], role: 'companion', text, turn_id: `pro-${want}`, proactive: true });
return send(res, 200, { id });
}
// A voice turn took the server's turn gate: the text stream in flight ends without a final; its row is cancelled.
if (p === '/__cut') { const s = textStream; textStream = null; if (s) { rows.forEach(r => { if (r.turn_id === s.turn_id && r.role === 'user') r.status = 'cancelled'; }); s.cut = true; s.res.end(); } return send(res, 200, { cut: !!s }); }
if (p === '/__real-sdk.js') return send(res, 200, await readFile(join(dist, 'vendor/livekit-client-2.22.4.umd.min.js')), 'text/javascript');
if (p.startsWith('/vendor/livekit-client')) return send(res, 200, await readFile(fake), 'text/javascript');
if (p === '/api/health') return send(res, 200, { ok: true, version: 'R5-candidate', epoch, llm: { ok: true, model: 'mock' }, backend: { life: true, persona: true, receipt: true, web_connected: true }, life_runtime: { state: 'running', timezone: 'Asia/Shanghai', budget_warning: false, budget_stopped: false, last: null }, capabilities: { text: true, proactive: true, voice: false, memory: true } });
if (p === '/api/companion') return send(res, 200, identity);
if (p === '/api/messages') {
const limit = Math.min(200, Number(url.searchParams.get('limit') || 200)), before = Number(url.searchParams.get('before') || Number.MAX_SAFE_INTEGER);
const desc = rows.filter(r => r.id < before).sort((a, b) => b.id - a.id).slice(0, limit + 1), more = desc.length > limit, page = desc.slice(0, limit);
return send(res, 200, { messages: [...page].reverse().map(dto), next_before: more ? page[page.length - 1].id : null, epoch });
}
if (p === '/api/persona') return send(res, 200, { state: 'ready', interpretation: null, seeds: [], growth: [] });
if (p === '/api/life') return send(res, 200, { events: [], next_before: null, epoch });
if (p === '/api/memories') return send(res, 200, { memories: [], next_before: null, epoch });
if (p === '/api/voice/status') return send(res, 200, voice.configured ? { configured: true, tts_ok: voice.tts, agent_name: 'cybergril-voice-agent', voice: false, livekit_url: 'wss://192.168.200.12:7880' } : { configured: false, tts_ok: false, agent_name: null, voice: false });
if (p === '/api/voice/session' && req.method === 'POST') {
if (!voice.configured) return send(res, 503, { detail: '语音还没有在这台服务上配置,不能假装能通话。' });
if (refuse) return send(res, refuse, { detail: REFUSALS[refuse] || '通话服务暂时连不上,稍后再试试。' });
await sleep(120);
const id = `sess-${++made}`; sessions.set(id, { room: `cg-voice-${made}` });
return send(res, 201, { url: 'wss://lk.invalid', token: `token-${id}`, room: `cg-voice-${made}`, session_id: id, agent_name: 'cybergril-voice-agent', epoch, expires_at: Date.now() + 2 * 3600e3 });
}
if (p === '/__hold-delete') { const id = url.searchParams.get('id'); if (id) { let open; held.set(id, { promise: new Promise(r => { open = r; }), open }); } else { held.forEach(h => h.open()); held.clear(); } return send(res, 200, { held: [...held.keys()] }); }
if (p.startsWith('/api/voice/session/') && req.method === 'DELETE') { const id = decodeURIComponent(p.slice(19)); if (held.has(id)) await held.get(id).promise; return sessions.delete(id) ? send(res, 200, { ended: true }) : send(res, 404, { detail: '这次通话已经不在了。' }); }
if (p === '/api/chat' && req.method === 'POST') {
let body = ''; for await (const chunk of req) body += chunk;
const { text: said, turn_id } = JSON.parse(body), reply = '我在。今天的雨停了没有?要是还在下,就慢点回家。';
add({ role: 'user', text: said, turn_id, status: 'pending' });
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
const stream = { res, turn_id, cut: false }; textStream = stream;
for (const part of reply.match(/.{1,4}/gu)) { if (stream.cut) return; res.write(`data: ${JSON.stringify({ t: 'chat.delta', epoch, turn_id, delta: part })}\n\n`); await sleep(400); }
if (stream.cut) return;
textStream = null;
add({ role: 'companion', text: reply, turn_id }); rows.forEach(r => { if (r.turn_id === turn_id) r.status = 'sent'; });
res.end(`data: ${JSON.stringify({ t: 'chat.final', epoch, turn_id, utterance: { text: reply, speech_tags: [] }, receipt: null })}\n\n`);
return;
}
if (p.startsWith('/api/')) return send(res, 404, { detail: 'Not Found' });
const file = normalize(join(dist, p === '/' ? 'index.html' : p));
if (!file.startsWith(normalize(dist))) return send(res, 403, 'no', 'text/plain');
try { send(res, 200, await readFile(file), { '.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp' }[extname(file)] || 'application/octet-stream'); }
catch { send(res, 200, await readFile(join(dist, 'index.html')), 'text/html; charset=utf-8'); }
}).on('error', e => { console.error(`hel878 mock could not listen on ${port}: ${e.code || e.message}`); process.exit(2); })
.listen(port, '127.0.0.1', () => console.log(`hel878 mock on ${port} pid ${process.pid}`));