HEL-898: preserve director three-fix rework verbatim on b0dcb17

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
总管
2026-10-27 07:09:23 +08:00
co-authored by multica-agent
parent b0dcb17e1a
commit 9254c17316
12 changed files with 527 additions and 115 deletions
+3 -2
View File
@@ -173,7 +173,8 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
// Her voice line withdrawn (cut, φ, text took over, you spoke, the call ended): it leaves at once, no fade.
const hadLine = useRef(false);
useLayoutEffect(() => { if (hadLine.current && !her) how.current = 'instant'; hadLine.current = !!herLine; }, [her, herLine]);
const signature = pages.map(p => p.key).join('|');
// Her spoken line can take in her next sentence under the same key, so its words count there too.
const signature = pages.map(p => p.message.live === 'speaking' || p.message.id.startsWith('voice-') ? `${p.key}=${p.text}` : p.key).join('|');
useLayoutEffect(() => {
lines.current?.present(pages, cursor, how.current, name, !motionOff());
how.current = 'advance';
@@ -360,7 +361,7 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
<aside className="record log-panel glass read" hidden={!log} role="dialog" aria-modal="false" aria-labelledby="record-title"><header><div><p className="eyebrow">{real ? '服务器聊天记录' : '完整记录 · 本机演示'}</p><h2 id="record-title">你们说过的话</h2></div><button className="btn-round sm" ref={logClose} aria-label="关闭记录" onClick={() => setLog(false)}><Icon name="x"/></button></header>
<div className="scroll" ref={logRef}><p className="guide">内容完整保留;关闭后回到刚才那一句,自动呈现会接着走。</p>{record.map(m => <article key={m.id} data-life={m.lifeIds.join(' ') || undefined} data-mid={m.id} data-role={m.role} className={`message ${m.status === 'failed' ? 'fail' : ''} ${(focusLife && m.lifeIds.includes(focusLife)) || focusIds.includes(m.id) ? 'hl' : ''}`}><div className="author"><i/>{m.role === 'user' ? '你' : name}{m.proactive && <span className="tagm">她主动说的</span>}</div><p>{m.text}</p>{m.status === 'failed' && <button className="btn-text" onClick={() => void send(m)}>没发出去 · 重试</button>}{m.status === 'cancelled' && <span className="incomplete">已取消</span>}{m.live === 'cancelled' && <span className="incomplete">已停止 · 这是未完成片段,未存入聊天记录</span>}</article>)}{reply && <article className="message" data-role="companion"><div className="author"><i/>{name}</div><p>{reply}</p><span className="incomplete">还在说…</span></article>}{herLine && !herLine.proactive && <article className="message" data-role="companion"><div className="author"><i/>{name}</div><p>{herLine.text}</p><span className="incomplete">{herOpen ? '还在说…' : '语音刚说完 · 正在读回聊天记录'}</span></article>}</div></aside>
{full && fullMessage && <aside className="record full glass read" role="dialog" aria-modal="false" aria-labelledby="full-title"><header><div><p className="eyebrow">{fullMessage.role === 'user' ? '你' : name} · 全文</p><h2 id="full-title">这一段,慢慢看</h2></div><button className="btn-round sm" ref={fullClose} aria-label="关闭全文" onClick={() => setFull(false)}><Icon name="x"/></button></header>
<div className="scroll"><p className="guide">整段完整可读。关闭后回到刚才那一句。</p><article className="message" data-role={fullMessage.role}><div className="author"><i/>{fullMessage.role === 'user' ? '你' : name}</div><p>{fullMessage.text}</p>{fullMessage.live === 'generating' && <span className="incomplete">还在说…</span>}{fullMessage.live === 'cancelled' && <span className="incomplete">这段回复已停止,内容未完成,未存入聊天记录。</span>}</article></div></aside>}
<div className="scroll"><p className="guide">整段完整可读。关闭后回到刚才那一句。</p><article className="message" data-role={fullMessage.role}><div className="author"><i/>{fullMessage.role === 'user' ? '你' : name}</div><p>{fullMessage.text}</p>{(fullMessage.live === 'generating' || fullMessage.live === 'speaking') && <span className="incomplete">还在说…</span>}{fullMessage.live === 'cancelled' && <span className="incomplete">这段回复已停止,内容未完成,未存入聊天记录。</span>}</article></div></aside>}
{real && permission === 'mic' && <Modal title={`开始和${name}语音?`} onClose={() => { setPermission(''); setNotice('没有开启语音,文字仍可使用。'); }} confirm="开始语音" onConfirm={() => { setPermission(''); setNotice(''); void voiceCtl.current?.start(); }}>浏览器会请求麦克风权限。你的声音只送到这台服务器上{name}的语音服务,她用同一份记忆、同一段聊天回应你;你说的话和她的回答照常存进聊天记录。直接开口就能打断她。结束语音、离开交谈或关上页面时,麦克风立即关闭。<br/><small className="voice-note">语音通路还没有经过真机验收,效果可能不稳定。</small></Modal>}
{!real && permission && <Modal title={permission === 'mic' ? '开启模拟语音?' : '打开模拟视觉窗?'} onClose={() => { setPermission(''); setDenied(true); setNotice('没有开启。真实服务尚未接通,文字仍可使用。'); }} confirm="开始模拟" onConfirm={() => { if (permission === 'mic') { setDenied(false); setVoice(true); onVoice(true); voiceController.current = new AbortController(); onPresence('在听你说(模拟)'); setNotice('模拟语音没有收音,可继续用文字输入。'); } else { if (fail) { onObservation('模拟 · 看不清,视觉服务未接通'); setNotice('模拟观察失败,文字仍可使用。'); } else setVision(true); } setPermission(''); }}>本次仅模拟界面状态,不申请麦克风或摄像头权限,不采集声音或影像,也不向外接服务发送请求。</Modal>}
</>;
+12
View File
@@ -14,6 +14,7 @@ export class LineStage {
const el = document.createElement('div');
el.className = 'line' + (current ? ' is-current' : ' is-prev');
el.dataset.role = page.message.role; el.dataset.key = page.key;
if (page.message.live === 'speaking') el.dataset.spoken = '1';
const who = document.createElement('span'); who.className = 'by';
const dot = document.createElement('i'), label = document.createElement('b'), state = document.createElement('em');
label.textContent = page.message.role === 'user' ? '你' : name; label.title = label.textContent; state.className = 'state';
@@ -38,6 +39,15 @@ export class LineStage {
{ duration: quick ? 240 : 520, easing: EASE, fill: 'forwards' }).finished.then(() => node.remove()).catch(() => node.remove());
}
clear() { this.stage.replaceChildren(); }
// Her spoken line took in the sentence she said next: the words already there stay as they are and only the new
// ones ink in after them (no motion: they just appear). Anything that is not a plain continuation is set at once.
private grow(node: HTMLElement, text: string, animate: boolean) {
const p = node.querySelector('p'); if (!p) return;
const was = p.textContent || ''; if (was === text) return;
if (!animate || !text.startsWith(was)) { p.className = ''; p.textContent = text; return; }
if (p.className !== 'ink') { p.append(text.slice(was.length)); return; }
graphemes(text.slice(was.length)).forEach((c, i) => { const s = document.createElement('span'); s.style.setProperty('--i', String(Math.min(i, 48))); s.textContent = c; p.append(s); });
}
// Shows the current page with the one before it. Returns early when the same lines are already on screen, so
// a growing stream, a status change or a re-render never replays anything.
present(pages: Page[], cursor: number, how: PresentHow, name: string, animate: boolean) {
@@ -46,6 +56,8 @@ export class LineStage {
const prev = pages[cursor - 1], want = [prev, page].filter((p): p is Page => !!p);
const have = [...stage.querySelectorAll<HTMLElement>('.line:not(.leaving)')], keys = have.map(n => n.dataset.key);
const inkFor = (p: Page) => p === page && animate && p.message.role === 'companion' && !this.inked.has(p.key);
// A line first shown while she was saying it keeps growing under its key (her final, then her stored row).
for (const p of want) { const n = have.find(x => x.dataset.key === p.key && x.dataset.spoken); if (n) this.grow(n, p.text, animate); }
if (how === 'instant' || !animate) {
// Keyboard review and reduced motion: show the target lines as they are — no slide, no re-played ink.
if (keys.join() === want.map(p => p.key).join() && how !== 'instant') return;
+14 -5
View File
@@ -2,8 +2,8 @@ import type { Message } from '../domain/model';
// Reading logic carried over from the verified HEL-793/795 prototype (PR#8) and HEL-799 (approved 01a16810), moved
// onto the real message flow: replies are shown one or two lines at a time and flow on by themselves.
// A message as the stage sees it: stored messages plus, at most, the reply still being written or cut off.
export interface ShownMessage extends Message { live?: 'generating' | 'cancelled' }
// A message as the stage sees it: stored messages plus, at most, the reply still being written, spoken or cut off.
export interface ShownMessage extends Message { live?: 'generating' | 'speaking' | 'cancelled' }
export interface Turn { key: string; items: ShownMessage[] }
export interface Page { key: string; text: string; index: number; last: boolean; mi: number; message: ShownMessage }
export interface Metrics { width: number; font: number; compact: boolean }
@@ -42,16 +42,23 @@ export function chunks(text: string, { width, font, compact }: Metrics): string[
return out;
}
// The finished sentences at the start of a line (with their closing marks); '' while the first is still forming.
const SAID = /^[\s\S]*[。!?!?…][」』))”’"]*/u;
export const said = (line: string) => SAID.exec(line)?.[0] ?? '';
export function pagesOf(turn: Turn | undefined, metrics: Metrics): Page[] {
const list: Page[] = [];
if (!turn) return list;
turn.items.forEach((message, mi) => {
const parts = chunks(message.text, metrics);
const parts = chunks(message.text, metrics), shown = parts.slice();
// The newest chunk of a reply still being written is held back (it may still grow or merge with the next
// sentence), so a line never changes or re-animates after it has appeared.
const held = message.live === 'generating' && parts.length ? 1 : 0;
if (message.live === 'generating') shown.pop();
// Her reply while she speaks it: the newest chunk shows the sentences she has already finished. It may still
// take the next short sentence in (it only ever grows, see LineStage.grow); the words still forming wait.
else if (message.live === 'speaking' && shown.length) { const done = said(shown.pop()!); if (done) shown.push(done); }
// Keys follow the turn and position, not the message id, so a streamed reply keeps its lines when it is stored.
for (let index = 0; index < parts.length - held; index++) list.push({ key: `${turn.key}:${mi}:${index}`, text: parts[index], index, last: index === parts.length - 1, mi, message });
shown.forEach((text, index) => list.push({ key: `${turn.key}:${mi}:${index}`, text, index, last: index === parts.length - 1, mi, message }));
});
return list;
}
@@ -75,6 +82,8 @@ export class ReadingClock {
const dt = this.last ? Math.min(STALL, Math.max(0, now - this.last)) : 0; this.last = now;
if (!page) return false;
if (page.key !== this.key) { this.key = page.key; this.dwell = 0; this.total = dwellFor(page); }
// A spoken line that took in her next sentence gets the extra time it now needs (never less).
else this.total = Math.max(this.total, dwellFor(page));
if (running && this.dwell < this.total) this.dwell = Math.min(this.total, this.dwell + dt);
return running && this.dwell >= this.total;
}
+11 -3
View File
@@ -20,7 +20,7 @@ interface LkRoom {
}
export interface Livekit {
Room: new (options?: Record<string, unknown>) => LkRoom;
RoomEvent: Record<'TrackSubscribed' | 'TrackUnsubscribed' | 'ParticipantConnected' | 'ParticipantAttributesChanged' | 'DataReceived' | 'Disconnected' | 'AudioPlaybackStatusChanged', string>;
RoomEvent: Record<'TrackSubscribed' | 'TrackUnsubscribed' | 'ParticipantConnected' | 'ParticipantDisconnected' | 'ParticipantAttributesChanged' | 'DataReceived' | 'Disconnected' | 'AudioPlaybackStatusChanged', string>;
Track: { Source: { Microphone: string } };
ParticipantKind?: { AGENT?: number };
createLocalAudioTrack(options?: MediaTrackConstraints): Promise<LkTrack>;
@@ -57,6 +57,8 @@ export function livekitTransport(lk: Livekit): VoiceTransport {
const holder = document.createElement('div'), E = lk.RoomEvent;
holder.hidden = true; holder.dataset.voice = 'her'; document.body.append(holder);
let closing = false, hushed = false;
// Her worker as seen in this room (by identity), so its leaving is recognised even if its attributes are gone.
const agents = new Set<string>(), joined = (p: LkParticipant) => { agents.add(p.identity); on.agentJoined(); };
const players = () => [...holder.querySelectorAll<HTMLMediaElement>('audio,video')];
const close = async () => {
if (closing) return; closing = true;
@@ -66,7 +68,13 @@ export function livekitTransport(lk: Livekit): VoiceTransport {
};
room.on(E.TrackSubscribed, ((track: LkTrack) => { if (closing || track.kind !== 'audio') return; const el = track.attach(); el.muted = hushed; holder.append(el); }) as (...a: never[]) => void);
room.on(E.TrackUnsubscribed, ((track: LkTrack) => { track.detach().forEach(el => el.remove()); }) as (...a: never[]) => void);
room.on(E.ParticipantConnected, ((p: LkParticipant) => { if (!closing && isAgent(p)) on.agentJoined(); }) as (...a: never[]) => void);
room.on(E.ParticipantConnected, ((p: LkParticipant) => { if (!closing && isAgent(p)) joined(p); }) as (...a: never[]) => void);
// Only her worker leaving ends the call (anyone else coming and going does not); our own closing says nothing.
room.on(E.ParticipantDisconnected, ((p: LkParticipant) => {
if (closing || !(agents.has(p.identity) || isAgent(p))) return;
agents.delete(p.identity);
if (![...room.remoteParticipants.values()].some(o => o.identity !== p.identity && isAgent(o))) on.agentLeft();
}) as (...a: never[]) => void);
room.on(E.ParticipantAttributesChanged, ((changed: Record<string, string>, p: LkParticipant) => { if (!closing && AGENT_STATE in changed && isAgent(p)) on.agentState(changed[AGENT_STATE]); }) as (...a: never[]) => void);
room.on(E.DataReceived, ((payload: Uint8Array, _p: unknown, _kind: unknown, topic?: string) => {
if (closing || topic !== SUBTITLES) return;
@@ -80,7 +88,7 @@ export function livekitTransport(lk: Livekit): VoiceTransport {
catch (e) { await close(); throw e; }
if (signal.aborted) { await close(); throw new DOMException('ended', 'AbortError'); }
signal.removeEventListener('abort', abort);
room.remoteParticipants.forEach(p => { if (!isAgent(p)) return; on.agentJoined(); const state = p.attributes?.[AGENT_STATE]; if (state) on.agentState(state); });
room.remoteParticipants.forEach(p => { if (!isAgent(p)) return; joined(p); const state = p.attributes?.[AGENT_STATE]; if (state) on.agentState(state); });
void room.startAudio().catch(() => {}).then(() => { if (!closing && !room.canPlaybackAudio) on.audioBlocked(true); });
const voiceRoom: VoiceRoom = {
async publish(mic) { const track = tracks.get(mic); if (!track) throw new Error('unknown microphone'); await room.localParticipant.publishTrack(track, { source: lk.Track.Source.Microphone }); },
+14 -8
View File
@@ -56,6 +56,8 @@ export function subtitle(v: unknown): Subtitle | null {
export interface MicTrack { stop(): void; onEnded(cb: () => void): void }
export interface RoomEvents {
agentJoined(): void;
// Her worker left the room while it stays open (its job ended or crashed): nobody is answering any more.
agentLeft(): void;
// The worker's own state attribute (lk.agent.state): initializing / listening / thinking / speaking.
agentState(state: string): void;
subtitle(payload: unknown): void;
@@ -81,6 +83,7 @@ export const WORDS = {
client: '语音组件没有加载出来,文字仍可使用。',
unreachable: '通话服务暂时连不上,稍后再试试。',
noAgent: '她没有接上这次通话,麦克风已经关闭。文字仍可使用。',
agentLeft: '她那边的语音中断了,这次通话已结束,麦克风已经关闭。文字仍可使用。',
dropped: '通话断开了,麦克风已经关闭。文字仍可使用。',
micGone: '麦克风被关掉了,语音已结束。',
offline: '网络断开了,语音已结束,麦克风已关闭。',
@@ -100,9 +103,9 @@ export interface VoiceDeps {
}
// seq: the highest subtitle sequence applied in this call (one worker job, one sequence). speech: her speech open now;
// closed: speeches that ended, were cancelled or were superseded here; nothing for them is shown again.
interface Live { gen: number; abort: AbortController; mic?: MicTrack; room?: VoiceRoom; session?: string; agent: boolean; stated: boolean; hushed: boolean; timer?: ReturnType<typeof setTimeout>; seq: number; speech: string; pro: boolean; message?: number; closed: string[] }
const CLOSED_KEPT = 64;
// closed: speeches that ended, were cancelled or were superseded in this call; nothing for them is shown again. It is
// kept for the whole call (no window a long call could push a retired speech out of) and goes with the call.
interface Live { gen: number; abort: AbortController; mic?: MicTrack; room?: VoiceRoom; session?: string; agent: boolean; stated: boolean; hushed: boolean; timer?: ReturnType<typeof setTimeout>; seq: number; speech: string; pro: boolean; message?: number; closed: Set<string> }
const AGENT_PHASE: Record<string, VoicePhase> = { initializing: 'joining', listening: 'listening', thinking: 'thinking', speaking: 'speaking' };
@@ -152,7 +155,7 @@ export class VoiceController {
// The generation is taken before anything is awaited, so a start that wakes up after a newer one never takes
// the call over; the call it replaces is released first, as end() would.
const prev = this.live;
const gen = ++this.gen, live: Live = { gen, abort: new AbortController(), agent: false, stated: false, hushed: false, seq: 0, speech: '', pro: false, closed: [] };
const gen = ++this.gen, live: Live = { gen, abort: new AbortController(), agent: false, stated: false, hushed: false, seq: 0, speech: '', pro: false, closed: new Set() };
this.live = live;
this.view = { ...OFF, phase: 'opening' }; this.deps.onView(this.view);
const stale = () => gen !== this.gen;
@@ -203,6 +206,9 @@ export class VoiceController {
this.show({ phase: 'joining' }, 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
// failure does (her line, microphone, her audio, room and server room all go; an unsent DELETE is owed).
agentLeft: () => { if (!stale() && live.agent) void fail(WORDS.agentLeft); },
agentState: state => {
if (stale()) return;
const phase = AGENT_PHASE[state]; if (!phase) return;
@@ -267,7 +273,7 @@ export class VoiceController {
}
const pro = s.kind.startsWith('proactive_');
if (s.kind === 'turn_start' || s.kind === 'proactive_start') {
if (live.closed.includes(s.speech) || live.speech === s.speech) return;
if (live.closed.has(s.speech) || live.speech === s.speech) return;
if (live.speech) this.close(live, live.speech);
live.speech = s.speech; live.pro = pro; live.message = s.messageId;
// A reach-out arrives whole (its stored text); a reply starts empty and grows.
@@ -306,7 +312,7 @@ export class VoiceController {
}
private close(live: Live, speech: string) {
if (live.speech === speech) { live.speech = ''; live.pro = false; live.message = undefined; }
if (!live.closed.includes(speech)) { live.closed.push(speech); if (live.closed.length > CLOSED_KEPT) live.closed.shift(); }
live.closed.add(speech);
}
// You sent text while she was answering by voice: the server cancels her voice turn; keep its last audio silent.
@@ -384,8 +390,8 @@ export function voiceLine(her: HerLine | null, messages: Message[], since: numbe
if (her.state !== 'open' && messages.slice(since).some(m => !own(m))) return null;
// A reach-out keeps its stored row's identity (id, turn), so the row taking over keeps the same lines on the stage.
const row = her.proactive ? [...messages, ...incoming].find(own) : undefined;
// Her reply still growing holds back its newest line, as a streamed text reply does.
return { id: row?.id ?? `voice-${her.speech}`, role: 'companion', text: her.text, lifeIds: [], turnId: row ? row.turnId : her.turnId, ...(her.proactive ? { proactive: true } : {}), ...(her.state === 'open' && !her.proactive ? { live: 'generating' as const } : {}) };
// Her reply while she says it: every sentence she has finished is on the stage, only the one still forming waits.
return { id: row?.id ?? `voice-${her.speech}`, role: 'companion', text: her.text, lifeIds: [], turnId: row ? row.turnId : her.turnId, ...(her.proactive ? { proactive: true } : {}), ...(her.state === 'open' && !her.proactive ? { live: 'speaking' as const } : {}) };
}
// Newest rows down to `since` (exclusive), at most `pages` pages of 50. Voice turns are few per read; a longer gap is