HEL-910: real-call retest window record — web text interrupt, wait chain, budgets, cleanup evidence
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env bash
|
||||
# HEL-910 测试窗口:统一实例(8360 HTTP + 8361 HTTPS 同进程双入口)启动/停止
|
||||
# 用法: bash api_ctl.sh start|stop|status (models.yaml 由调用方先摆好:failclosed 或 armed)
|
||||
set -u
|
||||
BASE=/opt/cybergril-hel910
|
||||
CODE=$BASE/current
|
||||
LOG=$BASE/logs/api.log
|
||||
PIDF=$BASE/logs/api.pid
|
||||
PAT='cybergril-hel910.*serve_dual_8360_8361'
|
||||
|
||||
stop() {
|
||||
if [ -f "$PIDF" ]; then
|
||||
P=$(cat "$PIDF")
|
||||
if [ "$P" != "$$" ] && kill -0 "$P" 2>/dev/null; then kill "$P"; sleep 3; fi
|
||||
if [ "$P" != "$$" ] && kill -0 "$P" 2>/dev/null; then kill -9 "$P"; fi
|
||||
rm -f "$PIDF"
|
||||
fi
|
||||
for p in $(pgrep -f "$PAT"); do
|
||||
[ "$p" = "$$" ] && continue
|
||||
kill "$p" 2>/dev/null
|
||||
done
|
||||
echo "api stopped"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
stop) stop; exit 0 ;;
|
||||
status)
|
||||
pgrep -af "$PAT" || echo "not running"
|
||||
exit 0 ;;
|
||||
esac
|
||||
|
||||
stop
|
||||
cd "$CODE"
|
||||
set -a
|
||||
export CYBERGRIL_DB=$BASE/data/companion.db
|
||||
export CYBERGRIL_SEMANTIC=stub
|
||||
export CYBERGRIL_R2_ENABLED=1
|
||||
export CYBERGRIL_MODELS=$BASE/etc/models.yaml
|
||||
export CYBERGRIL_VOICE_CONFIG=$BASE/etc/voice.yaml
|
||||
export CYBERGRIL_WEB=$CODE/web/dist
|
||||
export PYTHONPATH=$CODE/src
|
||||
set +a
|
||||
nohup /opt/cybergril-hel879/current/.venv311/bin/python deploy/voice/serve_dual_8360_8361.py \
|
||||
--http-port 8360 --https-port 8361 \
|
||||
--cert /opt/cybergril-voice-certs/cybergril-voice.pem \
|
||||
--key /opt/cybergril-voice-certs/cybergril-voice.key \
|
||||
> "$LOG" 2>&1 &
|
||||
echo $! > "$PIDF"
|
||||
echo "api starting (pid $(cat $PIDF))"
|
||||
sleep 6
|
||||
curl -s --max-time 3 http://127.0.0.1:8360/api/health >/dev/null && echo "OK: 8360 healthy" || { echo "FAIL:"; tail -20 "$LOG"; exit 1; }
|
||||
curl -sk --max-time 3 https://127.0.0.1:8361/api/health >/dev/null && echo "OK: 8361 healthy" || { echo "FAIL 8361:"; tail -20 "$LOG"; exit 1; }
|
||||
@@ -0,0 +1,4 @@
|
||||
# HEL-910 ASR 窗口布防(2026-10-29):新窗口 id,720 秒保守预记,每通重连≤2
|
||||
CYBERGRIL_ASR_WINDOW_ID=hel910-20261029-a
|
||||
CYBERGRIL_ASR_WINDOW_MAX_AUDIO_SECONDS=720
|
||||
CYBERGRIL_ASR_MAX_CONNECT_RETRIES_PER_CALL=2
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
# HEL-910 测试窗口:WSS TLS 桥 8363 -> 127.0.0.1:7880 启动/停止
|
||||
set -u
|
||||
BASE=/opt/cybergril-hel910
|
||||
LOG=$BASE/logs/bridge.log
|
||||
PIDF=$BASE/logs/bridge.pid
|
||||
PAT='cybergril-hel910.*wss_bridge'
|
||||
|
||||
stop() {
|
||||
if [ -f "$PIDF" ]; then
|
||||
P=$(cat "$PIDF")
|
||||
if [ "$P" != "$$" ] && kill -0 "$P" 2>/dev/null; then kill "$P"; sleep 2; fi
|
||||
rm -f "$PIDF"
|
||||
fi
|
||||
for p in $(pgrep -f "$PAT"); do
|
||||
[ "$p" = "$$" ] && continue
|
||||
kill "$p" 2>/dev/null
|
||||
done
|
||||
echo "bridge stopped"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
stop) stop; exit 0 ;;
|
||||
status)
|
||||
pgrep -af "$PAT" || echo "not running"
|
||||
exit 0 ;;
|
||||
esac
|
||||
|
||||
stop
|
||||
nohup /usr/bin/python3 $BASE/current/deploy/voice/wss_bridge.example.py \
|
||||
--listen 0.0.0.0:8363 --upstream 127.0.0.1:7880 \
|
||||
--cert /opt/cybergril-voice-certs/cybergril-voice.pem \
|
||||
--key /opt/cybergril-voice-certs/cybergril-voice.key \
|
||||
> "$LOG" 2>&1 &
|
||||
echo $! > "$PIDF"
|
||||
echo "bridge starting (pid $(cat $PIDF))"
|
||||
sleep 3
|
||||
timeout 8 openssl s_client -connect 127.0.0.1:8363 -servername 192.168.200.12 </dev/null 2>/dev/null | grep -q "Protocol.*TLSv1.3\|New, TLSv1.3" && echo "OK: bridge TLS up" || { echo "WARN: TLS probe inconclusive, check $LOG"; tail -5 "$LOG"; }
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build Chromium fake-audio-capture WAVs for HEL-910 (offline, workstation-local).
|
||||
|
||||
Pure stdlib (array/audioop-free) — resample by linear interpolation, mix to mono,
|
||||
place utterances on a fixed schedule padded with silence; Chromium loops the file.
|
||||
Usage: build_fake_wavs.py <outdir>
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
RATE = 16000
|
||||
|
||||
|
||||
def read_mono_16k(path: str) -> bytes:
|
||||
with wave.open(path, "rb") as w:
|
||||
raw = w.readframes(w.getnframes())
|
||||
rate, ch, width = w.getframerate(), w.getnchannels(), w.getsampwidth()
|
||||
assert width == 2, path
|
||||
total = len(raw) // (2 * ch)
|
||||
# de-interleave + average channels
|
||||
acc = [0.0] * total
|
||||
for c in range(ch):
|
||||
off = c
|
||||
for i in range(total):
|
||||
s = raw[(i * ch + off) * 2] | (raw[(i * ch + off) * 2 + 1] << 8)
|
||||
if s >= 32768:
|
||||
s -= 65536
|
||||
acc[i] += s
|
||||
mono = [int(round(a / ch)) for a in acc]
|
||||
if rate == RATE:
|
||||
return b"".join(max(-32768, min(32767, s)).to_bytes(2, "little", signed=True) for s in mono)
|
||||
n_out = int(len(mono) * RATE / rate)
|
||||
out = bytearray()
|
||||
step = rate / RATE
|
||||
for j in range(n_out):
|
||||
x = j * step
|
||||
i = int(x)
|
||||
frac = x - i
|
||||
s = mono[i] * (1 - frac) + (mono[i + 1] if i + 1 < len(mono) else mono[i]) * frac
|
||||
v = max(-32768, min(32767, int(round(s))))
|
||||
out += v.to_bytes(2, "little", signed=True)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def trim_silence(pcm: bytes, thresh: float = 0.05) -> bytes:
|
||||
# trim leading/trailing near-silence (50ms windows) — keep speech core
|
||||
n = len(pcm) // 2
|
||||
vals = [pcm[i * 2] | (pcm[i * 2 + 1] << 8) for i in range(n)]
|
||||
vals = [v - 65536 if v >= 32768 else v for v in vals]
|
||||
win = 800
|
||||
nw = n // win
|
||||
peak = 1
|
||||
for w0 in range(nw):
|
||||
m = max(abs(v) for v in vals[w0 * win:(w0 + 1) * win]) or 0
|
||||
peak = max(peak, m)
|
||||
t = peak * thresh
|
||||
first, last = 0, nw - 1
|
||||
for w0 in range(nw):
|
||||
if max(abs(v) for v in vals[w0 * win:(w0 + 1) * win]) > t:
|
||||
first = w0
|
||||
break
|
||||
for w0 in range(nw - 1, -1, -1):
|
||||
if max(abs(v) for v in vals[w0 * win:(w0 + 1) * win]) > t:
|
||||
last = w0
|
||||
break
|
||||
lo, hi = max(0, first - 2) * win, min(n, (last + 3) * win)
|
||||
out = bytearray()
|
||||
for v in vals[lo:hi]:
|
||||
out += max(-32768, min(32767, v)).to_bytes(2, "little", signed=True)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def silence(seconds: float) -> bytes:
|
||||
return b"\x00\x00" * int(RATE * seconds)
|
||||
|
||||
|
||||
def write_wav(path: Path, pcm: bytes, rate: int = RATE) -> None:
|
||||
with wave.open(str(path), "wb") as w:
|
||||
w.setnchannels(1)
|
||||
w.setsampwidth(2)
|
||||
w.setframerate(rate)
|
||||
w.writeframes(pcm)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
outdir = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
|
||||
outdir.mkdir(parents=True, exist_ok=True)
|
||||
src = Path("/tmp/multica-task-2856608943/opencode")
|
||||
u_hai = trim_silence(read_mono_16k(str(src / "haimianbaobao.wav")))
|
||||
u_baj = trim_silence(read_mono_16k(str(src / "bajie.wav")))
|
||||
u_xiao = trim_silence(read_mono_16k(str(src / "xiaoyun.wav")))
|
||||
meta: dict[str, dict] = {}
|
||||
secs = lambda p: len(p) / (2 * RATE)
|
||||
|
||||
# call1 browser schedule: U1@0 (reply R1), U2@60 (gen-cancel target),
|
||||
# U3@120 (voice recovery). Cycle 240s so a 4th utterance never arrives inside
|
||||
# the ~170s planned call.
|
||||
c1 = bytearray()
|
||||
c1 += u_hai
|
||||
c1 += silence(60 - secs(u_hai))
|
||||
c1 += u_baj
|
||||
c1 += silence(120 - 60 - secs(u_baj))
|
||||
c1 += u_hai
|
||||
c1 += silence(240 - 120 - secs(u_hai))
|
||||
write_wav(outdir / "hel910_call1_fake.wav", bytes(c1))
|
||||
meta["call1"] = {
|
||||
"u1_haimianbaobao_s": [0.0, round(secs(u_hai), 2)],
|
||||
"u2_bajie_s": [60.0, round(60 + secs(u_baj), 2)],
|
||||
"u3_haimianbaobao_s": [120.0, round(120 + secs(u_hai), 2)],
|
||||
"cycle_s": 240,
|
||||
}
|
||||
|
||||
# offline probe wav for the local fake-capture feasibility check: 3s speech, 8s silence
|
||||
t = bytearray()
|
||||
t += u_hai[: RATE * 3 * 2]
|
||||
t += silence(8.0)
|
||||
write_wav(outdir / "probe_fake.wav", bytes(t))
|
||||
meta["probe"] = {"speech_s": [0.0, round(min(secs(u_hai), 3.0), 2)], "cycle_s": round(min(secs(u_hai), 3.0) + 8.0, 2)}
|
||||
|
||||
for name, pcm in (("u_haimianbaobao", u_hai), ("u_bajie", u_baj), ("u_xiaoyun", u_xiao)):
|
||||
write_wav(outdir / f"{name}.trim.wav", pcm)
|
||||
meta[name] = {"seconds": round(secs(pcm), 2)}
|
||||
(outdir / "fake-wav-meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1))
|
||||
print(json.dumps(meta, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env bash
|
||||
# HEL-910 窗口截止保护:45 分钟硬顶到点强制收尾(也供 watchdog 与异常路径调用)。
|
||||
# 只动本窗专属句柄(pid 文件里的精确 PID)与本窗房间;绝不按程序名/端口扫杀,
|
||||
# 绝不触碰 8300/8310/8320/8350、7880/7881、10095、8081 等共享服务。
|
||||
set -u
|
||||
BASE=/opt/cybergril-hel910
|
||||
LOG=$BASE/logs/force_end.log
|
||||
ts() { date -u +%FT%TZ; }
|
||||
{
|
||||
echo "[$(ts)] force_end begin"
|
||||
# 1) 结清本窗房间(实例自己的登记账;DELETE 走统一实例所有者路径)
|
||||
for sid in $(python3 - "$BASE/data" <<'EOF' 2>/dev/null
|
||||
import json, sys, pathlib
|
||||
p = pathlib.Path(sys.argv[1]) / "companion-voice-sessions.json"
|
||||
try:
|
||||
d = json.loads(p.read_text())
|
||||
except Exception:
|
||||
raise SystemExit
|
||||
state = d.get("state", d)
|
||||
def walk(o):
|
||||
if isinstance(o, dict):
|
||||
for k, v in o.items():
|
||||
if k in ("sessions", "active") and isinstance(v, dict):
|
||||
for sid, sess in v.items():
|
||||
print(sid)
|
||||
else:
|
||||
walk(v)
|
||||
elif isinstance(o, list):
|
||||
for i in o:
|
||||
walk(i)
|
||||
walk(state)
|
||||
EOF
|
||||
); do
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 8 -X DELETE "http://127.0.0.1:8360/api/voice/session/$sid" || echo err)
|
||||
echo "[$(ts)] DELETE session $sid -> $code"
|
||||
done
|
||||
# 2) 停专属组件(每步都幂等)
|
||||
bash $BASE/ctl/worker_ctl.sh stop 2>&1 | sed 's/^/ worker: /'
|
||||
bash $BASE/ctl/api_ctl.sh stop 2>&1 | sed 's/^/ api: /'
|
||||
bash $BASE/ctl/bridge_ctl.sh stop 2>&1 | sed 's/^/ bridge: /'
|
||||
# 3) 共享 TTS 9880:只停我们启动的那个 PID
|
||||
bash $BASE/ctl/tts_ctl.sh stop 2>&1 | sed 's/^/ tts: /'
|
||||
echo "[$(ts)] force_end done"
|
||||
} >> "$LOG" 2>&1
|
||||
@@ -0,0 +1,274 @@
|
||||
// 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);
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
#!/usr/bin/env python3
|
||||
"""HEL-910 real-window voice test client (runs on .12, agent venv).
|
||||
|
||||
继承 HEL-907 hel907_client 的真链框架(预录音频回放经真实 WebRTC ->
|
||||
LiveKit -> FunASR -> 统一 /api/chat(LLM) -> CosyVoice -> WebRTC 回流),
|
||||
为本卡改造:dry(建房即删的挂断核验)、call2(稍长问题的首文/首声时延 +
|
||||
回放打断停声同钟量测 + 思考泄漏取证)。所有时间戳同一客户端时钟(毫秒)。
|
||||
文字打断的「真实网页原发送入口」场景在本机浏览器驱动脚本里,不在本文件。
|
||||
|
||||
Usage: hel910_client.py <phase> <outdir>
|
||||
phases: dry | call2 | status
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from livekit import api, rtc
|
||||
|
||||
API = "http://127.0.0.1:8360"
|
||||
LK_INTERNAL = "http://127.0.0.1:7880"
|
||||
KEY = "devkey"
|
||||
SECRET = "voiceagent-local-secret-2026"
|
||||
SAMPLES = Path("/opt/voice-agent/cosyvoice/voice_samples")
|
||||
TRIM = Path("/opt/cybergril-hel910/etc/trim")
|
||||
DB = "/opt/cybergril-hel910/data/companion.db"
|
||||
OUT = Path(sys.argv[2] if len(sys.argv) > 2 else "/opt/cybergril-hel910/evidence")
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
T0 = time.time()
|
||||
|
||||
|
||||
def log(msg: str) -> None:
|
||||
print(f"[{time.time()-T0:8.2f}] {msg}", flush=True)
|
||||
|
||||
|
||||
def now_ms() -> int:
|
||||
return int(time.time() * 1000)
|
||||
|
||||
|
||||
def load_wav_16k_mono(p: Path) -> bytes:
|
||||
with wave.open(str(p), "rb") as w:
|
||||
raw = w.readframes(w.getnframes())
|
||||
rate, ch, width = w.getframerate(), w.getnchannels(), w.getsampwidth()
|
||||
assert width == 2 and ch == 1 and rate == 16000, f"{p}: {rate}Hz ch{ch} w{width}"
|
||||
return raw
|
||||
|
||||
|
||||
async def list_rooms() -> list[str]:
|
||||
lk = api.LiveKitAPI(url=LK_INTERNAL, api_key=KEY, api_secret=SECRET)
|
||||
try:
|
||||
res = await lk.room.list_rooms(api.ListRoomsRequest())
|
||||
return [r.name for r in res.rooms]
|
||||
finally:
|
||||
await lk.aclose()
|
||||
|
||||
|
||||
def safe_json(r: httpx.Response):
|
||||
try:
|
||||
return r.json()
|
||||
except Exception:
|
||||
return r.text[:200]
|
||||
|
||||
|
||||
class Call:
|
||||
"""One voice call through the real product API; full frame timeline kept."""
|
||||
|
||||
def __init__(self, tag: str):
|
||||
self.tag = tag
|
||||
self.http = httpx.AsyncClient(timeout=15)
|
||||
self.room: rtc.Room | None = None
|
||||
self.session: dict = {}
|
||||
self.source: rtc.AudioSource | None = None
|
||||
self.track: rtc.LocalAudioTrack | None = None
|
||||
self.subtitles: list[dict] = []
|
||||
self.frames: list[tuple[int, int]] = [] # (arrival_ms, bytes)
|
||||
self.agent_audio = bytearray()
|
||||
self.audio_rate = 48000
|
||||
self.agent_joined_ms: int | None = None
|
||||
self._speaking = False
|
||||
self._keeper: asyncio.Task | None = None
|
||||
self._first_pub_ms: int | None = None
|
||||
|
||||
async def open(self) -> dict:
|
||||
r = await self.http.post(f"{API}/api/voice/session")
|
||||
r.raise_for_status()
|
||||
self.session = r.json()
|
||||
log(f"[{self.tag}] session room={self.session['room']} voice={self.session.get('voice')} epoch={self.session['epoch']}")
|
||||
return self.session
|
||||
|
||||
async def connect(self) -> None:
|
||||
url = self.session["url"]
|
||||
self.room = rtc.Room()
|
||||
self.room.on("data_received", self._on_data)
|
||||
self.room.on("track_subscribed", self._on_track)
|
||||
self.room.on("participant_connected", self._on_participant)
|
||||
await self.room.connect(url, self.session["token"])
|
||||
self.source = rtc.AudioSource(16000, 1)
|
||||
self.track = rtc.LocalAudioTrack.create_audio_track("mic", self.source)
|
||||
opt = rtc.TrackPublishOptions()
|
||||
opt.source = rtc.TrackSource.SOURCE_MICROPHONE
|
||||
await self.room.local_participant.publish_track(self.track, opt)
|
||||
log(f"[{self.tag}] connected via {url} mic published")
|
||||
self._keeper = asyncio.create_task(self._keep_silent())
|
||||
|
||||
async def _keep_silent(self) -> None:
|
||||
silence = b"\x00" * 3200
|
||||
while self.source is not None:
|
||||
if not self._speaking:
|
||||
try:
|
||||
await self.source.capture_frame(
|
||||
rtc.AudioFrame(silence, 16000, 1, 1600))
|
||||
except Exception:
|
||||
return
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
def _on_data(self, msg: rtc.DataPacket) -> None:
|
||||
try:
|
||||
payload = json.loads(msg.data.decode("utf-8"))
|
||||
except Exception:
|
||||
return
|
||||
payload["_at_ms"] = now_ms()
|
||||
self.subtitles.append(payload)
|
||||
text = str(payload.get("text", ""))[:40]
|
||||
log(f"[{self.tag}][sub] seq={payload.get('seq')} kind={payload.get('kind')} "
|
||||
f"role={payload.get('role')} {text}")
|
||||
|
||||
def _on_participant(self, p: rtc.RemoteParticipant) -> None:
|
||||
log(f"[{self.tag}] joined: {p.identity}")
|
||||
if "agent" in p.identity:
|
||||
self.agent_joined_ms = now_ms()
|
||||
|
||||
def _on_track(self, track: rtc.Track, pub, participant) -> None:
|
||||
if track.kind != rtc.TrackKind.KIND_AUDIO:
|
||||
return
|
||||
log(f"[{self.tag}] agent audio track: {track.sid}")
|
||||
|
||||
async def read():
|
||||
stream = rtc.AudioStream(track)
|
||||
async for ev in stream:
|
||||
frame = ev.frame
|
||||
self.audio_rate = frame.sample_rate
|
||||
self.frames.append((now_ms(), len(bytes(frame.data))))
|
||||
self.agent_audio.extend(bytes(frame.data))
|
||||
|
||||
asyncio.create_task(read())
|
||||
|
||||
async def _publish_pcm(self, pcm: bytes, label: str) -> dict:
|
||||
self._speaking = True
|
||||
started = now_ms()
|
||||
self._first_pub_ms = self._first_pub_ms or started
|
||||
step = 3200
|
||||
try:
|
||||
for i in range(0, len(pcm), step):
|
||||
chunk = pcm[i:i + step]
|
||||
if len(chunk) < step:
|
||||
chunk = chunk + b"\x00" * (step - len(chunk))
|
||||
await self.source.capture_frame(rtc.AudioFrame(chunk, 16000, 1, 1600))
|
||||
await asyncio.sleep(0.1)
|
||||
finally:
|
||||
self._speaking = False
|
||||
ended = now_ms()
|
||||
log(f"[{self.tag}] played {label} {len(pcm)/32000:.1f}s ({started}->{ended})")
|
||||
return {"label": label, "start_ms": started, "end_ms": ended}
|
||||
|
||||
async def speak(self, pcm: bytes, label: str) -> dict:
|
||||
return await self._publish_pcm(pcm, label)
|
||||
|
||||
async def wait_kind(self, kinds: tuple[str, ...], timeout: float, after_idx: int = 0) -> tuple[int, dict] | None:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
await asyncio.sleep(0.05)
|
||||
for i, s in enumerate(self.subtitles[after_idx:], start=after_idx):
|
||||
if s.get("kind") in kinds:
|
||||
return i, s
|
||||
return None
|
||||
|
||||
async def wait_reply(self, timeout: float = 60.0) -> dict:
|
||||
start_len = len(self.subtitles)
|
||||
deadline = time.time() + timeout
|
||||
seen_speech: str | None = None
|
||||
while time.time() < deadline:
|
||||
await asyncio.sleep(0.2)
|
||||
for s in self.subtitles[start_len:]:
|
||||
if s.get("kind") == "turn_start":
|
||||
seen_speech = s.get("speech_id")
|
||||
if s.get("kind") in ("turn_end", "turn_cancel") and (
|
||||
seen_speech is None or s.get("speech_id") == seen_speech):
|
||||
return {"kind": s["kind"], "speech_id": s.get("speech_id"),
|
||||
"reason": s.get("reason")}
|
||||
return {"kind": "timeout", "speech_id": seen_speech}
|
||||
|
||||
async def speak_and_wait(self, pcm: bytes, label: str, timeout: float = 60.0) -> dict:
|
||||
play = asyncio.create_task(self._publish_pcm(pcm, label))
|
||||
reply = await self.wait_reply(timeout)
|
||||
await play
|
||||
return {"play_label": label, "reply": reply}
|
||||
|
||||
async def wait_frames(self, min_seconds: float = 2.0, timeout: float = 40.0) -> int | None:
|
||||
"""Wait until agent audio frames have been arriving for min_seconds."""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
await asyncio.sleep(0.1)
|
||||
if len(self.frames) >= 2:
|
||||
cutoff = self.frames[-1][0] - int(min_seconds * 1000)
|
||||
earliest_in_window = next((t for t, _ in reversed(self.frames) if t < cutoff), None)
|
||||
if earliest_in_window is not None:
|
||||
return now_ms()
|
||||
# fewer than min_seconds of frames recorded at all
|
||||
if self.frames[-1][0] - self.frames[0][0] >= int(min_seconds * 1000) - 300:
|
||||
return now_ms()
|
||||
return None
|
||||
|
||||
async def barge_interrupt(self, pcm: bytes) -> dict:
|
||||
"""她长回复实际有声时,用预录响亮短句回放打断(真实 WebRTC 发布)。
|
||||
|
||||
T0 = 打断音频首帧发布;T1 = 旧语音最后一帧到达(≥1s 帧间隙分界)。
|
||||
声源为预录 WAV 回放(工程输入),非真实用户麦克风。
|
||||
"""
|
||||
base_subs = len(self.subtitles)
|
||||
ready = await self.wait_frames(min_seconds=3.0, timeout=45.0)
|
||||
if ready is None:
|
||||
return {"outcome": "no-audible-old-voice"}
|
||||
barge = asyncio.create_task(self.speak(pcm, "barge-xiaoyun"))
|
||||
# 打断首帧真正发布时刻由 speak 返回;此处先记发起
|
||||
cancel_ms = None
|
||||
deadline = time.time() + 25
|
||||
while time.time() < deadline:
|
||||
await asyncio.sleep(0.05)
|
||||
for s in self.subtitles[base_subs:]:
|
||||
if s.get("kind") == "turn_cancel":
|
||||
cancel_ms = s["_at_ms"]
|
||||
break
|
||||
if cancel_ms:
|
||||
break
|
||||
await asyncio.sleep(14.0) # 观察旧声停止 + 新回复起播
|
||||
await barge
|
||||
timeline = [t for (t, _) in self.frames]
|
||||
last_old = None
|
||||
for i, t in enumerate(timeline):
|
||||
if i + 1 < len(timeline) and timeline[i + 1] - t >= 1000:
|
||||
last_old = t
|
||||
break
|
||||
if last_old is None and timeline:
|
||||
last_old = timeline[-1]
|
||||
return {
|
||||
"outcome": "interrupted" if cancel_ms else "no-cancel",
|
||||
"old_audio_last_frame_ms": last_old,
|
||||
"cancel_ms": cancel_ms,
|
||||
"frames_total": len(self.frames),
|
||||
"source": "pre-recorded wav playback over real WebRTC (not a human microphone)",
|
||||
}
|
||||
|
||||
async def hangup(self) -> dict:
|
||||
sid = self.session.get("session_id")
|
||||
self.source = None
|
||||
frames_at_hangup = len(self.frames)
|
||||
t_delete = now_ms()
|
||||
r = await self.http.delete(f"{API}/api/voice/session/{sid}")
|
||||
body = {"delete_status": r.status_code, "delete_body": safe_json(r),
|
||||
"delete_ms": t_delete}
|
||||
await asyncio.sleep(0.5)
|
||||
if self.room is not None:
|
||||
await self.room.disconnect()
|
||||
await asyncio.sleep(2.0)
|
||||
body["agent_frames_after_delete"] = len(self.frames) - frames_at_hangup
|
||||
lk = api.LiveKitAPI(url=LK_INTERNAL, api_key=KEY, api_secret=SECRET)
|
||||
try:
|
||||
res = await lk.room.list_rooms(api.ListRoomsRequest(names=[self.session["room"]]))
|
||||
body["room_removed"] = len(res.rooms) == 0
|
||||
finally:
|
||||
await lk.aclose()
|
||||
log(f"[{self.tag}] hangup: {body}")
|
||||
return body
|
||||
|
||||
def save(self, name: str) -> dict:
|
||||
sub_path = OUT / f"{name}.subtitles.jsonl"
|
||||
with sub_path.open("w", encoding="utf-8") as f:
|
||||
for s in self.subtitles:
|
||||
f.write(json.dumps(s, ensure_ascii=False) + "\n")
|
||||
tl_path = OUT / f"{name}.frames.json"
|
||||
tl_path.write_text(json.dumps(
|
||||
{"first_pub_ms": self._first_pub_ms,
|
||||
"frames": self.frames}, ensure_ascii=False))
|
||||
audio_path = None
|
||||
if self.agent_audio:
|
||||
audio_path = OUT / f"{name}.agent.wav"
|
||||
with wave.open(str(audio_path), "wb") as w:
|
||||
w.setnchannels(1)
|
||||
w.setsampwidth(2)
|
||||
w.setframerate(self.audio_rate)
|
||||
w.writeframes(bytes(self.agent_audio))
|
||||
seqs = [s.get("seq") for s in self.subtitles if isinstance(s.get("seq"), int)]
|
||||
return {
|
||||
"tag": self.tag,
|
||||
"session": self.session,
|
||||
"session_voice": self.session.get("voice"),
|
||||
"subtitle_count": len(self.subtitles),
|
||||
"seq_monotonic": all(b > a for a, b in zip(seqs, seqs[1:])),
|
||||
"agent_frames": len(self.frames),
|
||||
"agent_audio_seconds": round(len(self.agent_audio) / 2 / self.audio_rate, 1),
|
||||
"agent_audio_rate": self.audio_rate,
|
||||
"agent_joined_ms": self.agent_joined_ms,
|
||||
"subtitles_file": str(sub_path),
|
||||
"frames_file": str(tl_path),
|
||||
"agent_audio_file": str(audio_path) if audio_path else None,
|
||||
}
|
||||
|
||||
|
||||
def _db_query(sql: str, params: tuple = ()) -> list[dict]:
|
||||
import sqlite3
|
||||
conn = sqlite3.connect(f"file:{DB}?mode=ro", uri=True)
|
||||
conn.row_factory = sqlite3.Row
|
||||
try:
|
||||
return [dict(r) for r in conn.execute(sql, params)]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def db_dump() -> dict:
|
||||
out: dict = {}
|
||||
try:
|
||||
out["chat_message"] = _db_query(
|
||||
"SELECT id, ts, role, turn_id, status, substr(text,1,120) AS text FROM chat_message ORDER BY id")
|
||||
out["budget_total"] = _db_query("SELECT key, value FROM budget_total")
|
||||
out["token_usage"] = _db_query("SELECT day, scene, used FROM token_usage")
|
||||
out["request_usage"] = _db_query("SELECT * FROM request_usage")
|
||||
except Exception as e:
|
||||
out["error"] = str(e)
|
||||
return out
|
||||
|
||||
|
||||
def budget_snapshot() -> dict:
|
||||
out: dict = {"at_ms": now_ms()}
|
||||
try:
|
||||
out["token_usage"] = _db_query("SELECT day, scene, used FROM token_usage")
|
||||
out["request_usage"] = _db_query("SELECT * FROM request_usage")
|
||||
out["budget_total"] = _db_query("SELECT key, value FROM budget_total")
|
||||
except Exception as e:
|
||||
out["error"] = str(e)
|
||||
return out
|
||||
|
||||
|
||||
def asr_ledger_summary() -> dict:
|
||||
p = Path("/opt/cybergril-hel910/asr-usage.jsonl")
|
||||
if not p.exists():
|
||||
return {"exists": False}
|
||||
events = [json.loads(l) for l in p.read_text().splitlines() if l.strip()]
|
||||
return {"exists": True, "events": len(events), "raw": events[-8:]}
|
||||
|
||||
|
||||
def worker_state() -> dict:
|
||||
p = Path("/opt/cybergril-hel910/worker/voice_state_cybergril.json")
|
||||
if not p.exists():
|
||||
return {"exists": False}
|
||||
try:
|
||||
return {"exists": True, "content": json.loads(p.read_text())}
|
||||
except Exception as e:
|
||||
return {"exists": True, "error": str(e)}
|
||||
|
||||
|
||||
def save_json(name: str, payload: dict) -> None:
|
||||
path = OUT / f"{name}.json"
|
||||
path.write_text(json.dumps(payload, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
log(f"saved {path}")
|
||||
|
||||
|
||||
async def phase_dry() -> None:
|
||||
"""建房即删:核验建房/派发/删除链路与房间清空;不发音频、无 LLM/TTS。"""
|
||||
rooms_before = await list_rooms()
|
||||
call = Call("dry")
|
||||
await call.open()
|
||||
await asyncio.sleep(10) # 给 worker 派发入房
|
||||
rooms_mid = await list_rooms()
|
||||
hangup = await call.hangup()
|
||||
await asyncio.sleep(2)
|
||||
rooms_after = await list_rooms()
|
||||
save_json("dry", {"rooms_before": rooms_before, "rooms_mid": rooms_mid,
|
||||
"hangup": hangup, "rooms_after": rooms_after,
|
||||
"budget_after": budget_snapshot(),
|
||||
"asr_ledger_after": asr_ledger_summary()})
|
||||
|
||||
|
||||
async def phase_call2() -> None:
|
||||
"""第二通:稍长问题(bajie)首文/首声时延 + 回放打断(xiaoyun)停声同钟量测。"""
|
||||
call = Call("call2")
|
||||
await call.open()
|
||||
sess_voice = call.session.get("voice")
|
||||
await call.connect()
|
||||
marks: dict[str, int | None] = {}
|
||||
base = len(call.subtitles)
|
||||
|
||||
await call.speak(load_wav_16k_mono(TRIM / "u_bajie.trim.wav"), "q-bajie")
|
||||
# 输入结束 = 回放发完
|
||||
marks["playback_end_ms"] = now_ms()
|
||||
# user_final
|
||||
got = await call.wait_kind(("user_final",), timeout=25)
|
||||
marks["user_final_ms"] = got[1]["_at_ms"] if got else None
|
||||
# 她的回复:turn_start(buffer_turn 下 interim 不先于全文)
|
||||
got = await call.wait_kind(("turn_start",), timeout=60, after_idx=base)
|
||||
marks["turn_start_ms"] = got[1]["_at_ms"] if got else None
|
||||
got = await call.wait_kind(("assistant_final", "turn_cancel", "error"), timeout=90, after_idx=base)
|
||||
marks["assistant_final_ms"] = got[1]["_at_ms"] if got else None
|
||||
marks["assistant_final_kind"] = got[1].get("kind") if got else None
|
||||
reply_text = (got[1].get("text") if got else "") or ""
|
||||
# 首帧音频(回放发完之后到达的第一帧她的音频)
|
||||
after = [t for (t, _) in call.frames if t > marks["playback_end_ms"]]
|
||||
marks["first_agent_frame_ms"] = after[0] if after else None
|
||||
# 等她实际有声再打断(不等 turn_end:那时音频已播完)
|
||||
barge = await call.barge_interrupt(load_wav_16k_mono(TRIM / "u_xiaoyun.trim.wav"))
|
||||
# 打断后的新回复
|
||||
new = await call.wait_kind(("user_final",), timeout=20)
|
||||
barge["new_user_final_ms"] = new[1]["_at_ms"] if new else None
|
||||
new_reply = await call.wait_kind(("turn_end", "turn_cancel"), timeout=90)
|
||||
barge["new_reply_end"] = {"kind": new_reply[1].get("kind"), "at_ms": new_reply[1]["_at_ms"]} if new_reply else None
|
||||
|
||||
# 时机A:她仍在生成时发文字(turn_start=生成开始;文字 POST 取消服务端活动轮)。
|
||||
# 口径如实:本步文字走 API 直发(python 客户端),不是网页输入框;网页入口的
|
||||
# 两种时机已在第一通完成(T1 在播时、T2 在 final→待播间隙)。
|
||||
base2 = len(call.subtitles)
|
||||
await call.speak(load_wav_16k_mono(TRIM / "u_bajie.trim.wav"), "q2-bajie")
|
||||
got = await call.wait_kind(("turn_start",), timeout=40, after_idx=base2)
|
||||
marks["q2_turn_start_ms"] = got[1]["_at_ms"] if got else None
|
||||
a_out: dict = {"fired": False}
|
||||
if got:
|
||||
h = (await call.http.get(f"{API}/api/health")).json()
|
||||
a_text = "先别把这句长回答生成完,我打字打断你:只用一句话告诉我你现在待在哪个角落。"
|
||||
t_post = now_ms()
|
||||
r = await call.http.post(f"{API}/api/chat", json={
|
||||
"text": a_text, "turn_id": str(__import__("uuid").uuid4()), "epoch": h["epoch"]},
|
||||
timeout=90)
|
||||
a_out = {"fired": True, "post_ms": t_post, "status": r.status_code,
|
||||
"body_head": r.text[:200]}
|
||||
marks["A_post_ms"] = t_post
|
||||
# 预期:语音轮 turn_cancel(生成被取消,零泄漏零复活),文字轮获完整回复
|
||||
got2 = await call.wait_kind(("turn_cancel",), timeout=30, after_idx=base2)
|
||||
a_out["voice_turn_cancel_ms"] = got2[1]["_at_ms"] if got2 else None
|
||||
a_out["voice_turn_cancel_reason"] = got2[1].get("reason") if got2 else None
|
||||
# 她此后不得再为 Q2 发声(观察窗口)
|
||||
quiet_from = now_ms()
|
||||
await asyncio.sleep(8.0)
|
||||
a_out["q2_frames_after_cancel"] = sum(1 for (t, _) in call.frames if t >= quiet_from)
|
||||
timing_a = a_out
|
||||
|
||||
await asyncio.sleep(3.0)
|
||||
hangup = await call.hangup()
|
||||
save_json("call2", {"session_voice": sess_voice, "marks": marks,
|
||||
"reply_text_head": reply_text[:200],
|
||||
"barge": barge, "timing_a": timing_a,
|
||||
"hangup": hangup, "call": call.save("call2"),
|
||||
"budget_after": budget_snapshot(),
|
||||
"worker_state_after": worker_state(),
|
||||
"db_dump": db_dump(),
|
||||
"asr_ledger_after": asr_ledger_summary()})
|
||||
|
||||
|
||||
async def phase_status() -> None:
|
||||
rooms = await list_rooms()
|
||||
save_json("status", {"rooms": rooms, "budget": budget_snapshot(),
|
||||
"worker_state": worker_state(),
|
||||
"asr_ledger": asr_ledger_summary(), "db": db_dump()})
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
phase = sys.argv[1]
|
||||
fn = {"dry": phase_dry, "call2": phase_call2, "status": phase_status}[phase]
|
||||
await fn()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,88 @@
|
||||
# HEL-910 一次性真实测试窗口部署配置(2026-10-29,服务器本地文件,不入仓库)
|
||||
# 授权:白栖知主卡 HEL-797 评论 01a18753-8c70-7181-9758-5bab4685ba9f「继续测」,
|
||||
# 批准《HEL-797-交谈修复复测安排.md》。LLM ≤10 请求、≤40000 tokens;嵌入 0
|
||||
# (CYBERGRIL_SEMANTIC=stub);生活/后台/语义 0。失败/取消/重试均计入(发送前预占)。
|
||||
# 窗口结束封账,余额不结转。tiers/routing/asr/tts/vad/turn/embedding/avatar 与
|
||||
# 候选 958c696 的 config/models.yaml 逐字一致(含 HEL-908 reasoning: buffer_turn)。
|
||||
tiers:
|
||||
high:
|
||||
provider: openai_compat
|
||||
model: halogen-qwen3.8-flash-next
|
||||
base_url: http://192.168.200.11:8731/v1
|
||||
api_key_env: null
|
||||
timeout: 60.0
|
||||
temperature: 0.85
|
||||
reasoning: buffer_turn
|
||||
standard:
|
||||
provider: openai_compat
|
||||
model: halogen-qwen3.8-flash-next
|
||||
base_url: http://192.168.200.11:8731/v1
|
||||
api_key_env: null
|
||||
timeout: 40.0
|
||||
temperature: 0.7
|
||||
reasoning: buffer_turn
|
||||
low:
|
||||
provider: openai_compat
|
||||
model: halogen-qwen3.8-flash-next
|
||||
base_url: http://192.168.200.11:8731/v1
|
||||
api_key_env: null
|
||||
timeout: 20.0
|
||||
temperature: 0.4
|
||||
reasoning: buffer_turn
|
||||
routing:
|
||||
dialogue_main: high
|
||||
dialogue_followup: standard
|
||||
proactive_message: high
|
||||
crisis: high
|
||||
life_event: low
|
||||
memory_gist: low
|
||||
fact_extract: low
|
||||
output_guard: low
|
||||
pattern_detect: low
|
||||
filler: none
|
||||
tick: none
|
||||
reach_out: none
|
||||
avatar_drive: none
|
||||
budget:
|
||||
daily_tokens: 40000
|
||||
warn_ratio: 0.7
|
||||
hard_stop_ratio: 0.95
|
||||
daily_requests:
|
||||
dialogue: 10
|
||||
life: 0
|
||||
background: 0
|
||||
semantic: 0
|
||||
total_requests: 10
|
||||
total_tokens: 40000
|
||||
asr:
|
||||
provider: scripted
|
||||
model: qwen3-asr-1.7b
|
||||
language: zh
|
||||
paralinguistic:
|
||||
provider: scripted
|
||||
model: sensevoice-small
|
||||
window_ms: 1500
|
||||
enabled: true
|
||||
tts:
|
||||
provider: silence
|
||||
model: fun-cosyvoice3-0.5b
|
||||
voice_ref: null
|
||||
sample_rate: 16000
|
||||
vad:
|
||||
provider: energy
|
||||
model: silero-v6
|
||||
sample_rate: 16000
|
||||
turn:
|
||||
provider: heuristic
|
||||
silence_min_ms: 150
|
||||
silence_hard_end_ms: 800
|
||||
embedding:
|
||||
provider: openai_compat
|
||||
model: qwen3-embedding-0.6b
|
||||
base_url: null
|
||||
api_key_env: null
|
||||
dim: 1024
|
||||
avatar:
|
||||
route: vrm
|
||||
renderer: three.js
|
||||
lipsync: envelope
|
||||
@@ -0,0 +1,88 @@
|
||||
# HEL-910 一次性真实测试窗口部署配置(2026-10-29,服务器本地文件,不入仓库)
|
||||
# 授权:白栖知主卡 HEL-797 评论 01a18753-8c70-7181-9758-5bab4685ba9f「继续测」,
|
||||
# 批准《HEL-797-交谈修复复测安排.md》。LLM ≤10 请求、≤40000 tokens;嵌入 0
|
||||
# (CYBERGRIL_SEMANTIC=stub);生活/后台/语义 0。失败/取消/重试均计入(发送前预占)。
|
||||
# 窗口结束封账,余额不结转。tiers/routing/asr/tts/vad/turn/embedding/avatar 与
|
||||
# 候选 958c696 的 config/models.yaml 逐字一致(含 HEL-908 reasoning: buffer_turn)。
|
||||
tiers:
|
||||
high:
|
||||
provider: openai_compat
|
||||
model: halogen-qwen3.8-flash-next
|
||||
base_url: http://192.168.200.11:8731/v1
|
||||
api_key_env: null
|
||||
timeout: 60.0
|
||||
temperature: 0.85
|
||||
reasoning: buffer_turn
|
||||
standard:
|
||||
provider: openai_compat
|
||||
model: halogen-qwen3.8-flash-next
|
||||
base_url: http://192.168.200.11:8731/v1
|
||||
api_key_env: null
|
||||
timeout: 40.0
|
||||
temperature: 0.7
|
||||
reasoning: buffer_turn
|
||||
low:
|
||||
provider: openai_compat
|
||||
model: halogen-qwen3.8-flash-next
|
||||
base_url: http://192.168.200.11:8731/v1
|
||||
api_key_env: null
|
||||
timeout: 20.0
|
||||
temperature: 0.4
|
||||
reasoning: buffer_turn
|
||||
routing:
|
||||
dialogue_main: high
|
||||
dialogue_followup: standard
|
||||
proactive_message: high
|
||||
crisis: high
|
||||
life_event: low
|
||||
memory_gist: low
|
||||
fact_extract: low
|
||||
output_guard: low
|
||||
pattern_detect: low
|
||||
filler: none
|
||||
tick: none
|
||||
reach_out: none
|
||||
avatar_drive: none
|
||||
budget:
|
||||
daily_tokens: 0
|
||||
warn_ratio: 0.7
|
||||
hard_stop_ratio: 0.95
|
||||
daily_requests:
|
||||
dialogue: 0
|
||||
life: 0
|
||||
background: 0
|
||||
semantic: 0
|
||||
total_requests: 0
|
||||
total_tokens: 0
|
||||
asr:
|
||||
provider: scripted
|
||||
model: qwen3-asr-1.7b
|
||||
language: zh
|
||||
paralinguistic:
|
||||
provider: scripted
|
||||
model: sensevoice-small
|
||||
window_ms: 1500
|
||||
enabled: true
|
||||
tts:
|
||||
provider: silence
|
||||
model: fun-cosyvoice3-0.5b
|
||||
voice_ref: null
|
||||
sample_rate: 16000
|
||||
vad:
|
||||
provider: energy
|
||||
model: silero-v6
|
||||
sample_rate: 16000
|
||||
turn:
|
||||
provider: heuristic
|
||||
silence_min_ms: 150
|
||||
silence_hard_end_ms: 800
|
||||
embedding:
|
||||
provider: openai_compat
|
||||
model: qwen3-embedding-0.6b
|
||||
base_url: null
|
||||
api_key_env: null
|
||||
dim: 1024
|
||||
avatar:
|
||||
route: vrm
|
||||
renderer: three.js
|
||||
lipsync: envelope
|
||||
@@ -0,0 +1,59 @@
|
||||
// HEL-910 offline feasibility probe (workstation-local, zero network beyond loopback):
|
||||
// does Chromium --use-file-for-fake-audio-capture feed our schedule into getUserMedia,
|
||||
// and does the AudioContext analyser probe see it at 50ms resolution?
|
||||
// Usage: node probe_fake_capture.mjs <chrome> <wav> <outdir>
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
const [chrome, wav, out] = process.argv.slice(2);
|
||||
mkdirSync(out, { recursive: true });
|
||||
const cdpPort = 9711, httpPort = 9712;
|
||||
const page = `<!doctype html><meta charset=utf-8><body><script>
|
||||
window.__log = [];
|
||||
(async () => {
|
||||
try {
|
||||
const s = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } });
|
||||
const ctx = new AudioContext(); await ctx.resume();
|
||||
const an = ctx.createAnalyser(); an.fftSize = 512;
|
||||
ctx.createMediaStreamSource(s).connect(an);
|
||||
const buf = new Uint8Array(an.fftSize);
|
||||
const t0 = performance.now();
|
||||
window.__timer = setInterval(() => {
|
||||
an.getByteTimeDomainData(buf);
|
||||
let acc = 0; for (const v of buf) { const d = (v - 128) / 128; acc += d * d; }
|
||||
window.__log.push([Math.round(performance.now() - t0), Math.round(Math.sqrt(acc / buf.length) * 100000) / 100000]);
|
||||
}, 50);
|
||||
window.__ok = true;
|
||||
} catch (e) { window.__ok = false; window.__err = String(e); }
|
||||
})();
|
||||
</script></body>`;
|
||||
writeFileSync(join(out, 'probe.html'), page);
|
||||
const server = spawn('python3', ['-m', 'http.server', String(httpPort), '--bind', '127.0.0.1', '--directory', out], { stdio: 'ignore' });
|
||||
const profile = join(tmpdir(), `hel910-probe-${Date.now()}`);
|
||||
const browser = spawn(chrome, [
|
||||
'--headless=new', `--remote-debugging-port=${cdpPort}`, `--user-data-dir=${profile}`, '--no-first-run',
|
||||
'--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream',
|
||||
`--use-file-for-fake-audio-capture=${wav}`,
|
||||
'--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` } });
|
||||
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 id = 0; const waiting = new Map();
|
||||
ws.addEventListener('message', ({ data }) => { const m = JSON.parse(data); if (m.id && waiting.has(m.id)) { const { ok } = waiting.get(m.id); waiting.delete(m.id); ok(m.result); } });
|
||||
const cdp = (method, params = {}) => new Promise(ok => { const n = ++id; waiting.set(n, { ok }); ws.send(JSON.stringify({ id: n, method, params })); });
|
||||
await cdp('Page.navigate', { url: `http://127.0.0.1:${httpPort}/probe.html` });
|
||||
await sleep(12000);
|
||||
const res = await cdp('Runtime.evaluate', { expression: 'JSON.stringify({ok: window.__ok, err: window.__err, samples: window.__log.length, log: window.__log})', returnByValue: true });
|
||||
writeFileSync(join(out, 'probe-result.json'), res.result.value);
|
||||
const parsed = JSON.parse(res.result.value);
|
||||
const speaking = parsed.log.filter(([, e]) => e > 0.02);
|
||||
console.log('gum ok:', parsed.ok, parsed.err || '', '| samples:', parsed.samples);
|
||||
console.log('speaking windows (>0.02 rms):', speaking.length);
|
||||
console.log('first/last speaking ms:', speaking[0]?.[0], speaking[speaking.length - 1]?.[0]);
|
||||
console.log('max rms:', Math.max(...parsed.log.map(([, e]) => e)));
|
||||
browser.kill(); server.kill();
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
# HEL-910:窗口前/后状态快照(只读)
|
||||
# 用法: snapshot.sh pre|post
|
||||
set -u
|
||||
BASE=/opt/cybergril-hel910
|
||||
OUT=$BASE/snapshots/$1-$(date -u +%H%M%S).txt
|
||||
{
|
||||
echo "== HEL-910 $1 snapshot $(date -u +%FT%TZ) =="
|
||||
echo "-- ports (83xx/80xx/98xx/788x/10095) --"
|
||||
ss -ltnp | grep -E ':(8[03][0-9]{2}|98[0-9]{2}|788[0-9]|10095) ' || echo none
|
||||
echo "-- our pids --"
|
||||
for f in api bridge worker tts9880; do
|
||||
p=$BASE/logs/$f.pid
|
||||
if [ -f "$p" ]; then P=$(cat "$p"); if kill -0 "$P" 2>/dev/null; then echo "$f pid $P alive: $(tr '\0' ' ' < /proc/$P/cmdline | cut -c1-120)"; else echo "$f pid $P dead"; fi; else echo "$f no pidfile"; fi
|
||||
done
|
||||
echo "-- livekit rooms --"
|
||||
curl -s --max-time 5 -H 'Authorization: Bearer skip' http://127.0.0.1:7880/twirp/livekit.RoomService/ListRooms -X POST -H 'Content-Type: application/json' -d '{}' 2>/dev/null | head -c 300 || true
|
||||
echo
|
||||
echo "-- voices.json hash + builtin count --"
|
||||
sha256sum /opt/voice-agent/cosyvoice/voices.json
|
||||
python3 - <<'EOF'
|
||||
import json
|
||||
try:
|
||||
d = json.load(open('/opt/voice-agent/cosyvoice/voices.json'))
|
||||
ids = list(d.keys()) if isinstance(d, dict) else [x.get('id') for x in d]
|
||||
print('entries:', len(ids), 'ids:', ids, 'cg- entries:', sum(1 for i in ids if str(i).startswith('cg-')))
|
||||
except Exception as e:
|
||||
print('voices.json read error:', e)
|
||||
EOF
|
||||
echo "-- gpu --"
|
||||
nvidia-smi --query-gpu=memory.used,memory.total --format=csv,noheader
|
||||
echo "-- 8300/8310/8320/8350 untouched check --"
|
||||
ss -ltn | grep -E ':(8300|8310|8320|8350) ' || echo 'WARN: expected demo ports missing'
|
||||
echo "-- tts.log size --"
|
||||
stat -c '%s bytes %y' /opt/voice-agent/cosyvoice/tts.log 2>/dev/null || echo no-log
|
||||
} > "$OUT" 2>&1
|
||||
cat "$OUT"
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env bash
|
||||
# HEL-910 测试窗口:共享 CosyVoice TTS 9880 临时恢复/停回(按快照;精确 PID,禁 fuser -k)
|
||||
# 用法: bash tts_ctl.sh start|stop|status|snapshot
|
||||
set -u
|
||||
BASE=/opt/cybergril-hel910
|
||||
PIDF=$BASE/logs/tts9880.pid
|
||||
SNAP=$BASE/snapshots/tts9880-before.txt
|
||||
CC=/opt/voice-agent/cosyvoice
|
||||
|
||||
case "${1:-}" in
|
||||
status)
|
||||
if [ -f "$PIDF" ]; then P=$(cat "$PIDF"); kill -0 "$P" 2>/dev/null && echo "running pid $P (ours)" || echo "pid $P not alive"; else echo "not started by us"; fi
|
||||
curl -s --max-time 3 http://127.0.0.1:9880/health && echo " <- health" || echo "health not answering"
|
||||
exit 0 ;;
|
||||
snapshot)
|
||||
mkdir -p "$BASE/snapshots"
|
||||
{ echo "ts=$(date -u +%FT%TZ)"; if curl -s --max-time 3 http://127.0.0.1:9880/health >/dev/null 2>&1; then echo "was=up"; else echo "was=down"; fi; ss -ltnp 2>/dev/null | grep ':9880 ' || echo "port9880=free"; } > "$SNAP"
|
||||
cat "$SNAP" ;;
|
||||
stop)
|
||||
if [ -f "$PIDF" ]; then
|
||||
P=$(cat "$PIDF")
|
||||
kill "$P" 2>/dev/null; sleep 5
|
||||
kill -0 "$P" 2>/dev/null && kill -9 "$P" 2>/dev/null
|
||||
rm -f "$PIDF"
|
||||
echo "tts stopped (pid $P)"
|
||||
else
|
||||
echo "not ours to stop (no pid file)"
|
||||
fi
|
||||
curl -s --max-time 3 http://127.0.0.1:9880/health >/dev/null 2>&1 && echo "WARN: 9880 still answering" || echo "9880 down" ;;
|
||||
esac
|
||||
|
||||
# start (fallthrough)
|
||||
if curl -s --max-time 3 http://127.0.0.1:9880/health >/dev/null 2>&1; then
|
||||
echo "9880 already up — NOT ours, not touching"; exit 0
|
||||
fi
|
||||
if ss -ltn 2>/dev/null | grep -q ':9880 '; then echo "port 9880 occupied by non-healthy process — abort"; exit 1; fi
|
||||
cd "$CC"
|
||||
nohup "$CC/venv/bin/python" server.py >> "$CC/tts.log" 2>&1 &
|
||||
echo $! > "$PIDF"
|
||||
echo "tts starting (pid $(cat $PIDF)) — model load takes up to ~120s"
|
||||
for i in $(seq 1 60); do
|
||||
sleep 2
|
||||
if curl -s --max-time 3 http://127.0.0.1:9880/health 2>/dev/null | grep -q '"ok"[[:space:]]*:[[:space:]]*true'; then
|
||||
echo "OK: tts healthy after ~$((i*2))s"; exit 0
|
||||
fi
|
||||
kill -0 "$(cat $PIDF)" 2>/dev/null || { echo "FAIL: tts process died"; tail -10 "$CC/tts.log"; exit 1; }
|
||||
done
|
||||
echo "FAIL: tts not healthy in 120s"; tail -10 "$CC/tts.log"; exit 1
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
# HEL-910:用量账快查(LLM 请求/tokens、TTS 段数、ASR 账本)——触线即停的现场读数
|
||||
set -u
|
||||
BASE=/opt/cybergril-hel910
|
||||
echo "== budget tables ($(date -u +%FT%TZ)) =="
|
||||
python3 - <<'EOF'
|
||||
import json, sqlite3, pathlib
|
||||
db = '/opt/cybergril-hel910/data/companion.db'
|
||||
try:
|
||||
conn = sqlite3.connect(f'file:{db}?mode=ro', uri=True); conn.row_factory = sqlite3.Row
|
||||
for sql, label in [
|
||||
("SELECT key,value FROM budget_total", 'budget_total'),
|
||||
("SELECT day,scene,used FROM token_usage ORDER BY day,scene", 'token_usage'),
|
||||
("SELECT * FROM request_usage", 'request_usage'),
|
||||
]:
|
||||
try:
|
||||
print(label, json.dumps([dict(r) for r in conn.execute(sql)], ensure_ascii=False))
|
||||
except Exception as e:
|
||||
print(label, 'ERR', e)
|
||||
conn.close()
|
||||
except Exception as e:
|
||||
print('db ERR', e)
|
||||
p = pathlib.Path('/opt/cybergril-hel910/asr-usage.jsonl')
|
||||
if p.exists():
|
||||
lines = [l for l in p.read_text().splitlines() if l.strip()]
|
||||
print('asr ledger events:', len(lines))
|
||||
else:
|
||||
print('asr ledger: (none)')
|
||||
EOF
|
||||
echo "== tts.log window segments =="
|
||||
T0MARK=$BASE/snapshots/tts-log-start-byte
|
||||
if [ -f "$T0MARK" ]; then
|
||||
START=$(cat "$T0MARK")
|
||||
else
|
||||
START=0
|
||||
fi
|
||||
tail -c +$((START + 1)) /opt/voice-agent/cosyvoice/tts.log 2>/dev/null | grep -c "first chunk" || true
|
||||
echo "(syntheses reaching first chunk since window start; cap 20)"
|
||||
@@ -0,0 +1,15 @@
|
||||
# HEL-910 一次性真实测试窗口语音配置(2026-10-29,服务器本地,不入仓库)
|
||||
# livekit_url 走独立 8363 TLS 桥(wss),livekit_internal 保持本机明文 7880。
|
||||
# 与 HEL-907 布局一致,仅状态/会话文件指到 /opt/cybergril-hel910。
|
||||
livekit_url: wss://192.168.200.12:8363
|
||||
livekit_internal: http://127.0.0.1:7880
|
||||
api_key: devkey
|
||||
api_secret: voiceagent-local-secret-2026
|
||||
agent_name: cybergril-voice-agent
|
||||
tts_health_url: http://127.0.0.1:9880/health
|
||||
panel_url: https://127.0.0.1:8090
|
||||
tts_url: http://127.0.0.1:9880
|
||||
registry_file: /opt/voice-agent/cosyvoice/voices.json
|
||||
worker_state_file: /opt/cybergril-hel910/worker/voice_state_cybergril.json
|
||||
token_ttl_seconds: 300
|
||||
session_ttl_seconds: 900
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# HEL-910 窗口墙钟看门狗:到点强制收尾。用法: watchdog.sh <deadline_epoch_seconds>
|
||||
set -u
|
||||
BASE=/opt/cybergril-hel910
|
||||
LOG=$BASE/logs/watchdog.log
|
||||
DL="${1:?deadline epoch seconds required}"
|
||||
echo "[$(date -u +%FT%TZ)] watchdog start, deadline $(date -u -d @$DL +%FT%TZ) (pid $$)" >> "$LOG"
|
||||
while [ "$(date +%s)" -lt "$DL" ]; do sleep 10; done
|
||||
echo "[$(date -u +%FT%TZ)] DEADLINE REACHED — force end" >> "$LOG"
|
||||
bash $BASE/ctl/force_end.sh
|
||||
echo "[$(date -u +%FT%TZ)] watchdog done" >> "$LOG"
|
||||
@@ -0,0 +1,10 @@
|
||||
# HEL-910 测试窗口 worker 配置(2026-10-29,600 权限,不入仓库)
|
||||
CYBERGRIL_API_BASE=http://127.0.0.1:8360
|
||||
CYBERGRIL_AGENT_NAME=cybergril-voice-agent
|
||||
LIVEKIT_URL=ws://127.0.0.1:7880
|
||||
LIVEKIT_API_KEY=devkey
|
||||
LIVEKIT_API_SECRET=voiceagent-local-secret-2026
|
||||
CYBERGRIL_WORKER_HEALTH_PORT=8082
|
||||
CYBERGRIL_VOICE_STATE=/opt/cybergril-hel910/worker/voice_state_cybergril.json
|
||||
# ASR 用量账本独立(HEL-907/879 目录只读)
|
||||
CYBERGRIL_ASR_USAGE_LEDGER=/opt/cybergril-hel910/asr-usage.jsonl
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env bash
|
||||
# HEL-910 测试窗口:专属语音 worker(只按 PID 句柄停止;ASR 布防在 etc/asr-arm.env)
|
||||
set -u
|
||||
BASE=/opt/cybergril-hel910
|
||||
LOG=$BASE/logs/worker.log
|
||||
PIDF=$BASE/logs/worker.pid
|
||||
VENV=/opt/voice-agent/agent/venv
|
||||
|
||||
stop() {
|
||||
if [ -f "$PIDF" ]; then
|
||||
P=$(cat "$PIDF")
|
||||
if [ "$P" != "$$" ] && kill -0 "$P" 2>/dev/null; then kill "$P"; sleep 3; fi
|
||||
if [ "$P" != "$$" ] && kill -0 "$P" 2>/dev/null; then kill -9 "$P"; fi
|
||||
rm -f "$PIDF"
|
||||
echo "worker stopped (pid $P)"
|
||||
else
|
||||
echo "no pid file; nothing stopped"
|
||||
fi
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
stop) stop; exit 0 ;;
|
||||
status)
|
||||
if [ -f "$PIDF" ]; then P=$(cat "$PIDF"); kill -0 "$P" 2>/dev/null && echo "running pid $P" || echo "pid $P not alive"; fi
|
||||
curl -s --max-time 3 "http://127.0.0.1:8082/" && echo " <- health" || echo "health port not answering"
|
||||
exit 0 ;;
|
||||
esac
|
||||
|
||||
cd "$BASE/worker"
|
||||
set -a
|
||||
source "$BASE/worker/.env"
|
||||
source "$BASE/etc/asr-arm.env"
|
||||
set +a
|
||||
PYTHONPATH="$BASE/current/src" nohup "$VENV/bin/python" -m cybergril.voice.worker start > "$LOG" 2>&1 &
|
||||
echo $! > "$PIDF"
|
||||
echo "worker starting (pid $(cat $PIDF)) ASR window=$(grep -o 'hel910-20261029-a' $BASE/etc/asr-arm.env | head -1)"
|
||||
sleep 18
|
||||
grep -m1 "registered worker" "$LOG" >/dev/null && echo "OK: worker registered" \
|
||||
|| { echo "FAIL:"; tail -8 "$LOG"; exit 1; }
|
||||
Reference in New Issue
Block a user