HEL-875: 接上真实主动留言,保全视觉总监原始补丁

Apply the exact eight-file HEL-875 patch from the visual director on 31970c4. Independently reran 49 frontend tests, typecheck/lint/build and original Python requirement checks. Candidate only; intake found pagination overflow dropping older reach-outs after >250 new records, requiring author repair before approval or deployment.

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
2026-10-26 22:08:58 +08:00
co-authored by multica-agent
parent 31970c4dd3
commit 1ae243f286
8 changed files with 518 additions and 15 deletions
+60
View File
@@ -0,0 +1,60 @@
import type { Message } from '../domain/model';
import { api, toMessage, within, type MessagePage } from './real';
// ── Her own messages arriving while the page is open (R4 reach-out, CG-011). ──
// The server keeps every reach-out as a chat_message row with proactive=1 and serves it from GET /api/messages with
// ascending ids; there is no push channel, so an open page reads the newest rows now and then. Only text inside the
// page: no microphone, notification or push permission is ever asked for.
// Server ids are positive integers; local, not yet confirmed messages carry random ids and never count.
export const serverId = (m: Message) => /^[1-9]\d{0,18}$/u.test(m.id) ? Number(m.id) : 0;
export const newestId = (messages: Message[]) => messages.reduce((top, m) => Math.max(top, serverId(m)), 0);
const newestProactive = (messages: Message[]) => messages.reduce((top, m) => m.proactive ? Math.max(top, serverId(m)) : top, 0);
// Rows newer than `after`, oldest first. Pages back only as far as needed (a long absence on a sleeping tab), bounded.
export async function fetchAfter(after: number, signal: AbortSignal, pages = 5): Promise<{ rows: Message[]; newest: number }> {
const rows: Message[] = [];
let before: number | null = null, newest = after;
for (let i = 0; i < pages; i++) {
const page: MessagePage = await api(`messages?limit=50${before ? `&before=${before}` : ''}`, { signal: within(signal, 10000) });
const list = Array.isArray(page.messages) ? page.messages.filter(m => Number.isSafeInteger(m?.id) && m.id > 0 && typeof m.text === 'string') : [];
for (const m of list) newest = Math.max(newest, m.id);
const fresh = list.filter(m => m.id > after);
rows.unshift(...fresh.map(toMessage));
// Reached what the page already holds (or the start of the record): stop.
if (fresh.length < list.length || !page.next_before || !after) break;
before = page.next_before;
}
return { rows, newest };
}
// What may be added from a poll: her own reach-out rows the page does not hold yet. Your own turns (and her replies to
// them) are already on the page under their turn ids and come in through the chat stream, so they are never added
// twice; a repeated read, a reconnect or a restarted server epoch returns the same ids and adds nothing.
export function arrivals(known: Message[], rows: Message[]): Message[] {
const ids = new Set(known.map(m => m.id)), turns = new Set(known.flatMap(m => m.turnId ? [`${m.role}:${m.turnId}`] : []));
const out: Message[] = [];
for (const m of [...rows].sort((a, b) => serverId(a) - serverId(b))) {
if (!m.proactive || m.role !== 'companion' || m.status !== 'sent' || !m.text.trim() || ids.has(m.id) || (m.turnId && turns.has(`companion:${m.turnId}`))) continue;
ids.add(m.id); out.push(m);
}
return out;
}
// ── Unread. One rule: a reach-out that is in the page's record is read once you are in the conversation with the
// page visible (one plays on the stage; several open the record at the first). One still queued is not. The mark is
// the newest seen id, kept in this browser only; it never changes the server. ──
const SEEN = 'cg.real.seen';
export function storedSeen(): number | null {
try { const raw = localStorage.getItem(SEEN); if (raw === null || !/^\d{1,19}$/u.test(raw)) return null; const v = Number(raw); return Number.isSafeInteger(v) ? v : null; } catch { return null; }
}
export function storeSeen(id: number) { try { localStorage.setItem(SEEN, String(id)); } catch { /* The mark stays in memory for this visit. */ } }
// First visit from this browser: everything already in the record is history, not "just arrived".
export function initialSeen(messages: Message[]): number {
const stored = storedSeen();
if (stored !== null) return stored;
const seen = newestProactive(messages);
storeSeen(seen);
return seen;
}
export const unreadOf = (messages: Message[], seen: number) => messages.filter(m => m.proactive && serverId(m) > seen);
export const seenThrough = newestProactive;
+8 -5
View File
@@ -121,7 +121,7 @@ export interface PersonaView {
export const loadPersona = (signal: AbortSignal) => api<PersonaView>('persona', { signal: within(signal, 10000) });
// Creation-time generation is bounded server-side (one model call, 30 s cap); give the explicit retry room for it.
export const retryPersona = (signal: AbortSignal) => api<PersonaView>('persona/retry', { method: 'POST', signal: within(signal, 90000) });
function within(signal: AbortSignal, ms: number) {
export function within(signal: AbortSignal, ms: number) {
const c = new AbortController(), stop = () => c.abort(), timer = setTimeout(stop, ms);
signal.addEventListener('abort', () => { clearTimeout(timer); stop(); }, { once: true });
return c.signal;
@@ -144,15 +144,18 @@ export async function loadReal(): Promise<DemoState | null> {
try { settings.reduced = JSON.parse(localStorage.getItem('cg.real.display') || '{}').reduced === true; } catch { /* Invalid local preference does not affect server data. */ }
return { version: 1, identity, settings, events: [], memories: [], messages: await loadMessages(), lastVisit: Date.now() };
}
export interface ServerMessage { id: number; role: Message['role']; text: string; turn_id: string; status: Message['status']; lifeIds?: number[]; proactive?: boolean }
export interface MessagePage { messages: ServerMessage[]; next_before: number | null; epoch?: number }
// lifeIds arrive already trimmed by the server to records she has told; older servers omit them.
// proactive arrives only on her own persisted reach-out rows (R4); older servers omit it.
export const toMessage = (m: ServerMessage): Message => ({ id: String(m.id), role: m.role, text: m.text, lifeIds: ints(m.lifeIds) ? m.lifeIds.map(String) : [], turnId: m.turn_id, status: m.status, ...(m.proactive === true ? { proactive: true } : {}) });
export async function loadMessages(): Promise<Message[]> {
// Cursor pages are bounded by the server. All pages restore in deterministic id order.
const messages: Message[] = [];
let before: number | null = null;
do {
const page: { messages: { id: number; role: Message['role']; text: string; turn_id: string; status: Message['status']; lifeIds?: number[]; proactive?: boolean }[]; next_before: number | null } = await api(`messages?limit=200${before ? `&before=${before}` : ''}`);
// lifeIds arrive already trimmed by the server to records she has told; older servers omit them.
// proactive arrives only on her own persisted reach-out rows (R4); older servers omit it.
messages.unshift(...page.messages.map(m => ({ id: String(m.id), role: m.role, text: m.text, lifeIds: ints(m.lifeIds) ? m.lifeIds.map(String) : [], turnId: m.turn_id, status: m.status, ...(m.proactive === true ? { proactive: true } : {}) })));
const page: MessagePage = await api(`messages?limit=200${before ? `&before=${before}` : ''}`);
messages.unshift(...page.messages.map(toMessage));
before = page.next_before;
} while (before);
return messages;
+57 -5
View File
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { api, lifeStatus, loadReal, memoryNote, type Health } from '../adapters/real';
import { arrivals, fetchAfter, initialSeen, newestId, seenThrough, storeSeen, unreadOf } from '../adapters/inbox';
import type { DemoState, Message, Theme } from '../domain/model';
import { Presenter } from '../stage/Presenter';
import { CreationWizard } from '../manage/CreationWizard';
@@ -16,9 +17,14 @@ export function RealApp() {
const [theme, setTheme] = useState<Theme>(() => { try { return localStorage.getItem('cg.theme') === 'fog' ? 'fog' : 'moon'; } catch { return 'moon'; } });
const [herFocus, setHerFocus] = useState(0);
const latest = useRef(state); latest.current = state;
// ── Her reach-outs while the page is open (inbox.ts). `cursor` is the newest server row this page has read;
// `incoming` holds what arrived during a conversation until the stage lets it in; `seen` is the unread mark. ──
const cursor = useRef(0), [incoming, setIncoming] = useState<Message[]>([]), held = useRef(incoming); held.current = incoming;
const [seen, setSeen] = useState(0), [fresh, setFresh] = useState<Message | null>(null), [visible, setVisible] = useState(!document.hidden);
const areaNow = useRef(area); areaNow.current = area;
const initialize = useCallback(async () => {
setError(''); setReady(false);
try { setHealth(await api<Health>('health')); const next = await loadReal(); setState(next); setCreating(!next); setReady(true); }
try { setHealth(await api<Health>('health')); const next = await loadReal(); cursor.current = next ? newestId(next.messages) : 0; setSeen(next ? initialSeen(next.messages) : 0); setState(next); setCreating(!next); setReady(true); }
catch (e) { setError((e as Error).message || '暂时连不上真实服务。'); }
}, []);
useEffect(() => { void initialize(); }, [initialize]);
@@ -28,6 +34,50 @@ export function RealApp() {
useEffect(() => { document.body.className = [creating ? 'creating' : '', area === 'talk' ? 'talk' : '', ['days', 'settings'].includes(area) ? 'paned' : '', log ? 'log' : ''].join(' '); }, [area, creating, log]);
useEffect(() => { document.documentElement.classList.toggle('reduced', !!state?.settings.reduced); }, [state?.settings.reduced]);
const changeMessages = useCallback((messages: Message[]) => { if (latest.current) { const next = { ...latest.current, messages }; latest.current = next; setState(next); } }, []);
// Read the newest rows every 20 s while the page is shown, at once on return or reconnect. A failed read is quiet
// (the next one simply tries again, slower); nothing on screen changes until a new row actually exists.
const live = !!state && !creating && ready;
useEffect(() => {
if (!live) return;
let timer: ReturnType<typeof setTimeout> | undefined, running = false, failures = 0, stopped = false, controller = new AbortController();
const poll = async () => {
if (running || stopped || document.hidden) return;
running = true; clearTimeout(timer); controller = new AbortController();
try {
const { rows, newest } = await fetchAfter(cursor.current, controller.signal);
if (stopped) return;
cursor.current = Math.max(cursor.current, newest); failures = 0;
const add = latest.current ? arrivals([...latest.current.messages, ...held.current], rows) : [];
if (add.length && latest.current) {
if (areaNow.current === 'talk') setIncoming(list => [...list, ...add]);
else { changeMessages([...latest.current.messages, ...add]); setFresh(add[add.length - 1]); }
}
} catch { failures++; }
finally { running = false; if (!stopped) timer = setTimeout(() => void poll(), failures ? Math.min(120000, 20000 * 2 ** failures) : 20000); }
};
const wake = () => { setVisible(!document.hidden); if (!document.hidden) void poll(); };
document.addEventListener('visibilitychange', wake); addEventListener('online', wake);
timer = setTimeout(() => void poll(), 20000);
return () => { stopped = true; controller.abort(); clearTimeout(timer); document.removeEventListener('visibilitychange', wake); removeEventListener('online', wake); };
}, [live, changeMessages]);
// Leaving the conversation before the stage let them in: they join the record and stay unread.
useEffect(() => { if (area !== 'talk' && incoming.length && latest.current) { const ids = new Set(latest.current.messages.map(m => m.id)); changeMessages([...latest.current.messages, ...incoming.filter(m => !ids.has(m.id))]); setIncoming([]); } }, [area, incoming, changeMessages]);
const admitted = useCallback((ids: string[]) => setIncoming(list => list.filter(m => !ids.includes(m.id))), []);
// The one unread rule: on the conversation with the page visible, what the page's record holds has been seen
// (a message still queued in `incoming` is not in it yet).
useEffect(() => {
if (area !== 'talk' || !visible || !state) return;
const top = seenThrough(state.messages);
if (top > seen) { setSeen(top); storeSeen(top); }
setFresh(null);
}, [area, visible, state, seen]);
const unread = useMemo(() => state ? unreadOf(state.messages, seen) : [], [state, seen]);
// On 此刻 the letter already carries her words; the card speaks up only over 日子 and 设置. It keeps its words while
// it fades out.
const card = !!fresh && (area === 'days' || area === 'settings'), shownFresh = useRef<Message | null>(null); if (fresh) shownFresh.current = fresh;
useEffect(() => { if (fresh && !unread.some(m => m.id === fresh.id)) setFresh(null); }, [fresh, unread]);
// Reply to her: one new message plays on the stage; several open the record at the first one you have not seen.
const openUnread = () => { setFresh(null); const first = unread[0]; leaveSettingsThen(() => { setArea('talk'); setFocusLife(''); setLog(unread.length > 1); setFocusIds(unread.length > 1 && first ? [first.id] : []); }); };
const ignoreVoice = useCallback(() => {}, []);
// Status words follow the server, re-read when you open a page that shows them; a failed read keeps the last one.
const life = lifeStatus(health);
@@ -53,10 +103,12 @@ export function RealApp() {
{!ready ? <main className="entry"><div className="card glass"><h1>一扇亮着的窗。</h1><Status text={error || '正在读取服务器档案…'} error={!!error}/>{error && <><p>请检查真实服务是否可达。资料仍在服务器保存。</p><Button primary onClick={() => void initialize()}>重新连接</Button></>}</div></main> : <>
{creating && <CreationWizard real fail={false} onCreate={setState} onEnter={() => setCreating(false)}/>}
{!creating && state && <>
{area === 'now' && <main className="home"><div className="eyebrow">一扇亮着的窗</div><h1 className="whisper">慢慢说,我在这里。</h1><div className="meta"><span><Icon name="heart"/>{state.identity.relation} · 慢慢熟悉</span></div><button className="away" onClick={() => navigate('days')}>日子与回忆 · {life.label} <Icon name="next"/></button>{lastReply && <button className="letter glass" onClick={() => { navigate('talk'); setLog(true); }}><span className="lh"><b>最近说过的话</b><span>打开完整记录</span></span><p>{lastReply.text}</p></button>}<div className="cta"><Button primary small={false} onClick={() => navigate('talk')}><Icon name="chat"/>和她说话</Button></div><p className="first-note">{memoryNote(health, life)}</p>{health && !health.llm.ok && <Status error text="模型暂时不可达,档案和历史仍可查看。"/>}</main>}
{area === 'talk' && <ChatPanel real state={state} onChange={changeMessages} onPresence={setPresence} onVoice={ignoreVoice} onObservation={ignoreVoice} onRecord={setRecord} offline={false} fail={false} log={log} setLog={setLog} focusLife={focusLife} focusIds={focusIds} onReceipt={acknowledged}/>}
{area === 'now' && <main className="home"><div className="eyebrow">一扇亮着的窗</div><h1 className="whisper">慢慢说,我在这里。</h1><div className="meta"><span><Icon name="heart"/>{state.identity.relation} · 慢慢熟悉</span></div><button className="away" onClick={() => navigate('days')}>日子与回忆 · {life.label} <Icon name="next"/></button>{unread.length ? <button className="letter glass" onClick={openUnread}><span className="lh"><b>她留给你的</b><span>{unread.length > 1 ? `${unread.length} 句还没看` : '还没看'}</span></span><p>{unread[unread.length - 1].text}</p></button> : lastReply && <button className="letter glass read" onClick={() => { navigate('talk'); setLog(true); }}><span className="lh"><b>最近说过的话</b><span>打开完整记录</span></span><p>{lastReply.text}</p></button>}<div className="cta"><Button primary small={false} onClick={() => navigate('talk')}><Icon name="chat"/>和她说话</Button></div><p className="first-note">{memoryNote(health, life)}</p>{health && !health.llm.ok && <Status error text="模型暂时不可达,档案和历史仍可查看。"/>}</main>}
{area === 'talk' && <ChatPanel real state={state} onChange={changeMessages} onPresence={setPresence} onVoice={ignoreVoice} onObservation={ignoreVoice} onRecord={setRecord} offline={false} fail={false} log={log} setLog={setLog} focusLife={focusLife} focusIds={focusIds} onReceipt={acknowledged} incoming={incoming} onAdmit={admitted}/>}
<LifePanel real state={state} open={area === 'days'} now={life.now} life={life} ackAt={ackAt} onClose={() => navigate('now')} onChat={openTold} onSaid={openSaid} onSettings={() => { navigate('settings'); setHerFocus(n => n + 1); }}/>
<ManagePanel real state={state} open={area === 'settings'} now={life.now} life={life} focus={herFocus} onClose={() => navigate('now')} onSave={setState} fail={false} theme={theme} setTheme={setTheme}/>
<nav className="nav glass" aria-label="主导航">{[['now','moon','此刻'],['talk','chat','交谈'],['days','book','日子'],['settings','gear','设置']].map(([id, icon, label]) => <button key={id} className="nav-item" aria-current={area === id ? 'page' : undefined} onClick={() => navigate(id)}><Icon name={icon}/>{label}</button>)}</nav></>}
{/* Same card as the approved demo reach-out, now with her real words; it never opens the conversation by itself. */}
<aside className={`reach glass ${card ? 'show' : ''}`} aria-hidden={!card} ref={el => { el?.toggleAttribute('inert', !card); }}>{shownFresh.current && <><div className="rh"><b>{state.identity.name}</b>主动说的</div><p>{shownFresh.current.text}</p><div className="acts"><Button primary onClick={openUnread}>回她</Button><Button onClick={() => setFresh(null)}>稍后再看</Button></div></>}</aside>
<nav className="nav glass" aria-label="主导航">{[['now','moon','此刻'],['talk','chat','交谈'],['days','book','日子'],['settings','gear','设置']].map(([id, icon, label]) => <button key={id} className={`nav-item ${id === 'talk' && (unread.length || incoming.length) ? 'unread' : ''}`} aria-current={area === id ? 'page' : undefined} aria-label={id === 'talk' && unread.length ? `${label},她有 ${unread.length} 句新留言` : undefined} onClick={() => navigate(id)}><Icon name={icon}/>{label}<i className="badge"/></button>)}</nav></>}
</>}</>;
}
+17 -5
View File
@@ -15,11 +15,14 @@ const START: Anchor = { mi: 0, offset: 0 };
const metricsFor = (width: number): Metrics => { const compact = document.documentElement.classList.contains('compact'); return { width, font: compact ? 16 : innerWidth <= 720 ? 18 : 23, compact }; };
const typingTarget = (el: Element | null) => !!el && (el.matches('textarea,input,select,[contenteditable="true"]'));
const NO_IDS: string[] = [];
export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation, onRecord, offline, fail, log, setLog, focusLife, focusIds = NO_IDS, real = false, onReceipt }: {
const NO_IDS: string[] = [], NO_MESSAGES: Message[] = [];
export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation, onRecord, offline, fail, log, setLog, focusLife, focusIds = NO_IDS, real = false, onReceipt, incoming = NO_MESSAGES, onAdmit }: {
real?: boolean;
// Real only: the server accepted a complete-receipt confirmation (the life it may unlock is decided later).
onReceipt?: () => void;
// Real only: her own messages that reached the open page while you are here, not yet on the stage.
incoming?: Message[];
onAdmit?: (ids: string[]) => void;
state: DemoState;
onChange: (messages: Message[]) => void;
onPresence: (p: string) => void;
@@ -72,6 +75,11 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
if (cursor > headIndex) head.current = anchor;
const held = useRef(new Set<string>()), clock = useRef(new ReadingClock());
const reading = useRef({ pages, cursor, flow }); reading.current = { pages, cursor, flow };
// Her own message that arrives while you are here waits its turn: never while she is answering you, a sheet is
// open, you paused or went back, or the line on screen has not had its time. Then it comes in as a new turn.
const waiting = useRef({ count: 0, busy: false, sheet: false }), admit = useRef(() => {});
waiting.current = { count: incoming.length, busy, sheet: log || full };
admit.current = () => { const add = incoming.filter(m => !live.current.some(k => k.id === m.id)); onAdmit?.(incoming.map(m => m.id)); if (add.length) change([...live.current, ...add]); };
function stop() { gate.current.cancel(); if (replyLive.current) setInterrupted({ text: replyLive.current, turn: turnLive.current }); replyLive.current = ''; setBusy(false); setReply(''); onPresence('停下来了'); change(live.current.map(m => m.status === 'pending' ? { ...m, status: 'cancelled' } : m)); }
function endVoice() { stop(); voiceController.current?.abort(); setVoice(false); onVoice(false); onPresence('在你面前'); }
@@ -119,8 +127,10 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
let raf = 0;
const c = clock.current, away = () => c.pause();
const tick = (now: number) => {
const { pages: list, cursor: at, flow: on } = reading.current;
if (c.tick(now, list[at], on && !held.current.size && !document.hidden) && at < list.length - 1) { how.current = 'advance'; setAnchor(anchorOf(list, at + 1) || START); }
const { pages: list, cursor: at, flow: on } = reading.current, w = waiting.current;
const running = on && !held.current.size && !document.hidden, done = c.tick(now, list[at], running);
if (done && at < list.length - 1) { how.current = 'advance'; setAnchor(anchorOf(list, at + 1) || START); }
else if (w.count && !w.busy && !w.sheet && running && at >= list.length - 1 && (done || !list.length)) { w.count = 0; admit.current(); }
if (meter.current) meter.current.style.transform = `scaleX(${c.progress})`;
raf = requestAnimationFrame(tick);
};
@@ -214,7 +224,9 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
}
const setVoiceMode = () => { if (real) { setNotice('语音尚未接通,文字仍可使用。'); return; } if (voice) { endVoice(); return; } setPermission('mic'); };
const lastUser = [...view.messages].reverse().find(m => m.role === 'user');
const status = notice || flash || (busy ? (reply ? `${name}正在回应…` : `${name}在想…`) : !pages.length ? '你们还没有说过话。' : real ? '' : '演示回复 · 未连接真实模型');
// Only says why her new words wait when it is your own reading that holds them; otherwise they simply come in.
const queued = incoming.length && !busy ? (!flow ? `${name}刚又说了一句 · 继续后呈现` : !atEnd ? `${name}刚又说了一句 · 读完这段呈现` : '') : '';
const status = notice || flash || (busy ? (reply ? `${name}正在回应…` : `${name}在想…`) : queued || (!pages.length ? '你们还没有说过话。' : real ? '' : '演示回复 · 未连接真实模型'));
const unread = pages.length - 1 - cursor, single = pages.length <= 1 && !busy, fullMessage = page?.message;
const textarea = useRef<HTMLTextAreaElement>(null);
useLayoutEffect(() => { const t = textarea.current; if (!t) return; t.style.height = 'auto'; t.style.height = Math.min(t.scrollHeight, 88) + 'px'; }, [draft]);