HEL-911: fix AgentHandoff/shutdown seams, attribute & fix the 3.66s pre-generation wait

- worker _on_item: filter conversation_item_added by the real 1.8.8 item
  discriminator (ChatMessage | AgentHandoff | _TypeDiscriminator); only
  assistant str-part body feeds the echo filter (HEL-910 AttributeError)
- bind_interrupt_channel unload: async (JobContext shutdown callbacks are
  awaited), idempotent, disconnect-safe; interrupt/receipt/budget paths
  untouched (HEL-910 TypeError await None)
- TURN_HANDLING: explicit turn_detection=None — 1.8.8 silently installs an
  English EOU TurnDetector whose unlikely verdicts on Chinese finals push
  endpointing to max_delay=6.0 (measured 3.667/3.654s HEL-910 call2; offline
  A/B on the real SDK: baseline 3.704s vs fixed 0.004s). Endpointing
  0.8/6.0 kept verbatim; no VAD/buffer_turn/semantic change
- scripts/gen_hel911_wait_repro.py: offline reproduction harness (real
  AgentSession + real silero VAD + HEL-910 wav and measured timings)
- tests: +3 real-SDK checks (11/11 on .12 agent venv; prior 8 regressions
  kept, unload call sites await the new protocol)
- hel910_call1.mjs reliability: segmented probe/recorder dumps to disk,
  timing-A trigger requires the server-committed voice turn row (not a
  we-sent-it proxy); node --check only, no real run
- window-record.md §9: appended factual corrections (companion 9 not 18,
  turn_start +6.099 not +4.10, assistant_final is the playout/receipt gate,
  post-window ListRooms token failure is not empty-room evidence); original
  record untouched
- docs/rework/hel911/summary.md + handoff-HEL-911.json; requirement checks
  pass vs origin/main and 407fc81

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
施工员2号
2026-10-29 21:25:25 +08:00
co-authored by multica-agent
parent 407fc8158c
commit 4a38106eef
7 changed files with 868 additions and 24 deletions
+46
View File
@@ -0,0 +1,46 @@
{
"baseline_version": "1.12",
"read_commit": "407fc8158ce392e20ee51c05420c8b74aa545a92",
"task": "HEL-911:修好 HEL-910 实证的两个 livekit-agents 1.8.8 SDK 接缝错误(worker _on_item 对 AgentHandoff 取 role 的 AttributeError;add_shutdown_callback 对同步卸载回调 await None 的 TypeError),并用已有原始证据+实际 SDK 源码+离线复现查清首声 ~9.5s 等待的分段:识别终稿→生成开始的 3.66s 系 1.8.8 默认补入的英文 EOU TurnDetector 对中文终稿的 unlikely 判定把 endpointing 顶到 max_delay=6.0,显式 turn_detection=None 修复(离线 A/B 3.704s→0.004s);同时纠正 HEL-910 交付说明四处事实错误并追加纠偏记录、为下次测量修工具可靠性(分段落盘+服务端活动门控,仅离线验证)。全程真实 cap=0:零 LLM/ASR/TTS/嵌入/登记/试听调用、不建房不开窗不恢复服务,仅只读复用 .12 agent venv 实物 SDK 与既有 wav 做离线证明。",
"requirement_ids": [
"CG-006",
"CG-010",
"CG-013",
"CG-014",
"CG-015",
"CG-016",
"CG-018",
"CG-019",
"CG-020",
"CG-021",
"AM-001",
"GOV-001",
"GOV-002",
"GOV-003",
"GOV-004",
"GOV-005",
"GOV-006",
"DEL-001"
],
"deliverable": "src/cybergril/voice/worker.py:_on_item 按 1.8.8 ConversationItemAddedEvent.item 判别字段过滤(仅 type==message 且 role==assistant 的 str 部件正文进回声过滤);bind_interrupt_channel 卸载改协程(SDK 关停回调一律被 await)、幂等、断连不抛,interrupt(force=True)/回执/预算路径不动;TURN_HANDLING 显式 turn_detection=None(endpointing 0.8/6.0 逐字保留,不降 VAD 阈值、不动 buffer_turn)。scripts/gen_hel911_wait_repro.py:真 SDK+真 silero VAD+实测时间轴的离线复现(BASELINE 3.704s 复现实测 3.667/3.654s,修复态 0.004s)。tests/test_sdk_livekit_hel908.py +3 项真 SDK 检查(共 11,.12 agent venv 11/11;既有 8 项回归全保持,unload 调用点随协议改 await)。docs/rework/hel910/window-record.md §9 追加纠偏记录(原文未回改);docs/rework/hel910/tools/hel910_call1.mjs 可靠性修正(探针每 5s 分段落盘 call1-probe-live.jsonl+录音分片即存,防超时杀进程丢证;时机A 触发改为服务端已把语音轮落成 chat 行+生成中相位双条件,不再以页面相位/己方发送为 API 已激活代理;node --check 通过)。docs/rework/hel911/summary.md 完整分段归因与验证记录。产品测试套 .12 规范环境 480 passed/11 skipped/2 failed(两个 test_r3 预先存在与 HEL-908 记录一致);本地 py3.10 与基准 407fc81 干树失败集合完全相同(环境差异非本卡引入)。",
"acceptance": [
"真 SDK(.12 /opt/voice-agent/agent/venv livekit-agents 1.8.8)驱动:AgentHandoff/_TypeDiscriminator/user 消息不触发崩溃且不污染回声过滤,assistant 混合 content 只取 str 正文;真 JobContext.add_shutdown_callback 包装协议下协程卸载通过、旧同步形状经同一包装复现生产 TypeError(反向证据)、重复 await 幂等、卸载后监听真摘除;TURN_HANDLING 下 _turn_detection 为 None 且默认探测器存在性前置断言",
"等待链离线复现(复用 HEL-910 实际回放 wav、实测时延脚本化):BASELINE 终稿+2.443→llm.chat+6.142(3.699s,对上实测 3.667/3.654),修复态 +2.439→+2.444(0.005s);VAD 端点 ~0.7s、FunASR 链+0.6s 去抖 2.43s、服务端整轮 ~1.4s、TTS 首包 1.614s 各段归因落在源码行与实测日志",
"既有回归保持:SDK harness 11/11(文字取消不重试/force 停声/通道校验/未启动存活等);产品套 .12 规范环境 480/2 预存失败与基准一致;web 未动未重建",
"纠偏记录入 window-record.md §9:companion 9 条非 18、生成起点 +6.099s 非 +4.10、assistant_final 是播放收尾/回执门非首次全文生成/落库、post-window.txt ListRooms 为 invalid authorization token 不能证明空房(总管独立核实空房成立);原快照/录音/日志一字未改",
"用量:真实 cap=0 全程保持——零模型/识别/合成/嵌入/登记/试听调用、零建房、零窗口、未恢复 9880/8090 或任何本窗服务、未访问 4080、未改绑定;.12 上仅只读使用 agent venv 与既有 wav,临时副本 /tmp/hel911 已清"
],
"deferred": [
"修复后首声真实总时延(离线推算 9.5→约 5.9s,不承诺):需下轮真实工程窗口复测(工具门控与分段落盘已备好)",
"FunASR 适配器 0.6s 去抖与 2pass 离线纠错往返是否可再压:识别链参数,本卡不动语义,与真实复测同窗评估",
"真实用户麦克风打断时延/可闻旧声回放打断正面样本/生成中文字取消正面样本:两轮窗口均未取得,需按新门控重试",
"真实端点带 </think> 形状分离(离线证据 HEL-909);首声是否经常>5s 需多样本",
"真机/手机麦克风、Safari(D3 用户动作);R1–R7 完整功能继续主卡承接,不宣布整产品完成"
],
"requirement_changes": [],
"verification": [
"python3 scripts/check_requirements.py --base-ref origin/main 与 --base-ref 407fc81,均带 --handoff docs/requirements/handoff-HEL-911.json 通过(结构检查,不代替原话核对与体验验收)",
"定向验证:tests/test_sdk_livekit_hel908.py --standalone 于 .12 agent venv 11/11;scripts/gen_hel911_wait_repro.py BASELINE/FIXED 两模式;产品套 .12 .venv311 480 passed/2 预存失败;hel910_call1.mjs node --check",
"未验证(如实):修复后真实通话首声数字、真实麦克风、手机/真机、思考带 closer 真实端点形状——见 deferred,不冒充"
]
}
+48 -7
View File
@@ -8,9 +8,17 @@
// 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
// - HEL-911 reliability fixes (offline-verified only, no re-run):
// * probe data is drained to disk in segments (call1-probe-live.jsonl + rec-part-*.webm)
// every few seconds, so a driver timeout kill can no longer lose the raw evidence
// (HEL-910 defect: first call's probe JSON/webm died with the browser);
// * the timing-A trigger requires SERVER-side turn activity (the user's voice utterance
// committed as a chat row) plus old voice actually audible where applicable — never
// "we sent something" as a proxy for "the API is working on it" (HEL-910: turn_start
// is emitted when the adapter opens the stream, which says nothing about server state).
// Usage: node hel910_call1.mjs <chrome> <fakeWav> <outDir> <baseURL>
import { spawn } from 'node:child_process';
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdirSync, writeFileSync, appendFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
@@ -50,7 +58,11 @@ const INIT = `(() => {
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; };
const chunks = []; mr.ondataavailable = ev => { chunks.push(ev.data); cg.rec.bytes += ev.data.size;
// HEL-911: also hand each chunk to the driver as base64 the moment it
// exists, so audio evidence survives a driver timeout kill.
ev.data.arrayBuffer().then(buf => { const b = new Uint8Array(buf); let s = ''; for (let i = 0; i < b.length; i += 32768) s += String.fromCharCode(...b.subarray(i, i + 32768)); (cg.rec.parts = cg.rec.parts || []).push(s); }).catch(() => {});
};
mr.onstop = () => { cg.rec.chunks = chunks; };
mr.start(1000); cg.rec.started = pnow(); cg.rec.mr = mr;
} catch (e) { cg.errs.push('rec:' + e); }
@@ -164,6 +176,24 @@ 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}`); };
// HEL-911: segmented evidence drain — every 5s pull ONLY the new probe slices and
// append them as one JSONL line, and drain recorder chunks to rec-part-<n>.webm.
// A timeout kill now loses at most one 5s segment instead of the whole probe
// (the HEL-910 first-call loss mode).
const livePath = join(out, 'call1-probe-live.jsonl');
let drained = { energy: 0, muted: 0, phase: 0, heard: 0, chat: 0, net: 0 };
let recPart = 0;
const drainSegments = async () => {
try {
const s = await js(`(() => { const cg = window.__cg; const parts = (cg.rec.parts || []).splice(0); return JSON.stringify({ anchor: cg.anchor, marks: cg.marks, errs: cg.errs, slices: { energy: cg.energy.slice(${drained.energy}), muted: cg.muted.slice(${drained.muted}), phase: cg.phase.slice(${drained.phase}), heard: cg.heard.slice(${drained.heard}), chat: cg.chat.slice(${drained.chat}), net: cg.net.slice(${drained.net}) }, counts: { energy: cg.energy.length, muted: cg.muted.length, phase: cg.phase.length, heard: cg.heard.length, chat: cg.chat.length, net: cg.net.length }, parts }); })()`);
const d = JSON.parse(s);
for (const p of d.parts || []) writeFileSync(join(out, `rec-part-${String(++recPart).padStart(4, '0')}.webm`), Buffer.from(p, 'base64'));
appendFileSync(livePath, JSON.stringify({ wall: Date.now(), ...d, parts: undefined }) + '\n');
drained = { energy: d.counts.energy, muted: d.counts.muted, phase: d.counts.phase, heard: d.counts.heard, chat: d.counts.chat, net: d.counts.net };
} catch (e) { /* page mid-navigation etc. — next tick retries */ }
};
const segmentTimer = setInterval(() => { drainSegments().catch(() => {}); }, 5000);
await cdp('Page.addScriptToEvaluateOnNewDocument', { source: INIT });
await cdp('Page.enable'); await cdp('Network.enable');
@@ -222,18 +252,27 @@ await until(async () => { const e = await energyRecent(16); return e.length && e
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));
// U2 @60-73.3s: prefill T2; HEL-911 trigger = the U2 VOICE turn is committed
// server-side (its user row appears in the chat DOM — the server only writes that
// row once it has the turn), NOT page phase alone and NOT any "we saw/sent X"
// proxy. The thinking phase is still required (generation in flight for timing A),
// but the server-activity row is what proves the API is actually working this turn.
await until(async () => (await js(`window.__cg.heard.some(h => h[1] === 'final' && (h[2].includes('取经') || h[2].includes('老庄') || h[2].includes('俺老猪'))) || window.__cg.chat.some(c => c.role === 'user' && (c.text.includes('取经') || c.text.includes('俺老猪')))`)), 90000, 200).then(v => note('U2 recognized/committed: ' + !!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);
const t2fired = await until(async () => {
const ph = await phaseNow();
if (ph !== 'thinking' && ph !== 'speaking') return false;
// server actually holds the U2 voice turn: its user row is in the chat DOM
return await js(`window.__cg.chat.some(c => c.role === 'user' && (c.text.includes('取经') || c.text.includes('俺老猪')))`);
}, 45000, 100);
if (t2fired) {
await js(`window.__mark('T2_thinking_seen')`);
await js(`window.__mark('T2_server_active_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');
note('T2 NOT fired: server-committed U2 turn + thinking phase not both observed in time');
}
await sleep(1500);
await shot('06-after-T2');
@@ -261,6 +300,8 @@ await finish('done');
async function finish(status) {
R.status = status;
clearInterval(segmentTimer);
await drainSegments().catch(() => {}); // last segment before the full dump
try {
await js(`(() => { try { window.__cg.rec.mr && window.__cg.rec.mr.state !== 'inactive' && window.__cg.rec.mr.stop(); } catch (e) {} })()`);
await sleep(800);
+11
View File
@@ -83,3 +83,14 @@
- **真实端点带 `</think>` 形状**:未出现,真实分离未复现(离线证据在 HEL-909)。
- 首声等待"经常>5s"与否:需多样本;本轮 1 精确样本 + 1 量级相近。
- 真机/手机麦克风、Safari:未测(D3 用户动作)。
## 9. HEL-911 纠偏记录(2026-10-29 追加;上文原报告原样保留,不回改)
以下按总管独立复算(附件 hel910-independent-check.md)与 HEL-911 离线复现订正本文数字,原始日志/录音/快照未动:
- **§0/§4 的"18 条 companion 行"不准确**:`window/db-final.json` 共 20 条 chat_message = user 11 + **companion 9**。思考隔离结论(零 `<think>` 泄漏)不变,基数以 9 为准。
- **§3 的等待链分段"turn_start +4.10s"不符合 marks**:同钟原始 marks 为 playback_end → user_final **+2.432s** → turn_start **+6.099s** → assistant_interim +7.514s → 首有声帧 ≈+9.51s(frames 第二列是字节数,PCM 样本数需除 2;RMS 阈值 500 复算首声 9.514s,阈值 200 为 9.474s,"约 9.5s"总量成立)→ assistant_final +12.102s。原"生成 3.4s+TTS 0.5s"的相加归因作废,按真实时刻重建见下条与 `docs/rework/hel911/summary.md`。
- **§3 "字幕全文/落库 +12.10s" 的语义错误**:assistant_final 字幕是**播放收尾/回执门**(整段播完且回执合法才发,contract v2),不是首次全文生成、更不是落库时刻。落库是 DB 行 14 ts=+7.511s(与 assistant_interim +7.514s 同刻)。
- **§7 "LiveKit ListRooms 空"的证据引述错误**:`window/post-window.txt` 里 ListRooms 的实际输出是 `invalid authorization token`,不能作为空房证据;总管其后用服务器已有 agent venv 只读加载并独立核实 `room_names=[]`(不打印凭证),空房结论成立但证据来源以此纠偏为准。
- **§6 两个 🟡 已在 HEL-911 修复**:`_on_item` 对 AgentHandoff 取 `role` 的 AttributeError,与 job 关停 `TypeError: object NoneType can't be used in 'await' expression`(同步卸载回调被 SDK await)。
- **§6 首声等待的构成已重新归因**(离线可证部分):user_final→turn_start 的 3.65~3.67s 是 livekit-agents 1.8.8 默认补入的**英文 EOU TurnDetector** 对中文终稿给出"不太像说完"判定、把 endpointing 延迟顶到 max_delay=6.0 所致;显式 `turn_detection: None` 后离线同链路该段降为 ~5ms。VAD 端点本身 ~0.7s、FunASR 离线纠错+适配器 0.6s 去抖共 2.43s、服务端整轮生成 ~1.4s、TTS 首包 1.61s 为主构成。修复已入 worker.py(TURN_HANDLING),**首声总时延下降需真实窗口复测确认,本文不宣称**。
+133
View File
@@ -0,0 +1,133 @@
# HEL-911 · 修好通话收尾报错并查清开口等待(2026-10-29)
> 起点:`agent/agent/ab943ea62162` @ `407fc81`(含完整 958c696 产品与 HEL-910 证据,
> SHA 已核)。需求基准 v1.12/60 项;关联 CG-006/010/013–016/018–021、AM-001、
> GOV-001–006、DEL-001;本卡无需求变更。全程真实 cap=0:零 LLM/ASR/TTS/嵌入/
> 登记/试听调用,未建任何房间/窗口,未恢复任何本窗服务;仅只读复用 .12
> `/opt/voice-agent/agent/venv`(livekit-agents 1.8.8 实物)与既有 wav 证据做离线证明。
## 1. 两个 SDK 接缝错误的修复(真实 1.8.8 驱动验证)
### 1.1 `conversation_item_added` 的非 ChatMessage 项目崩溃(worker.py `_on_item`)
- **事实**:1.8.8 的 `ConversationItemAddedEvent.item` 是
`ChatMessage | AgentHandoff | _TypeDiscriminator`(`voice/events.py:419`)。会话启动即入
一条 `AgentHandoff`(无 `role`/`content`),旧代码直取 `ev.item.role` 抛
`AttributeError`——HEL-910 两轮通话 worker.log 实录,每通各一次。
- **修复**(src/cybergril/voice/worker.py `_on_item`):按 SDK 判别字段
`item.type == "message"` 过滤,再按 `role == "assistant"` 取**纯 str 部件**正文
(`ChatContent = str | ImageContent | AudioContent | CacheBreakpoint`,
`llm/chat_context.py:459`)。用户消息、AgentHandoff、unknown 项不更新
`agent_recent_text`;正常 assistant 正文继续喂回声过滤,语义不变。
- **验证**:tests/test_sdk_livekit_hel908.py
`test_conversation_item_added_filters_non_message_items`——真 SDK 真 pydantic 模型
驱动:AgentHandoff / `_TypeDiscriminator` / user 消息 / 混合 content 的 assistant
消息四例,前三种不碰状态,第四种只取正文。
### 1.2 shutdown 回调的异步协议(worker.py `bind_interrupt_channel`)
- **事实**:`JobContext.add_shutdown_callback` 把无参回调包成 `await callback()`
(`job.py:633-643`),job 关停逐个 await(`ipc/job_proc_lazy_main.py:493`)。旧的同步
`def unload() -> None` 因此在关停路径抛
`TypeError: object NoneType can't be used in 'await' expression`(HEL-910 实录)。
- **修复**:unload 改为**协程**;幂等(重复 shutdown/多次调用安全);房间未连接/已断连
不抛。`session.interrupt(force=True)`、回执/预算停机路径一字未动。
- **验证**:`test_shutdown_callback_protocol_real_jobcontext_wrapper`——用**真
JobContext.add_shutdown_callback 方法**做包装(仅缺 job 进程管线),按
job_proc_lazy_main 的原样 await 驱动:新协程通过;旧的同步形状经同一包装复现出
生产那条 TypeError(反向证据);重复 await 幂等;卸载后真 rtc.Room 再收
cg.interrupt 消息监听已摘除。既有三项 R2 通道测试同步改为 `await unload()`,
校验/未启动/卸载语义全部保持。
## 2. 9.5 秒等待分段核对(已有证据 + 实际 SDK 源码 + 离线复现)
### 2.1 按真实时刻重建的分段(call2 q1/q2,同钟 marks)
| 分段 | q1 实测 | 构成(已证) |
| --- | --- | --- |
| 回放结束 → ASR 终稿 | +2.432s | silero 端点 ~0.7s(含 min_silence 0.55s)+ FunASR 2pass 离线纠错往返 + **适配器 0.6s 去抖合并**(stt_funasr.py `emit_merged_final`) |
| ASR 终稿 → 生成开始(turn_start) | **+3.667s(q2 +3.654s)** | **本卡查清,见 2.2——默认英文 EOU TurnDetector 把 endpointing 顶到 max_delay=6.0** |
| 生成开始 → 服务端首条 delta | ~1.42s | 服务端整轮缓冲生成(buffer_turn 已知代价,换零思考泄漏;DB 行 14 ts=+7.511 与 assistant_interim +7.514 同刻) |
| 首条 delta → 第一有声帧 | ~2.0s | CosyVoice3 首包实测 1.614s(worker.log:220 `[tts] first audio after 1.614s`)+ 播放管线 ~0.4s |
| (收尾)assistant_final 字幕 | +12.102s | **播放收尾/回执门**,非首次全文生成/落库时刻(纠偏,见 §4) |
### 2.2 user_final → turn_start 的 3.66s:成因与修复(离线 A/B 证实)
- **成因**:livekit-agents 1.8.8 在 `turn_handling` 未显式给 `turn_detection` 键时
**默认构造 `inference.TurnDetector()`**(`voice/agent_session.py:576-579`
`turn_handling.get("turn_detection", inference.TurnDetector())`;自托管回落本地
v1-mini 英文 EOU 模型)。worker 只配了 `endpointing`,于是这个英文模型对**中文**
终稿做端点预测;其"不太像说完"判定走
`audio_recognition.py` `_bounce_eou_task` 的
`end_of_turn_probability < unlikely_threshold → endpointing_delay = max_delay`
路径,把等待顶到 6.0s:
`extra_sleep = 6.0 + 说话结束锚点(≈+0.14) − 终稿时刻(≈+2.45) ≈ 3.69s`——与两轮
实测 3.667/3.654s 对上(`_run_eou_detection(stt)` 内锚点体检打印实录)。
- **离线复现**(scripts/gen_hel911_wait_repro.py,.12 真 SDK + 真 silero VAD +
HEL-910 实际回放 wav 按实测时间脚本化 STT/LLM/TTS,零外呼):
- BASELINE(复刻旧配置,默认 TurnDetector 在):终稿 +2.443 → llm.chat +6.142
(**3.699s**,复现实测 3.667/3.654);VAD 端点 +0.712;首声 +9.18——与生产
9.5s 形状一致。
- 修复后(显式 `turn_detection: None`):终稿 +2.439 → llm.chat +2.444
(**0.005s**);首声 +5.48。
- **修复**(worker.py `TURN_HANDLING`):显式 `"turn_detection": None`。轮次边界回到
本会话自己配置的 VAD endpointing(min 0.8 / max 6.0 原样保留),**不降 VAD 阈值、
不动 buffer_turn、不改模型/网关/认证**;短轮次行为不变(call2"盯着"轮原本就在终稿后
8ms 提交——其终稿晚于 说话结束+0.8s,min_delay 锚点已过)。附带收益:不再预载
v1-mini 本地权重(~244MB/进程)。
- **回归**:`test_turn_handling_disables_default_english_eou_detector` 断言真 SDK 下
默认会装探测器(若 SDK 行为变更该前置断言会失败,提示重新归因)、worker 配置下为
None、endpointing 参数逐字未动。
- **未承诺**:首声总时延 9.5s → 约 5.9s 是离线推算;**需真实窗口复测确认**,本卡
cap=0 未跑真实通话。
### 2.3 分段归因清单(已证 / 已修 / 需真实环境)
- 已证(已有证据+源码+离线复现):2.432s(FunASR 链+去抖)、3.66s(默认英文
TurnDetector)、~1.4s(服务端整轮生成)、TTS 首包 1.614s、VAD 端点 ~0.7s。
- 已修(离线定向验证通过,待真实复测收数字):3.66s 段(TURN_HANDLING)。
- 需真实环境才能判断:修复后首声总时延的真实值;FunASR 离线纠错往返在真实麦克风
下的分布(当前只有工程回放样本);"经常>5s"与否需多样本。
## 3. 修复清单与验证记录
| 变更 | 文件 | 验证 |
| --- | --- | --- |
| `_on_item` 类型过滤 | `src/cybergril/voice/worker.py` | 真 SDK 4 例(§1.1) |
| unload 协程化+幂等 | `src/cybergril/voice/worker.py` | 真 JobContext 包装协议(§1.2) |
| 显式禁用默认 TurnDetector | `src/cybergril/voice/worker.py`(`TURN_HANDLING`) | 离线 A/B + 真会话断言(§2.2) |
| 等待链离线复现工具 | `scripts/gen_hel911_wait_repro.py`(新增) | BASELINE/FIXED 两模式跑通 |
| 测量工具可靠性修正 | `docs/rework/hel910/tools/hel910_call1.mjs` | `node --check` 通过(离线) |
| HEL-910 事实纠偏 | `docs/rework/hel910/window-record.md` §9 追加 | 原文未回改 |
- **真 SDK harness**(.12 agent venv 1.8.8):
`tests/test_sdk_livekit_hel908.py --standalone` **11/11**(既有 8 项回归全保持 +
本卡 3 项新证)。
- **产品测试套**(.12 规范环境 `.venv311` 只读复用):**480 passed / 11 skipped /
2 failed**——两个 `test_r3` 基线/迁移失败与 HEL-908 记录一致(预先存在,前轮已留证)。
本地 py3.10 环境 75/81 通过、6 失败与基准 407fc81 干树完全同集合(环境差异,非本卡
引入)。
- web 未动,未重建界面;ruff/lint 未配置进仓库流程,Python 语法经两环境实测导入通过。
## 4. HEL-910 交付说明纠偏(详见 window-record.md §9)
companion 实为 **9 条**(非 18);生成起点 **+6.099s**(非 +4.10);assistant_final
是**播放收尾/回执门**(非首次全文生成/落库,落库在 +7.511s);post-window.txt 的
ListRooms 实为 `invalid authorization token`,不能证明空房(总管已独立核实空房成立)。
## 5. 测量工具可靠性修正(仅必要项,离线验证,不执行真实窗口)
- **分段落盘**:hel910_call1.mjs 每 5s 把页内探针新增切片追加写
`call1-probe-live.jsonl`、录音分片即产即存 `rec-part-NNNN.webm`——驱动被超时杀掉
最多丢 5s 一段,不再整包丢失(HEL-910 第一通丢证模式)。`node --check` 通过。
- **打断触发条件**:时机A 不再以页面相位/己方发送为"服务端已激活"的代理,改为
**服务端已把 U2 语音轮落成 chat 行**(用户行出现在会话 DOM)+ 生成中相位双条件;
旧"发过 turn_start 即认为 API 已激活"的假设作废。
## 6. 未测 / 承接(如实)
- 修复后首声真实数字、真实麦克风打断时延、可闻旧声中的回放打断正面样本、生成中
文字取消正面样本:需下轮真实工程窗口(门控与分段落盘已备好)。
- FunASR 适配器 0.6s 去抖与 2pass 离线纠错往返是否可再压:属识别链参数,本卡不动
语义,留待与真实复测同窗评估。
- 真实端点带 `</think>` 形状、真机/手机麦克风、Safari、完整 R1–R7:继续主卡承接。
+432
View File
@@ -0,0 +1,432 @@
"""HEL-911 离线等待链复现:真 AgentSession + 真 silero VAD + 脚本化 STT/LLM/TTS.
目的:把 HEL-910 call2 实测的「识别终稿 → 生成开始」3.667s 间隙(q1
+2.432→+6.099、q2 +48.525→+52.179,两轮同为 3.65~3.67s)在完全离线的
真实 SDK 1.8.8 里复现或排除,从而把 9.5s 首声等待的分段归因落到可检验
的事实上。
做法(全部本地计算,零网络,零 LLM/ASR/TTS 外呼):
- 输入:HEL-910 真实回放用过的 /opt/cybergril-hel910/etc/trim/u_bajie.trim.wav
按 100ms 帧、真实时钟节奏推给 session.input.audio(与 hel910_client 的
发布节奏一致),播完继续推真零样本静音帧(对应 asr-usage.jsonl 证实
的连续帧流 ~100.5% 实时);
- STT:脚本化 stt.STT,按实测时间发 INTERIM(语音期间)与 FINAL(回放
结束后 +2.432s,即 FunASR 离线纠错 + 适配器 0.6s 去抖的实测结果),
不设 end_time(与 FunASRSTT 的 SpeechData 形状一致);
- LLM:脚本化 LLM,记录 chat() 调用时刻(= 生产链路里 on_stream_started
→ 字幕 turn_start 的同一时刻),1.415s 后发两条 delta(对应实测
turn_start→assistant_interim 的服务端整轮生成时延);
- TTS:脚本化 ChunkedStream,1.614s 后出首帧(对应实测
[tts] first audio after 1.614s,worker.log:220);
- 会话参数与 worker.py entrypoint 完全一致(真 VAD.load()、
endpointing min 0.8 / max 6.0)。
输出各里程碑相对回放结束(= wav 末帧后第一帧静音的时刻)的秒数,与
HEL-910 实测列对照。本脚本不修改任何服务,只读 wav。
运行(.12 agent venv):
/opt/voice-agent/agent/venv/bin/python scripts/gen_hel911_wait_repro.py
"""
from __future__ import annotations
import asyncio
import sys
import time
import wave
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from livekit import rtc
from livekit.agents import stt, tts, llm as lk_llm
from livekit.agents.llm import ChatContext, LLM, LLMStream, Tool
from livekit.agents.stt import RecognizeStream, SpeechData, SpeechEvent, SpeechEventType
from livekit.agents.tts import AudioEmitter, ChunkedStream
from livekit.agents.types import DEFAULT_API_CONNECT_OPTIONS, APIConnectOptions
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins.silero import VAD
WAV = Path("/opt/cybergril-hel910/etc/trim/u_bajie.trim.wav")
# HEL-910 call2 实测时延(相对回放结束/各起点)
FINAL_AFTER_PLAYBACK_END = 2.432 # user_final(VAD+FunASR 离线+0.6s 去抖)
GEN_AFTER_TURN_START = 1.415 # turn_start -> assistant_interim(服务端整轮)
TTS_FIRST_AUDIO = 1.614 # [tts] first audio after(worker.log:220)
TAIL_SILENCE = 14.0 # 回放结束后继续推的静音时长
def _now() -> float:
return time.perf_counter()
class Timeline:
def __init__(self) -> None:
self.t0: float | None = None
self.playback_end: float | None = None
self.marks: list[tuple[str, float]] = []
def mark(self, name: str) -> None:
self.marks.append((name, _now()))
class ScriptedSTT(stt.STT):
"""按 HEL-910 实测时间发 FINAL 的 STT;不连任何识别服务。"""
def __init__(self, tl: Timeline) -> None:
super().__init__(capabilities=stt.STTCapabilities(streaming=True, interim_results=True))
self._tl = tl
@property
def provider(self) -> str:
return "scripted"
@property
def model(self) -> str:
return "hel910-timeline"
async def _recognize_impl(self, buffer, *, language=None,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
) -> SpeechEvent:
raise NotImplementedError("scripted STT only supports streaming")
def stream(self, *, language=None,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
) -> RecognizeStream:
return ScriptedRecognizeStream(stt=self, conn_options=conn_options, tl=self._tl)
class ScriptedRecognizeStream(RecognizeStream):
def __init__(self, *, stt: ScriptedSTT, conn_options: APIConnectOptions,
tl: Timeline) -> None:
super().__init__(stt=stt, conn_options=conn_options)
self._tl = tl
def _ev(self, ev_type: SpeechEventType, text: str) -> SpeechEvent:
return SpeechEvent(type=ev_type,
alternatives=[SpeechData(language="zh", text=text)])
async def _run(self) -> None:
tl = self._tl
async def schedule_final() -> None:
# 等回放结束锚点(由输入源标记),再按实测延迟发终稿
while tl.playback_end is None:
await asyncio.sleep(0.02)
await asyncio.sleep(FINAL_AFTER_PLAYBACK_END)
tl.mark("stt_final_emitted")
self._event_ch.send_nowait(
self._ev(SpeechEventType.FINAL_TRANSCRIPT,
"师傅,哎,这取经路比高,老庄种地还苦,俺老猪饿的能吞下石龙素"
"包子,猴哥,你筋斗云块,要不先去化个缘"))
final_task = asyncio.create_task(schedule_final())
sent_interim = False
try:
async for ev in self._input_ch:
if ev is None:
break
if isinstance(ev, rtc.AudioFrame) and not sent_interim:
sent_interim = True
self._event_ch.send_nowait(
self._ev(SpeechEventType.INTERIM_TRANSCRIPT, "师傅"))
await asyncio.sleep(0)
finally:
final_task.cancel()
class ProbeLLM(LLM):
def __init__(self, tl: Timeline) -> None:
super().__init__()
self._tl = tl
@property
def provider(self) -> str:
return "probe"
@property
def model(self) -> str:
return "hel911-wait-probe"
def chat(self, *, chat_ctx: ChatContext, tools: list[Tool] | None = None,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS, **_
) -> LLMStream:
self._tl.mark("llm_chat_called") # = 生产链路的 turn_start 时刻
return ProbeLLMStream(llm=self, chat_ctx=chat_ctx, tools=tools or [],
conn_options=conn_options, tl=self._tl)
class ProbeLLMStream(LLMStream):
def __init__(self, *, llm: ProbeLLM, chat_ctx: ChatContext, tools: list[Tool],
conn_options: APIConnectOptions, tl: Timeline) -> None:
super().__init__(llm, chat_ctx=chat_ctx, tools=tools, conn_options=conn_options)
self._tl = tl
async def _run(self) -> None:
from livekit.agents.llm import ChatChunk, ChoiceDelta
await asyncio.sleep(GEN_AFTER_TURN_START)
self._tl.mark("first_delta")
self._event_ch.send_nowait(ChatChunk(
id="hel911-probe",
delta=ChoiceDelta(role="assistant", content="好,小十。去化缘")))
self._event_ch.send_nowait(ChatChunk(
id="hel911-probe", delta=ChoiceDelta(role="assistant", content="")))
self._event_ch.send_nowait(ChatChunk(id="hel911-probe"))
class ProbeTTS(tts.TTS):
def __init__(self, tl: Timeline) -> None:
super().__init__(capabilities=tts.TTSCapabilities(streaming=False),
sample_rate=24000, num_channels=1)
self._tl = tl
@property
def provider(self) -> str:
return "probe"
@property
def model(self) -> str:
return "hel911-wait-probe"
def synthesize(self, text: str, *,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
) -> ChunkedStream:
return ProbeChunkedStream(tts=self, input_text=text,
conn_options=conn_options, tl=self._tl)
class ProbeChunkedStream(ChunkedStream):
def __init__(self, *, tts: ProbeTTS, input_text: str,
conn_options: APIConnectOptions, tl: Timeline) -> None:
super().__init__(tts=tts, input_text=input_text, conn_options=conn_options)
self._tl = tl
async def _run(self, output_emitter: AudioEmitter) -> None:
output_emitter.initialize(request_id="hel911", sample_rate=24000,
num_channels=1, mime_type="audio/pcm")
await asyncio.sleep(TTS_FIRST_AUDIO) # 实测 CosyVoice3 首包
self._tl.mark("tts_first_audio")
# ~1s 的可听音频(20ms 帧),足够走完 playout/回执路径
frame = b"\x10\x00" * 480
for _ in range(50):
output_emitter.push_frame(rtc.AudioFrame(frame, 24000, 1, 480))
await asyncio.sleep(0.02)
output_emitter.flush()
def make_sink(tl: Timeline):
from livekit.agents.voice.io import AudioOutput, AudioOutputCapabilities
class _Sink(AudioOutput):
def __init__(self) -> None:
super().__init__(label="probe-sink",
capabilities=AudioOutputCapabilities(pause=False))
self.first_frame_at: float | None = None
async def capture_frame(self, frame: rtc.AudioFrame) -> None:
if self.first_frame_at is None:
tl.mark("sink_first_frame")
self.first_frame_at = _now()
def flush(self) -> None:
self.on_playback_finished(interrupted=False)
def clear_buffer(self) -> None:
self.on_playback_finished(interrupted=True)
return _Sink()
class MicSource:
"""wav 实时回放 + 尾部连续静音,节奏与 hel910_client._publish_pcm 一致。"""
def __init__(self, tl: Timeline) -> None:
self._tl = tl
def make(self):
tl = self._tl
from livekit.agents.voice.io import AudioInput
with wave.open(str(WAV), "rb") as w:
raw = w.readframes(w.getnframes())
rate = w.getframerate()
class _Source(AudioInput):
def __init__(self) -> None:
super().__init__(label="hel911-mic")
self._i = 0
self._phase = "wav"
async def __anext__(self) -> rtc.AudioFrame:
step = 1600 * 2 # 100ms @16k,同 hel910_client
if self._phase == "wav":
chunk = raw[self._i:self._i + step]
if tl.t0 is None:
tl.t0 = _now()
if len(chunk) < step:
chunk = chunk + b"\x00" * (step - len(chunk))
self._i += step
if self._i >= len(raw):
self._phase = "silence"
tl.playback_end = _now()
tl.mark("playback_end")
await asyncio.sleep(0.1)
return rtc.AudioFrame(chunk, rate, 1, 1600)
# 静音段:真实时钟节奏(帧流连续,asr-usage 证实)
await asyncio.sleep(0.1)
return rtc.AudioFrame(b"\x00" * step, rate, 1, 1600)
return _Source()
async def main() -> None:
if not WAV.exists():
raise SystemExit(f"wav not found: {WAV}")
import logging
logging.basicConfig(level=logging.INFO) # eot prediction 走 debug 时再降
logging.getLogger("livekit.agents.voice.audio_recognition").setLevel(logging.DEBUG)
import os
# 默认复刻生产接线(worker.TURN_HANDLING,已显式 turn_detection=None);
# HEL911_BASELINE=1 复现缺陷态:1.8.8 对缺省键默认补英文 TurnDetector
baseline = os.environ.get("HEL911_BASELINE") == "1"
from cybergril.voice.worker import TURN_HANDLING as WORKER_TURN_HANDLING
turn_handling = (
{k: v for k, v in WORKER_TURN_HANDLING.items() if k != "turn_detection"}
if baseline else dict(WORKER_TURN_HANDLING)
)
tl = Timeline()
session = AgentSession(
stt=ScriptedSTT(tl),
llm=ProbeLLM(tl),
tts=ProbeTTS(tl),
vad=VAD.load(),
turn_handling=turn_handling,
)
session.input.audio = MicSource(tl).make() # type: ignore[assignment]
session.output.audio = make_sink(tl) # type: ignore[assignment]
@session.on("user_state_changed")
def _ustate(ev):
tl.mark(f"user_state_{getattr(ev, 'new_state', '?')}")
@session.on("agent_state_changed")
def _astate(ev):
tl.mark(f"agent_state_{getattr(ev, 'new_state', '?')}")
@session.on("user_input_transcribed")
def _tr(ev):
if ev.is_final:
tl.mark("sdk_user_final")
await session.start(agent=Agent(instructions="probe"))
tl.mark("session_started")
# 定位 FINAL→llm.chat 间隙:给真 SDK 的提交/调度内部打点(只读包装,不改行为)
from livekit.agents.voice import agent_activity
activity = session._activity
_orig_eou = activity.on_end_of_turn
def _logged_eou(info):
committed = _orig_eou(info)
tl.mark(f"on_end_of_turn(committed={committed})")
return committed
activity.on_end_of_turn = _logged_eou # type: ignore[method-assign]
_orig_gen = activity._generate_reply
def _logged_gen(**kwargs):
handle = _orig_gen(**kwargs)
tl.mark("_generate_reply")
return handle
activity._generate_reply = _logged_gen # type: ignore[method-assign]
_orig_sched = activity._schedule_speech
def _logged_sched(speech, priority, force=False):
tl.mark("_schedule_speech")
return _orig_sched(speech, priority, force=force)
activity._schedule_speech = _logged_sched # type: ignore[method-assign]
_orig_run_eou = type(activity._audio_recognition)._run_eou_detection
def _logged_run_eou(self, chat_ctx, *, trigger, skip_reply=False):
tl.mark(f"_run_eou_detection({trigger})")
# EOU 锚点体检:提交前的 extra_sleep 由这些值决定
lst = self._last_speaking_time
print(f" [eou:{trigger}] speaking={self._speaking} "
f"last_speaking_time={'none' if lst is None else f'{time.time() - lst:+.3f}s ago'} "
f"final_at={'none' if self._last_final_transcript_time is None else f'{time.time() - self._last_final_transcript_time:+.3f}s ago'} "
f"endpointing_min={self._endpointing.min_delay} "
f"turn_detector={type(self._turn_detector).__name__ if self._turn_detector else None} "
f"td_stream={type(self._turn_detector_stream).__name__ if self._turn_detector_stream else None} "
f"mode={self._turn_detection_mode}", flush=True)
return _orig_run_eou(self, chat_ctx, trigger=trigger, skip_reply=skip_reply)
type(activity._audio_recognition)._run_eou_detection = _logged_run_eou
ar = activity._audio_recognition
_orig_span = ar._ensure_eou_wait_span
def _logged_span(user_turn_span, **kwargs):
tl.mark("_ensure_eou_wait_span")
out = _orig_span(user_turn_span, **kwargs)
print(f" [eou-span] args={kwargs}", flush=True)
return out
ar._ensure_eou_wait_span = _logged_span # type: ignore[method-assign]
import livekit.agents.voice.audio_recognition as ar_mod
_orig_metrics = ar_mod._compute_end_of_turn_metrics
def _logged_metrics(**kwargs):
tl.mark("eou_metrics_start")
out = _orig_metrics(**kwargs)
tl.mark("eou_metrics_end")
return out
ar_mod._compute_end_of_turn_metrics = _logged_metrics
_orig_auth = type(activity)._scheduling_task
async def _logged_sched_task(self_inner):
tl.mark("_scheduling_task_start")
await _orig_auth(self_inner)
type(activity)._scheduling_task = _logged_sched_task
# 跑完一轮:回放 13.26s + 尾部静音(覆盖 FINAL→生成→TTS→播放收尾)
await asyncio.sleep(13.26 + TAIL_SILENCE)
await session.aclose()
pe = tl.playback_end
if pe is None:
raise SystemExit("playback never ended?")
print(f"\nwav={WAV.name} marks 相对回放结束(秒):")
print(f"{'mark':28s} {'t-playback_end':>15s}")
for name, at in tl.marks:
print(f"{name:28s} {at - pe:>+15.3f}")
# 与 HEL-910 实测对照
stt_final = next((at for n, at in tl.marks if n == "stt_final_emitted"), None)
chat = next((at for n, at in tl.marks if n == "llm_chat_called"), None)
if stt_final and chat:
gap = chat - stt_final
print(f"\nFINAL->llm.chat 间隙: {gap:+.3f}s "
f"(HEL-910 实测 user_final->turn_start = +3.667s / +3.654s)")
baseline_note = ("BASELINE(默认英文 TurnDetector 在)" if baseline
else "生产 TURN_HANDLING(turn_detection=None)")
print(f"模式: {baseline_note}")
if __name__ == "__main__":
asyncio.run(main())
+43 -14
View File
@@ -200,14 +200,22 @@ def bind_voice_session(session: AgentSession, *, llm: CyberGrillLLM,
@session.on("conversation_item_added")
def _on_item(ev) -> None:
if ev.item.role == "assistant":
texts = [
getattr(p, "text", "") or (p if isinstance(p, str) else "")
for p in (ev.item.content or [])
]
text = "".join(t for t in texts if t).strip()
if text:
stt.agent_recent_text = text
# SDK 1.8.8 的 ConversationItemAddedEvent.item 是
# ChatMessage | AgentHandoff | _TypeDiscriminator(events.py:416-420):
# 会话启动的 AgentHandoff 没有 role/content,直接取 ev.item.role 会抛
# AttributeError(HEL-910 两轮通话日志实录)。按 SDK 的类型判别字段
# 过滤,只认 type=="message" 的 ChatMessage,再按 role=="assistant"
# 取正文;用户消息、非消息项一律不更新 agent_recent_text。
item = ev.item
if getattr(item, "type", None) != "message":
return
if item.role != "assistant":
return
# ChatContent = str | ImageContent | AudioContent | CacheBreakpoint:
# 只有 str 部件是正文(chat_context.py:459-461),其余形状不冒充文本。
text = "".join(p for p in (item.content or []) if isinstance(p, str)).strip()
if text:
stt.agent_recent_text = text
@session.on("agent_state_changed")
def _on_state(ev) -> None:
@@ -220,6 +228,19 @@ web/src/voice 的 hush() 在本地静音反馈之外 publish 它(reliable)
本房间订阅。只复用 LiveKit 自己的数据通道与 session.interrupt,不建第二套
调度引擎。"""
TURN_HANDLING = {
# 停顿稍久才判说完, 合并慢语速碎片(同通用 worker 实测参数)
"endpointing": {"min_delay": 0.8, "max_delay": 6.0},
# HEL-911:livekit-agents 1.8.8 对未显式给 turn_detection 的会话默认
# 构造英文 EOU TurnDetector(agent_session.py:576-579,自托管回落本地
# v1-mini)。它对中文终稿的"不太像说完"判定把 endpointing 延迟顶到
# max_delay=6.0,实测造成识别终稿后 ~3.66s 的额外等待(HEL-910 call2
# 两轮 3.667/3.654s;离线 A/B:默认 3.704s vs 显式 None 0.004s,
# scripts/gen_hel911_wait_repro.py)。显式禁用:轮次边界回到本会话配置
# 的 VAD endpointing 本身,语义不变(不降 VAD 阈值、不动 buffer_turn)。
"turn_detection": None,
}
def bind_interrupt_channel(room, session) -> Callable[[], None]:
"""订阅本房间的 cg.interrupt 打断消息,走 SDK 自己的 programmatic 打断.
@@ -235,7 +256,7 @@ def bind_interrupt_channel(room, session) -> Callable[[], None]:
RuntimeError,HEL-909 evidence B2);失败一律大声留痕,不静默假装
成功。session.interrupt 未启动时抛 RuntimeError 同样留痕返回。
返回卸载函数(JobContext.add_shutdown_callback 注册,会话结束卸载)。
返回卸载协程(JobContext.add_shutdown_callback 注册,会话结束 await).
"""
def on_data(msg) -> None:
if getattr(msg, "topic", None) != INTERRUPT_TOPIC:
@@ -267,8 +288,19 @@ def bind_interrupt_channel(room, session) -> Callable[[], None]:
asyncio.get_running_loop().create_task(_drain(fut))
room.on("data_received", on_data)
unloaded = False
def unload() -> None:
async def unload() -> None:
# SDK 1.8.8 的 shutdown 回调一律被 await(job.py:622-643 把无参回调
# 包成 `await callback()`,ipc/job_proc_lazy_main.py:493 逐个 await):
# 同步返回 None 的旧卸载函数让 job 关停日志抛
# TypeError: object NoneType can't be used in 'await' expression
# (HEL-910 实录)。必须是协程;幂等(重复 shutdown/多次调用安全),
# 未连接/已断连的房间卸载监听不得抛出。
nonlocal unloaded
if unloaded:
return
unloaded = True
with contextlib.suppress(Exception):
room.off("data_received", on_data)
@@ -367,10 +399,7 @@ async def entrypoint(ctx: JobContext) -> None:
llm=llm,
tts=CosyVoiceTTS(default_voice=read_default_voice()),
vad=ctx.proc.userdata["vad"],
turn_handling={
# 停顿稍久才判说完, 合并慢语速碎片(同通用 worker 实测参数)
"endpointing": {"min_delay": 0.8, "max_delay": 6.0},
},
turn_handling=TURN_HANDLING,
)
bind_voice_session(session, llm=llm, ledger=ledger, interim=interim,
bus=bus, stt=stt, receipts=receipts)
+155 -3
View File
@@ -291,7 +291,7 @@ async def test_interrupt_message_stops_pending_playout_after_final():
fresh.interrupt(force=True)
_quiet_await(fresh)
_quiet_await(handle)
unload()
await unload()
async def test_interrupt_channel_validation_and_unload():
@@ -323,7 +323,7 @@ async def test_interrupt_channel_validation_and_unload():
await asyncio.sleep(0.05)
assert bridge.calls == [True] and handle.interrupted
unload()
await unload()
room.emit("data_received", _data_packet("cg.interrupt", b'{"v":1}'))
await asyncio.sleep(0.05)
assert bridge.calls == [True], "the unload callback removed the listener"
@@ -348,7 +348,153 @@ async def test_interrupt_message_survives_session_not_running():
await asyncio.sleep(0.05) # logged, swallowed at the boundary, listener intact
room.emit("data_received", _data_packet("cg.interrupt", b'{"v":1}'))
await asyncio.sleep(0.05)
unload()
await unload()
# ── HEL-911: conversation_item_added item types + async shutdown seam ────────
def _echo_stt_state() -> "SimpleNamespace":
from types import SimpleNamespace
return SimpleNamespace(agent_recent_text="", agent_speaking=False)
async def test_conversation_item_added_filters_non_message_items():
"""The session-start AgentHandoff (real 1.8.8 ConversationItemAddedEvent
payload: ChatMessage | AgentHandoff | _TypeDiscriminator, events.py:419)
crashed the old handler with AttributeError (HEL-910 worker.log, both
calls). Non-message items and user messages must not touch the echo
filter state."""
from livekit.agents.llm.chat_context import AgentHandoff, ChatMessage
from livekit.agents.voice import AgentSession
from livekit.agents.voice.events import ConversationItemAddedEvent, _TypeDiscriminator
from cybergril.voice.worker import bind_voice_session
class _Noop:
def __getattr__(self, name): # any other seam touch fails the test
raise AssertionError(f"unexpected seam use: {name}")
session = AgentSession()
stt = _echo_stt_state()
bind_voice_session(session, llm=_Noop(), ledger=_Noop(), interim=_Noop(),
bus=_Noop(), stt=stt, receipts=_Noop())
# 1. real SDK AgentHandoff (the session-start item that crashed 1.8.8)
session.emit("conversation_item_added",
ConversationItemAddedEvent(item=AgentHandoff(new_agent_id="agent_1")))
assert stt.agent_recent_text == ""
# 2. the SDK's own unknown-item discriminator shape
session.emit("conversation_item_added",
ConversationItemAddedEvent(item=_TypeDiscriminator()))
assert stt.agent_recent_text == ""
# 3. a real user ChatMessage must not feed the assistant echo filter
session.emit("conversation_item_added", ConversationItemAddedEvent(
item=ChatMessage(role="user", content=["用户说的话"])))
assert stt.agent_recent_text == ""
# 4. real assistant ChatMessage with mixed content parts: only the str
# parts are body text (ChatContent = str | ImageContent | AudioContent |
# CacheBreakpoint, chat_context.py:459)
from livekit.agents.llm.chat_context import CacheBreakpoint
session.emit("conversation_item_added", ConversationItemAddedEvent(
item=ChatMessage(role="assistant", content=["好,小十。", CacheBreakpoint()])))
assert stt.agent_recent_text == "好,小十。"
async def test_shutdown_callback_protocol_real_jobcontext_wrapper():
"""The unload seam must satisfy the REAL JobContext.add_shutdown_callback
contract: the SDK wraps a no-arg callback into `await callback()`
(job.py:633-643) and the job runner awaits every callback
(ipc/job_proc_lazy_main.py:493). The old sync `def unload() -> None`
raised TypeError: object NoneType can't be used in 'await' expression
(HEL-910 worker.log). Here the REAL JobContext method does the wrapping
and the runner's exact await pattern drives it — only the job plumbing
around it is absent, so a broken seam reproduces the production error.
"""
import inspect
from livekit import rtc
from livekit.agents import JobContext
from livekit.agents.voice import SpeechHandle
from cybergril.voice.worker import bind_interrupt_channel
handle = SpeechHandle.create(allow_interruptions=True)
class _Bridge:
def interrupt(self, *, force: bool = False):
return handle.interrupt(force=force)
room = rtc.Room()
unload = bind_interrupt_channel(room, _Bridge())
assert inspect.iscoroutinefunction(unload), \
"add_shutdown_callback awaits its callbacks; unload must be async"
# register through the REAL SDK method (it appends the wrapper it will await)
ctx = object.__new__(JobContext) # real method, minimal instance: no job plumbing
ctx._shutdown_callbacks = []
ctx.add_shutdown_callback(unload)
wrapped = ctx._shutdown_callbacks[-1]
# exactly what ipc/job_proc_lazy_main._traced_shutdown_callback does
await wrapped("job shutdown") # must not raise (the old sync seam did)
# the old seam reproduces the production TypeError through the same wrapper
def sync_unload() -> None:
return None
ctx.add_shutdown_callback(sync_unload)
broken = ctx._shutdown_callbacks[-1]
try:
await broken("job shutdown")
raise AssertionError("sync unload should have failed the real await")
except TypeError as exc:
assert "await" in str(exc)
# duplicate shutdown: the runner may only fire callbacks once per job, but
# idempotency must not depend on that
await unload()
await unload()
# subscription really unloaded: a valid interrupt message after unload is a no-op
room.emit("data_received", _data_packet("cg.interrupt", b'{"v":1}'))
await asyncio.sleep(0.05)
assert not handle.interrupted, "listener must be gone after unload"
_quiet_await(handle)
async def test_turn_handling_disables_default_english_eou_detector():
"""HEL-911: livekit-agents 1.8.8 silently installs an English EOU
TurnDetector when turn_handling has no explicit turn_detection key
(agent_session.py:576-579, `turn_handling.get("turn_detection",
inference.TurnDetector())`). Its unlikely-eot verdicts on CHINESE
transcripts push the endpointing delay to max_delay and cost the measured
~3.66s between ASR final and turn_start (HEL-910 call2: 3.667s/3.654s;
offline A/B in scripts/gen_hel911_wait_repro.py: default 3.704s vs
explicit None 0.004s). The worker's TURN_HANDLING must keep the detector
off so the configured VAD endpointing alone decides the turn boundary."""
from livekit.agents import AgentSession
from cybergril.voice.worker import TURN_HANDLING
# the SDK default that bites: same options minus the explicit key
with_default = {k: v for k, v in TURN_HANDLING.items() if k != "turn_detection"}
default_session = AgentSession(turn_handling=with_default)
assert default_session._turn_detection is not None, (
"precondition: 1.8.8 installs a default turn detector — if this fails "
"the SDK changed; re-check the HEL-911 wait attribution"
)
session = AgentSession(turn_handling=TURN_HANDLING)
assert session._turn_detection is None, \
"the worker must not run the English EOU detector on Chinese turns"
assert TURN_HANDLING["endpointing"] == {"min_delay": 0.8, "max_delay": 6.0}, \
"the measured endpointing parameters stay exactly as configured"
# ── standalone runner (agent venv has no pytest) ─────────────────────────────
@@ -371,6 +517,12 @@ async def _standalone() -> int:
test_interrupt_channel_validation_and_unload),
("interrupt_message_survives_session_not_running",
test_interrupt_message_survives_session_not_running),
("conversation_item_added_filters_non_message_items",
test_conversation_item_added_filters_non_message_items),
("shutdown_callback_protocol_real_jobcontext_wrapper",
test_shutdown_callback_protocol_real_jobcontext_wrapper),
("turn_handling_disables_default_english_eou_detector",
test_turn_handling_disables_default_english_eou_detector),
]
failures = 0
for name, check in checks: