HEL-903: preserve visual author voice status, call voice and recovery fixes

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
总管
2026-10-28 01:10:48 +08:00
co-authored by multica-agent
parent b09a907747
commit 51669aae6d
11 changed files with 656 additions and 24 deletions
+13
View File
@@ -11,6 +11,7 @@ import { motionOff } from '../stage/roomScene';
import { LineStage, type PresentHow } from './lineStage';
import { anchorOf, cursorAt, groupTurns, pagesOf, ReadingClock, type Anchor, type Metrics, type ShownMessage } from './reading';
import { mergeTurns, OFF, recentRows, VoiceController, voiceLine, voiceStatus, WORDS, type VoiceView } from '../voice/session';
import { callVoiceName, listVoices } from '../voice/custom';
import { loadTransport } from '../voice/livekit';
import { newestId, serverId } from '../adapters/inbox';
@@ -89,6 +90,17 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
voiceStatus(c.signal).then(s => setVoiceOff(s.available ? '' : s.reason), () => {});
return () => c.abort();
}, [real]);
// The voice this call was opened with (HEL-903). Its name is looked up by that id only — never the choice settings
// hold now, which is the next call's — and an answer for another id (an older call) is never shown.
const pinned = real ? voiceView.voice : null, [named, setNamed] = useState<{ id: string; label: string } | null>(null);
useEffect(() => {
const id = pinned?.id; if (!id || id === 'default' || named?.id === id) return;
const c = new AbortController();
listVoices(c.signal).then(list => { const v = !c.signal.aborted && list.configured ? list.voices.find(x => x.id === id) : undefined; if (v) setNamed({ id, label: v.label }); }, () => { /* The id stays on show. */ });
return () => c.abort();
// eslint-disable-next-line react-hooks/exhaustive-deps -- one lookup per pinned id.
}, [pinned?.id]);
const pinnedName = pinned && callVoiceName(pinned.id, named);
const voiceOn = real ? voiceView.phase !== 'off' : voice;
const voiceLabel = { off: '', opening: '正在接通…', joining: `在等${name}接起…`, listening: '在听你说', thinking: `${name}在想`, speaking: `${name}在说 · 开口就能打断` }[voiceView.phase];
useEffect(() => {
@@ -334,6 +346,7 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
{real && voiceOn && <div className="voice-row real" data-phase={voiceView.phase} role="status" aria-live="polite">
<span className="voice-wave" aria-hidden="true"><i/><i/><i/><i/></span>
<span className="voice-state">{voiceLabel}</span>
{pinned && pinnedName && <span className={`voice-pin ${pinned.id ? '' : 'unknown'}`} title={pinned.id ? `本次通话用「${pinnedName}」,到这次通话结束都不变;设置里换的声音下一次通话才生效。` : '服务器这次没有说明用的是哪个声音,这里不猜。设置里换的声音下一次通话才生效。'}><small>本次<span className="vp-wide">通话</span></small>{pinnedName}</span>}
{voiceView.spoken ? <span className="voice-heard said" title={voiceView.spoken}>{name}:{voiceView.spoken}<em>未记入聊天</em></span> : voiceView.heard && <span className="voice-heard" title={voiceView.heard}>「{voiceView.heard}」</span>}
{voiceView.blocked && <button onClick={() => void voiceCtl.current?.resumeAudio()}>点一下听{name}的声音</button>}
<button className="voice-end" onClick={() => { void voiceCtl.current?.end(); setNotice('语音已结束,麦克风已关闭。'); }}>结束语音</button>
+19 -2
View File
@@ -5,12 +5,21 @@ import { delay } from '../adapters/demo';
import { exportDemo, parseState } from '../adapters/storage';
import { BaseColor, Button, Field, Icon, Modal, Status } from '../shared/ui';
import { VoiceSection, type VoiceCap } from './VoiceSection';
import { readVoiceStatus, type VoiceStatusKind } from '../voice/session';
const sections = [['her', 'user', '她'], ['relation', 'heart', '关系'], ['voice', 'mic', '她的声音'], ['city', 'pin', '城市'], ['appearance', 'image', '外观素材'], ['backup', 'box', '本地演示导出'], ['services', 'plug', '外接服务'], ['display', 'moon', '显示']];
// What each section can actually do here (HEL-815 capability tags): read-only, adjustable, demo only, not connected, this device.
type Cap = 'ro' | 'edit' | 'demo' | 'off' | 'live' | 'local';
const CAP: Record<Cap, [string, string]> = { ro: ['只读', ''], edit: ['可以调整', 'accent'], demo: ['演示数据', 'demo'], off: ['未接入', 'off'], live: ['文字已接通', 'ok'], local: ['本机生效', 'ok'] };
const capOf = (id: string, real: boolean, voice: VoiceCap = 'unknown'): Cap => id === 'her' ? 'ro' : id === 'relation' ? 'edit' : id === 'voice' ? real ? voice === 'off' ? 'off' : 'edit' : 'demo' : id === 'display' ? 'local' : id === 'services' && real ? 'live' : real ? 'off' : 'demo';
const NOTE: Record<string, string> = { her: '只读资料', relation: '可以调整', voice: '上传 · 录音 · 试听', display: '本机生效' };
// 外接服务 · voice rows (HEL-903): exactly what GET /api/voice/status can tell — no route, not configured, configured with
// the TTS health probe passing or failing, or unreadable. Recognition has no probe of its own there, so it never claims one.
type VoiceSvc = VoiceStatusKind | 'loading';
const VOICE_SVC: Record<'asr' | 'tts' | 'config', Record<VoiceSvc, string>> = {
tts: { loading: '正在读取语音状态…', none: '这台服务没有语音状态接口', off: '未配置 · 这台服务没有语音配置', ok: '已配置 · 合成服务健康检查可连接', down: '已配置 · 合成服务这会儿暂不可用', unknown: '状态未知 · 这次没读到语音状态' },
asr: { loading: '正在读取语音状态…', none: '这台服务没有语音状态接口', off: '未配置 · 这台服务没有语音配置', ok: '已配置 · 没有单独的健康检查,以实际通话为准', down: '已配置 · 没有单独的健康检查,以实际通话为准', unknown: '状态未知 · 这次没读到语音状态' },
config: { loading: '读取中', none: '服务尚未配置', off: '服务尚未配置', ok: '由服务器管理', down: '由服务器管理', unknown: '暂时读不到' },
};
function CapTag({ cap }: { cap: Cap }) { const [text, tone] = CAP[cap]; return <span className={`tag cap ${tone}`}>{text}</span>; }
// Honest placeholder for a capability that is not connected: what it will do once connected, and that nothing happens now.
function Off({ title, will, now }: { title: string; will: string; now: string }) { return <div className="off-card"><p className="off-t">{title}</p><p>{will}</p><p className="d-dim">{now}</p></div>; }
@@ -33,6 +42,14 @@ export function ManagePanel({ state, open, onClose, onSave, fail, theme, setThem
const approvedNavigation = useRef(false);
const pendingNavigation = useRef<(() => void) | null>(null);
const [serviceHealth, setServiceHealth] = useState<Health>();
// Read on opening 外接服务 and on an explicit re-read; real only (the demo never asks a server).
const [voiceSvc, setVoiceSvc] = useState<VoiceSvc>('loading'), [voiceSvcRead, setVoiceSvcRead] = useState(0);
useEffect(() => {
if (!real || !open || section !== 'services') return;
const c = new AbortController(); setVoiceSvc('loading');
readVoiceStatus(c.signal).then(kind => { if (!c.signal.aborted) setVoiceSvc(kind); }, () => { /* Aborted: left the section. */ });
return () => c.abort();
}, [real, open, section, voiceSvcRead]);
// 她的声音 (HEL-900): an unregistered reference counts as unsaved; the tag follows what the server reports.
const [voiceDirty, setVoiceDirty] = useState(false), [voiceCap, setVoiceCap] = useState<VoiceCap>('unknown');
const request = useRef<AbortController | null>(null), generation = useRef(0), feedback = useRef<HTMLDivElement>(null);
@@ -56,7 +73,7 @@ export function ManagePanel({ state, open, onClose, onSave, fail, theme, setThem
}, [open, anyDirty]);
async function checkService() {
setBusy(true); setError(false); setMessage('正在检查文字服务…');
try { const status = await api<Health>('health'); setServiceHealth(status); setMessage(status.llm.ok ? '文字服务可达。语音、视觉和长期记忆仍未接通。' : '文字模型暂时不可达,档案和历史仍可查看。'); setError(!status.llm.ok); }
try { const status = await api<Health>('health'); setServiceHealth(status); setMessage(status.llm.ok ? '文字服务可达。视觉观察和长期记忆仍未接通;语音状态以上面两行为准。' : '文字模型暂时不可达,档案和历史仍可查看。'); setError(!status.llm.ok); }
catch (e) { setMessage((e as Error).message); setError(true); }
finally { setBusy(false); }
}
@@ -187,7 +204,7 @@ export function ManagePanel({ state, open, onClose, onSave, fail, theme, setThem
{real && section === 'city' && <><Off title="城市与天气还没有接上。" will="接上以后,你选一个真实城市,她房间里的天气、白天黑夜和作息都跟着那里走;换城市不需要每次重新定位。" now="现在窗外的雨是界面氛围,不是真实天气。尚未设置可核实的城市,天气来源尚未确定。"/><Field label="搜索城市" hint="可浏览候选目录;当前无法保存,不会更改她的城市。"><input className="input" value={search} placeholder="输入城市名称" onChange={e => setSearch(e.target.value)}/></Field><ul className="city-list">{['杭州', '上海', '北京', '成都', '广州', '深圳'].filter(c => c.includes(search.trim())).map(c => <li key={c}><button disabled>{c}<small>候选城市 · 保存待接入</small></button></li>)}</ul>{!['杭州', '上海', '北京', '成都', '广州', '深圳'].some(c => c.includes(search.trim())) && <div className="empty">当前目录没有匹配的城市。</div>}<div className="actions"><Button disabled>保存城市 · 待接入</Button></div></>}
{real && section === 'appearance' && <><dl className="kv"><dt>现在的样子</dt><dd>工程外观 v2<small>参考静帧 · 尚无成套日常与交谈视频</small></dd></dl><Off title="换外观还没有接上。" will="接上以后:选择素材包 → 检查素材 → 看新旧对比 → 确认「她还是她」。只换样子,名字、底色、记忆和关系都不变。" now="素材包规范与导入检查尚未定稿。这里不会导入、预览或替换任何素材。"/><Field label="选择外观素材包" hint="素材包格式与媒体检查将在后续接入。当前不上传、不读取文件。"><input type="file" disabled/></Field><ul className="phases">{['清单结构与版本', '媒体格式与时长', '人物一致性', '必要场景覆盖', '可用性与兼容性'].map(label => <li key={label}>待检查 · {label}</li>)}</ul><div className="compare"><figure><img src="/assets/her-room.jpg" alt="当前内置参考静帧"/><figcaption>当前参考</figcaption></figure><figure><div className="empty">导入并通过检查后显示新外观</div><figcaption>新旧对比 · 待接入</figcaption></figure></div><Button disabled>确认应用外观 · 待接入</Button></>}
{real && section === 'backup' && <><Off title="备份还没有接上。" will="接上以后:服务器每天自动备份;你可以随时把她完整导出到自己的电脑(含底色、性格资料、对话、记忆、关系、生活进度和所用素材),也能从备份恢复同一个她。" now="现在没有任何备份在运行,这里也不会假装导出或恢复。"/><div className="card"><h4>每日自动备份</h4><p>暂无可核实的备份记录。自动备份、保留份数与运行结果将在接入后显示。</p><div className="empty">尚未接通备份服务</div></div><div className="card"><h4>完整导出</h4><p>将包含服务器档案、聊天及届时接通的记录与素材。当前不生成伪备份文件。</p><Button disabled>导出完整备份 · 待接入</Button></div><Field label="恢复同一位她的备份" hint="恢复前会检查完整性、版本和同一档案,要求输入“恢复”,并先备份当前资料。当前不接收文件或执行覆盖。"><input type="file" disabled/></Field><ul className="phases">{['检查完整性与版本', '核对是否同一位她', '先备份当前资料', '输入确认并恢复'].map(label => <li key={label}>待接入 · {label}</li>)}</ul><button className="btn-danger" disabled>检查备份并继续 · 待接入</button></>}
{real && section === 'services' && <>{[['文字对话', serviceHealth ? serviceHealth.llm.ok ? '连接可达' : '暂时不可达' : '已接通 · 可重新检查'], ['语音识别', '尚未接通'], ['语音合成', '尚未接通'], ['视觉观察', '尚未接通']].map(([label, status], index) => <div className="svc" key={label}><div className="nm">{label}<small>{status}</small></div><Button disabled={index !== 0 || busy} onClick={() => void checkService()}>{index === 0 ? busy ? '检查中…' : '重新检查连接' : '测试连接 · 待接入'}</Button><input className="input" aria-label={`${label}配置`} value={index === 0 ? '由服务器管理' : '服务尚未配置'} readOnly/></div>)}<Off title="语音与视觉观察还没有接上。" will="接上以后:语音由你主动开启,结束后停止收音,文字聊天一直保留;视觉观察只看人在不在、明显物品和房间变化,过期的画面不再当作眼前。" now="这里不申请麦克风或摄像头,不采集声音与影像。"/><div className="card"><h4>其余能力</h4><p>{life?.wired ? `生活:${life.label}。${life.note}长期记忆、主动消息和天气尚未接通。` : '生活、长期记忆、主动消息和天气尚未接通。'}文字模型暂时不可达时,已保存的档案和聊天记录仍可查看。</p></div></>}
{real && section === 'services' && <>{([['text', '文字对话', serviceHealth ? serviceHealth.llm.ok ? '连接可达' : '暂时不可达' : '已接通 · 可重新检查'], ['voice', '语音识别', VOICE_SVC.asr[voiceSvc]], ['voice', '语音合成', VOICE_SVC.tts[voiceSvc]], ['off', '视觉观察', '尚未接通']] as const).map(([kind, label, status]) => <div className="svc" key={label} data-state={kind === 'voice' ? voiceSvc : undefined}><div className="nm">{label}<small>{status}</small></div>{kind === 'text' ? <Button disabled={busy} onClick={() => void checkService()}>{busy ? '检查中…' : '重新检查连接'}</Button> : kind === 'voice' ? <Button disabled={voiceSvc === 'loading'} onClick={() => setVoiceSvcRead(n => n + 1)}>{voiceSvc === 'loading' ? '读取中…' : '重新读取状态'}</Button> : <Button disabled>测试连接 · 待接入</Button>}<input className="input" aria-label={`${label}配置`} value={kind === 'text' ? '由服务器管理' : kind === 'voice' ? VOICE_SVC.config[voiceSvc] : '服务尚未配置'} readOnly/></div>)}<p className="d-dim">语音两项读自服务器的语音状态:「可连接」只说明她的声音(合成)这会儿通过了健康检查,不代表整套语音通话已经验收;语音识别这里查不到单独的状态。这里只读状态,不申请麦克风。</p><Off title="视觉观察还没有接上。" will="接上以后:视觉观察只看人在不在、明显物品和房间变化,过期的画面不再当作眼前。语音由你在交谈里主动开启,结束后停止收音,文字聊天一直保留。" now="这里不申请摄像头,不采集影像。"/><div className="card"><h4>其余能力</h4><p>{life?.wired ? `生活:${life.label}。${life.note}长期记忆、主动消息和天气尚未接通。` : '生活、长期记忆、主动消息和天气尚未接通。'}文字模型暂时不可达时,已保存的档案和聊天记录仍可查看。</p></div></>}
<div ref={feedback}><Status text={message} error={error}/></div>{(real ? ['relation', 'display'] : ['relation', 'city', 'services', 'display']).includes(section) && <div className="actions"><span className={`grow ${dirty ? 'dirty' : ''}`}>{dirty ? '有未保存的修改' : '尚未修改'}</span><Button disabled={!dirty || busy} onClick={reset}>取消修改</Button><Button primary disabled={!dirty || busy} onClick={() => void save()}>{busy ? '正在保存…' : error ? '重试保存' : '保存'}</Button></div>}</div></div></div>
{confirm && <Modal title={confirm === 'leave' ? '有未保存的修改' : confirm === 'relation' ? `把关系从「${state.identity.relation}」改成「${draft.identity.relation}」?` : confirm === 'restore' ? '恢复本地演示资料?' : '她还是她'} danger={confirm === 'restore'} onClose={() => setConfirm('')} disabled={confirm === 'restore' && confirmText !== '恢复'} onConfirm={() => { const which = confirm; setConfirm(''); if (which === 'leave') { request.current?.abort(); setBusy(false); setDraft({ identity: structuredClone(state.identity), settings: structuredClone(state.settings) }); const action = pendingNavigation.current; pendingNavigation.current = null; approvedNavigation.current = true; try { action?.(); } finally { approvedNavigation.current = false; } } if (which === 'relation')
void save(true); if (which === 'appearance') {
+27 -6
View File
@@ -4,7 +4,7 @@
// (request aborted, audio stopped, object URL revoked), so an old sample can never pass for the new one.
import { useEffect, useRef, useState, type RefObject } from 'react';
import { clockOf } from '../adapters/real';
import { applyVoice, LABEL_MAX, listVoices, PREVIEW_DEFAULT, PREVIEW_MAX, previewVoice, Recorder, registerVoice, SAY, SUGGEST_MAX, SUGGEST_MIN, TEXT_MAX, toReference, VoiceError, type CustomVoice, type RecView, type VoiceSelection } from '../voice/custom';
import { applyVoice, idOnly, LABEL_MAX, listVoices, PREVIEW_DEFAULT, PREVIEW_MAX, previewVoice, Recorder, registerVoice, SAY, SUGGEST_MAX, SUGGEST_MIN, TEXT_MAX, toReference, VoiceError, type CustomVoice, type RecView, type VoiceSelection } from '../voice/custom';
import { Button, Field, Icon, Status } from '../shared/ui';
export type VoiceCap = 'edit' | 'off' | 'unknown';
@@ -37,6 +37,11 @@ export function VoiceSection({ name, active, onDirty, onCap }: { name: string; a
// One controller per kind of request; a new one aborts the old. `takeGen` guards decoding a file or a recording.
const ctl = useRef<Record<'list' | 'register' | 'preview' | 'apply', AbortController | null>>({ list: null, register: null, preview: null, apply: null });
const takeGen = useRef(0), urls = useRef(new Set<string>()), listed = useRef(false);
// HEL-903: a registration that failed without a clear answer may still have been filed. `unsure` holds the custom ids
// listed when it failed, so an explicit refresh can say which entry is new (never a silent second registration).
const [unsure, setUnsure] = useState(false), unsureBefore = useRef<Set<string> | null>(null);
const settleUnsure = () => { unsureBefore.current = null; setUnsure(false); };
const loadNow = useRef(load); loadNow.current = load;
const fresh = (kind: keyof typeof ctl.current) => { ctl.current[kind]?.abort(); const c = new AbortController(); ctl.current[kind] = c; return c; };
const own = (blob: Blob) => { const url = URL.createObjectURL(blob); urls.current.add(url); return url; };
const drop = (url?: string) => { if (url && urls.current.delete(url)) URL.revokeObjectURL(url); };
@@ -69,6 +74,12 @@ export function VoiceSection({ name, active, onDirty, onCap }: { name: string; a
if (c.signal.aborted) return;
if (!list.configured) { setLoad({ state: 'off', text: SAY.notConfigured }); onCap('off'); return; }
listed.current = true; setNote(n => n.error ? { text: '', error: false } : n); setLoad({ state: 'ok', voices: list.voices, selection: list.selection }); onCap('edit');
const before = unsureBefore.current;
if (before) {
const fresh = list.voices.filter(v => v.source === 'custom' && !before.has(v.id));
if (fresh.length) { settleUnsure(); setRegNote({ text: `列表里多了${fresh.map(v => `「${v.label}」`).join('、')},${SAY.refreshFound}`, error: false }); }
else setRegNote({ text: SAY.refreshNone, error: false });
}
}, e => {
if (c.signal.aborted) return;
const status = e instanceof VoiceError ? e.status : 0;
@@ -86,6 +97,7 @@ export function VoiceSection({ name, active, onDirty, onCap }: { name: string; a
try {
const ref = await toReference(input);
if (gen !== takeGen.current) return;
settleUnsure();
const url = own(ref.wav);
setTake(old => { drop(old?.url); return { wav: ref.wav, url, seconds: ref.seconds, from: kind, name: label }; });
setRegNote({ text: '', error: false });
@@ -99,7 +111,7 @@ export function VoiceSection({ name, active, onDirty, onCap }: { name: string; a
if (!file || registering) return;
void accept(file, 'file', file.name.slice(0, 60));
}
function discardTake() { takeGen.current++; recorder.current?.cancel(); setTake(old => { drop(old?.url); return null; }); setRegNote({ text: '', error: false }); }
function discardTake() { takeGen.current++; recorder.current?.cancel(); settleUnsure(); setTake(old => { drop(old?.url); return null; }); setRegNote({ text: '', error: false }); }
function switchFrom(next: 'file' | 'record') { if (next === from) return; recorder.current?.cancel(); setFrom(next); setRegNote({ text: '', error: false }); }
const text = form.text.trim(), needText = !text && !form.allowAsr;
@@ -111,6 +123,7 @@ export function VoiceSection({ name, active, onDirty, onCap }: { name: string; a
try {
const done = await registerVoice(sent.wav, form, c.signal);
if (c.signal.aborted) return;
settleUnsure();
setTake(old => { if (old === sent) { drop(old.url); return null; } return old; });
setForm({ label: '', text: '', allowAsr: false });
setRegNote({ text: done.prompt_text_source === 'asr' ? `登记好了:「${done.label}」。服务器转写的参考文字是:${done.prompt_text || '(空)'}` : `登记好了:「${done.label}」。`, error: false });
@@ -119,8 +132,15 @@ export function VoiceSection({ name, active, onDirty, onCap }: { name: string; a
setReads(n => n + 1);
} catch (e) {
if (c.signal.aborted) return;
// Nothing is lost on failure: the take, the label and the text all stay for another try.
setRegNote({ text: message(e), error: true });
// Nothing is lost on failure: the take, the label and the text all stay for another try. When the server may
// have filed it anyway, say so and offer a look at the list first; the list is not re-read behind your back.
if (e instanceof VoiceError && e.uncertain) {
const l = loadNow.current;
if (l.state === 'ok' && !unsureBefore.current) unsureBefore.current = new Set(l.voices.filter(v => v.source === 'custom').map(v => v.id));
setUnsure(true);
// The server's own words when it gave any; a bare "try again later" would contradict "look first".
setRegNote({ text: e.message === SAY.failed || e.message === SAY.odd ? SAY.maybeRegistered : `${e.message}${SAY.maybeRegistered}`, error: true });
} else setRegNote({ text: message(e), error: true });
} finally { if (ctl.current.register === c) { ctl.current.register = null; setRegistering(false); } }
}
@@ -174,7 +194,7 @@ export function VoiceSection({ name, active, onDirty, onCap }: { name: string; a
const mine = voices.filter(v => v.source === 'custom'), builtin = voices.filter(v => v.source === 'builtin');
const chosen = voices.find(v => v.id === candidate), ready = sample?.voice === candidate && sample.state === 'ready';
const recording = rec.phase === 'asking' || rec.phase === 'recording';
const row = (v: CustomVoice) => <li key={v.id}><button aria-pressed={candidate === v.id} onClick={() => pick(v.id)} disabled={applying}><span>{v.label}{v.selected && <span className="tag accent">正在用</span>}</span><small>{v.source === 'custom' ? `自定义${v.registered_at ? ` · ${clockOf(v.registered_at).date}` : ''}` : '服务自带'}{v.previewed ? ' · 试听过' : ''}</small></button></li>;
const row = (v: CustomVoice) => <li key={v.id}><button aria-pressed={candidate === v.id} onClick={() => pick(v.id)} disabled={applying}><span>{v.label}{v.selected && <span className="tag accent">正在用</span>}</span><small>{idOnly(v) ? '自定义 · 只有编号,缺本地资料' : v.source === 'custom' ? `自定义${v.registered_at ? ` · ${clockOf(v.registered_at).date}` : ''}` : '服务自带'}{v.previewed ? ' · 试听过' : ''}</small></button></li>;
return <div className="voice-sec">
<dl className="kv"><dt>现在的声音</dt><dd>{selection.voice ? <>{current?.label || selection.label || selection.voice}<small>{current?.source === 'custom' ? '自定义' : current ? '服务自带' : '这个声音已不在列表里,通话时会用默认声音'}{selection.updated_at ? ` · ${clockOf(selection.updated_at).date} ${clockOf(selection.updated_at).time} 换上` : ''}</small></> : <>还没有为她选过<small>通话时用服务默认的声音</small></>}</dd>
@@ -197,7 +217,7 @@ export function VoiceSection({ name, active, onDirty, onCap }: { name: string; a
<Field label="给这个声音起个名字" hint={`最多 ${LABEL_MAX} 个字,只用来在这里区分;不填就用编号。`}><input className="input" value={form.label} maxLength={LABEL_MAX} placeholder="比如:轻一点的她" disabled={registering} onChange={e => setForm(f => ({ ...f, label: e.target.value.replace(/[<>\p{Cc}]/gu, '') }))}/></Field>
<Field label="参考文字" hint="这段声音里念的原话。写得越准,克隆越像。"><textarea className="textarea" value={form.text} maxLength={TEXT_MAX} rows={2} disabled={registering} placeholder="照着录音里念的内容写下来" onChange={e => setForm(f => ({ ...f, text: e.target.value }))}/></Field>
<label className="switch-row"><span>参考文字留空时,允许服务器转写<small>{text ? '已经填写了参考文字,不会转写。' : '会用这台服务器上的语音识别听一遍这段声音;不打开就必须填写参考文字。'}</small></span><input type="checkbox" className="switch" checked={form.allowAsr && !text} disabled={!!text || registering} onChange={e => setForm(f => ({ ...f, allowAsr: e.target.checked }))}/></label>
<div className="take-acts"><Button primary disabled={registering || needText} onClick={() => void register()}>{registering ? '正在登记…' : '登记这段声音'}</Button><Button disabled={registering} onClick={discardTake}>换一段</Button></div>
<div className="take-acts">{unsure && <Button primary disabled={registering} onClick={() => setReads(n => n + 1)}><Icon name="list"/>刷新列表</Button>}<Button primary={!unsure} disabled={registering || needText} onClick={() => void register()}>{registering ? '正在登记…' : unsure ? '确认没有,再登记' : '登记这段声音'}</Button><Button disabled={registering} onClick={discardTake}>换一段</Button></div>
{needText && !registering && <p className="d-dim">填写参考文字,或打开上面的转写开关,才能登记。</p>}
</div>}
<Status text={regNote.text} error={regNote.error}/>
@@ -205,6 +225,7 @@ export function VoiceSection({ name, active, onDirty, onCap }: { name: string; a
<h4 className="sub-h">可以给她用的声音<small>先试听,再给她用</small></h4>
<p className="voice-group">你给的声音</p>
{mine.length ? <ul className="city-list voice-list">{mine.map(row)}</ul> : <div className="empty sm">还没有登记过自己的声音。</div>}
{mine.some(idOnly) && <p className="d-dim voice-idonly">{SAY.idOnly}</p>}
{builtin.length > 0 && <details className="voice-builtin" open={!!chosen && chosen.source === 'builtin'}><summary>服务自带的声音 · {builtin.length} 个</summary><ul className="city-list voice-list">{builtin.map(row)}</ul></details>}
{chosen && <div className="card audition" aria-live="polite">
+12
View File
@@ -1034,4 +1034,16 @@ body.creating .now-chip{display:none}
@media (max-width:720px){
.voice-sec .take-acts .btn-primary,.voice-sec .take-acts .btn-ghost,.voice-sec .rec-acts button{flex:1}
.voice-sec .rec .btn-ghost{width:100%}
}
/* ── HEL-903: the call's own voice on the call line, the voice status rows, id-only entries. Tokens only. ── */
.voice-row.real .voice-pin{display:inline-block;flex:0 1 auto;min-width:0;max-width:12em;padding-left:10px;border-left:1px solid var(--glass-line);color:var(--text-1);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.voice-row.real .voice-pin small{margin-right:6px;font-size:11px;color:var(--text-3);letter-spacing:.04em}
.voice-row.real .voice-pin.unknown{color:var(--text-3)}
.svc[data-state="ok"] .nm small{color:var(--ok)}
.svc[data-state="down"] .nm small{color:var(--warn)}
.voice-idonly{margin:8px 0 0;font-size:12.5px}
@media (max-width:720px){
.voice-sec .take-acts .btn-primary,.voice-sec .take-acts .btn-ghost{flex:1 1 auto;white-space:nowrap}
.voice-row.real .voice-pin{max-width:9.5em;padding-left:8px}
.voice-row.real .voice-pin .vp-wide{display:none}
}
+23 -4
View File
@@ -37,9 +37,16 @@ export const SAY = {
noRecorder: '这个浏览器不支持在网页里录音。可以改用上传文件。',
micGone: '麦克风被关掉了,这段没有录完,已经丢弃。',
recordFailed: '这次录音没有成功,已经丢弃,可以再录一次。',
// HEL-903: the upload may have reached the shared voice panel even though no answer came back (server error, a
// dropped connection, local metadata not saved). Look before registering again, so one voice is not filed twice.
maybeRegistered: '这段声音可能已经登记上了,只是这边没收到结果。先点「刷新列表」,看看「你给的声音」里有没有新出现的编号条目(cg- 开头):有就直接选它试听、使用,不用再登记一次。',
refreshFound: '很可能就是刚才那段:直接在下面选它试听、使用就好,不用再登记一次。',
refreshNone: '列表里暂时没有新出现的条目。服务器可能还在处理,稍等几秒再刷新一次;确认没有再登记。',
idOnly: '只有编号的条目:声音已经登记在共享面板上,但这台服务器没存下它的名字和参考文字,多半来自一次没收到结果的登记。它仍可试听、使用;这里暂时不能删除。',
} as const;
export class VoiceError extends Error { constructor(message: string, readonly status = 0) { super(message); } }
// `uncertain`: the request may have been carried out even though it failed here (sent, then no usable answer).
export class VoiceError extends Error { constructor(message: string, readonly status = 0, readonly uncertain = false) { super(message); } }
// ── WAV ──
export function encodeWav(samples: Float32Array, rate = RATE): ArrayBuffer {
@@ -111,7 +118,8 @@ const online = () => typeof navigator === 'undefined' || navigator.onLine !== fa
async function call(f: Fetch, path: string, init: RequestInit): Promise<Response> {
if (!online()) throw new VoiceError(SAY.offline);
try { return await f(`/api/voice/${path}`, init); }
catch (e) { if (init.signal?.aborted) throw e; throw new VoiceError(online() ? SAY.unreachable : SAY.offline); }
// Gone after sending started: whether the server acted on it is unknown (an offline check above sent nothing).
catch (e) { if (init.signal?.aborted) throw e; throw new VoiceError(online() ? SAY.unreachable : SAY.offline, 0, true); }
}
async function refusal(r: Response, fallback: string = SAY.failed): Promise<VoiceError> {
const data = await r.json().catch(() => null) as { detail?: unknown } | null;
@@ -136,11 +144,22 @@ export async function listVoices(signal: AbortSignal, f: Fetch = fetch): Promise
export async function registerVoice(wav: Blob, form: { label: string; text: string; allowAsr: boolean }, signal: AbortSignal, f: Fetch = fetch): Promise<Registered> {
const q = new URLSearchParams({ label: form.label.trim(), prompt_text: form.text.trim(), allow_asr: form.allowAsr && !form.text.trim() ? 'true' : 'false' });
const r = await call(f, `voices?${q}`, { method: 'POST', headers: { 'Content-Type': 'audio/wav' }, body: wav, signal });
if (!r.ok) throw await refusal(r);
// A 4xx is a clear refusal (nothing filed). A 5xx, or a success whose body never arrived whole, may sit after the
// panel already took the voice (HEL-902 §4: metadata write failing → 500, panel down → 503).
if (!r.ok) { const e = await refusal(r); throw r.status >= 500 ? new VoiceError(e.message, r.status, true) : e; }
const data = await r.json().catch(() => null) as Partial<Registered> | null;
if (!data || typeof data.id !== 'string' || !data.id) throw new VoiceError(SAY.odd);
if (!data || typeof data.id !== 'string' || !data.id) throw new VoiceError(SAY.odd, r.status, true);
return { id: data.id, label: typeof data.label === 'string' && data.label ? data.label : data.id, prompt_text: typeof data.prompt_text === 'string' ? data.prompt_text : '', prompt_text_source: data.prompt_text_source === 'asr' ? 'asr' : 'user' };
}
// A voice the server lists with no local metadata (label falls back to the id, no registration time): the panel has it,
// this server never recorded it — typically a registration whose answer was lost.
export const idOnly = (v: CustomVoice) => v.source === 'custom' && v.registered_at === null && v.label === v.id;
// The name a call's pinned voice is shown by: its own label if the list knows that id, else the id itself; never a guess.
export function callVoiceName(id: string | null, named: { id: string; label: string } | null): string {
if (!id) return '声音未说明';
if (id === 'default') return '默认声音';
return named?.id === id ? named.label : id;
}
// A fresh synthesis every time. Only a real WAV comes back as playable; anything else is refused, never played.
export async function previewVoice(voice: string, text: string, signal: AbortSignal, f: Fetch = fetch): Promise<Blob> {
const r = await call(f, 'preview', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(text.trim() ? { voice, text: text.trim() } : { voice }), signal });
+26 -11
View File
@@ -24,12 +24,16 @@ export interface VoiceView {
notice: string;
// The browser held her audio back until a tap (autoplay rules); `resume` lets it out.
blocked: boolean;
// The voice the server pinned for THIS call (HEL-903, session response `voice`): null until a room is granted;
// `id: null` when the server did not say. It stays for the whole call; a choice made in settings is the next call's.
voice: CallVoice | null;
}
export interface CallVoice { id: string | null }
// One "she speaks" (an SDK speech): her reply to your voice turn, or a stored reach-out read aloud. `open` grows by
// replacement (each interim is the whole text so far); `final` is the stored reply's exact text; `done` is closed and
// stays only until the record (or the next turn) takes its place.
export interface HerLine { speech: string; text: string; state: 'open' | 'final' | 'done'; turnId?: string; messageId?: number; proactive?: boolean }
export const OFF: VoiceView = { phase: 'off', heard: '', spoken: '', her: null, notice: '', blocked: false };
export const OFF: VoiceView = { phase: 'off', heard: '', spoken: '', her: null, notice: '', blocked: false, voice: null };
// ── cg.subtitle contract v2 (docs/voice-subtitle-contract-v2.md). Anything that is not exactly v2 is dropped. ──
const USER_KINDS = ['interim', 'user_final'] as const;
@@ -69,7 +73,9 @@ export interface VoiceRoom { publish(mic: MicTrack): Promise<void>; hush(on: boo
export interface VoiceTransport { capture(): Promise<MicTrack>; join(url: string, token: string, on: RoomEvents, signal: AbortSignal): Promise<VoiceRoom> }
export interface VoiceAvailability { available: boolean; reason: string }
export interface SessionGrant { url: string; token: string; room: string; session_id: string; epoch: number; expires_at: number }
export interface SessionGrant { url: string; token: string; room: string; session_id: string; epoch: number; expires_at: number; voice?: unknown }
// Only an id the voice list could hold is taken as the call's voice; anything else is "not said", never guessed.
export const callVoiceOf = (grant: { voice?: unknown }): CallVoice => ({ id: typeof grant.voice === 'string' && /^[\w-]{1,40}$/u.test(grant.voice) ? grant.voice : null });
export const WORDS = {
notConfigured: '语音还没有在这台服务上配置,文字仍可使用。',
@@ -109,16 +115,24 @@ interface Live { gen: number; abort: AbortController; mic?: MicTrack; room?: Voi
const AGENT_PHASE: Record<string, VoicePhase> = { initializing: 'joining', listening: 'listening', thinking: 'thinking', speaking: 'speaking' };
export async function voiceStatus(signal: AbortSignal, f: typeof fetch = fetch): Promise<VoiceAvailability> {
// What GET /api/voice/status can actually tell (HEL-903): no route on this server, not configured, configured with the
// TTS health probe passing ('ok') or failing ('down'), or unreadable. It says nothing about recognition on its own and
// never that a whole call works end to end (`voice` stays false until real-device acceptance).
export type VoiceStatusKind = 'none' | 'off' | 'ok' | 'down' | 'unknown';
export async function readVoiceStatus(signal: AbortSignal, f: typeof fetch = fetch): Promise<VoiceStatusKind> {
let response: Response;
try { response = await f('/api/voice/status', { signal }); } catch (e) { if (signal.aborted) throw e; return { available: false, reason: WORDS.unknown }; }
try { response = await f('/api/voice/status', { signal }); } catch (e) { if (signal.aborted) throw e; return 'unknown'; }
// A server from before R5 has no such route: that is "not wired", not a failure.
if (response.status === 404 || response.status === 405) return { available: false, reason: WORDS.noRoute };
if (response.status === 404 || response.status === 405) return 'none';
const data = await response.json().catch(() => null) as { configured?: unknown; tts_ok?: unknown } | null;
if (!response.ok || !data) return { available: false, reason: WORDS.unknown };
if (data.configured !== true) return { available: false, reason: WORDS.notConfigured };
if (data.tts_ok !== true) return { available: false, reason: WORDS.ttsDown };
return { available: true, reason: '' };
if (!response.ok || !data) return 'unknown';
if (data.configured !== true) return 'off';
return data.tts_ok === true ? 'ok' : 'down';
}
const REASON: Record<VoiceStatusKind, string> = { none: WORDS.noRoute, off: WORDS.notConfigured, ok: '', down: WORDS.ttsDown, unknown: WORDS.unknown };
export async function voiceStatus(signal: AbortSignal, f: typeof fetch = fetch): Promise<VoiceAvailability> {
const kind = await readVoiceStatus(signal, f);
return { available: kind === 'ok', reason: REASON[kind] };
}
function micFailure(e: unknown, secure: boolean) {
@@ -202,8 +216,9 @@ export class VoiceController {
if (!response.ok || !data?.token || !data.url || !live.session) return fail(typeof data?.detail === 'string' && data.detail ? data.detail : WORDS.unreachable);
const grant = data;
// 4. Join and speak.
this.show({ phase: 'joining' }, gen);
// 4. Join and speak. The voice this room was opened with is shown from here to the end of this call; a late grant
// of an older call never gets here (stale), and every end or failure resets the view.
this.show({ phase: 'joining', voice: callVoiceOf(grant) }, gen);
const events: RoomEvents = {
agentJoined: () => { if (stale() || live.agent) return; live.agent = true; clearTimeout(live.timer); if (!live.stated) this.show({ phase: 'listening' }, gen); },
// Her worker gone with the room still open: no one would ever answer, so the call ends honestly, exactly as a